2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
15 #include <sys/ioctl.h>
16 #include <sys/select.h>
18 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
23 #define MAX_STDIN_BACKLOG 4096
25 void fatalbox(char *p
, ...)
28 fprintf(stderr
, "FATAL ERROR: ");
30 vfprintf(stderr
, p
, ap
);
35 void modalfatalbox(char *p
, ...)
38 fprintf(stderr
, "FATAL ERROR: ");
40 vfprintf(stderr
, p
, ap
);
45 void connection_fatal(void *frontend
, char *p
, ...)
48 fprintf(stderr
, "FATAL ERROR: ");
50 vfprintf(stderr
, p
, ap
);
55 void cmdline_error(char *p
, ...)
58 fprintf(stderr
, "plink: ");
60 vfprintf(stderr
, p
, ap
);
66 struct termios orig_termios
;
69 static void *backhandle
;
73 * Default settings that are specific to pterm.
75 char *platform_default_s(const char *name
)
77 if (!strcmp(name
, "TermType"))
78 return dupstr(getenv("TERM"));
79 if (!strcmp(name
, "UserName"))
80 return get_username();
84 int platform_default_i(const char *name
, int def
)
86 if (!strcmp(name
, "TermWidth") ||
87 !strcmp(name
, "TermHeight")) {
89 if (ioctl(0, TIOCGWINSZ
, (void *)&size
) >= 0)
90 return (!strcmp(name
, "TermWidth") ? size
.ws_col
: size
.ws_row
);
95 FontSpec
platform_default_fontspec(const char *name
)
102 Filename
platform_default_filename(const char *name
)
105 if (!strcmp(name
, "LogFileName"))
106 strcpy(ret
.path
, "putty.log");
112 char *x_get_default(const char *key
)
114 return NULL
; /* this is a stub */
116 int term_ldisc(Terminal
*term
, int mode
)
120 void ldisc_update(void *frontend
, int echo
, int edit
)
122 /* Update stdin read mode to reflect changes in line discipline. */
128 mode
.c_lflag
|= ECHO
;
130 mode
.c_lflag
&= ~ECHO
;
133 mode
.c_iflag
|= ICRNL
;
134 mode
.c_lflag
|= ISIG
| ICANON
;
136 mode
.c_iflag
&= ~ICRNL
;
137 mode
.c_lflag
&= ~(ISIG
| ICANON
);
139 mode
.c_cc
[VTIME
] = 0;
142 tcsetattr(0, TCSANOW
, &mode
);
145 void cleanup_termios(void)
147 tcsetattr(0, TCSANOW
, &orig_termios
);
150 bufchain stdout_data
, stderr_data
;
152 void try_output(int is_stderr
)
154 bufchain
*chain
= (is_stderr ?
&stderr_data
: &stdout_data
);
155 int fd
= (is_stderr ?
2 : 1);
159 if (bufchain_size(chain
) == 0)
162 bufchain_prefix(chain
, &senddata
, &sendlen
);
163 ret
= write(fd
, senddata
, sendlen
);
165 bufchain_consume(chain
, ret
);
167 perror(is_stderr ?
"stderr: write" : "stdout: write");
172 int from_backend(void *frontend_handle
, int is_stderr
,
173 const char *data
, int len
)
178 bufchain_add(&stderr_data
, data
, len
);
181 bufchain_add(&stdout_data
, data
, len
);
185 osize
= bufchain_size(&stdout_data
);
186 esize
= bufchain_size(&stderr_data
);
188 return osize
+ esize
;
193 void sigwinch(int signum
)
195 write(signalpipe
[1], "x", 1);
199 * In Plink our selects are synchronous, so these functions are
202 int uxsel_input_add(int fd
, int rwx
) { return 0; }
203 void uxsel_input_remove(int id
) { }
206 * Short description of parameters.
208 static void usage(void)
210 printf("PuTTY Link: command-line connection utility\n");
212 printf("Usage: plink [options] [user@]host [command]\n");
213 printf(" (\"host\" can also be a PuTTY saved session name)\n");
214 printf("Options:\n");
215 printf(" -V print version information\n");
216 printf(" -v show verbose messages\n");
217 printf(" -load sessname Load settings from saved session\n");
218 printf(" -ssh -telnet -rlogin -raw\n");
219 printf(" force use of a particular protocol\n");
220 printf(" -P port connect to specified port\n");
221 printf(" -l user connect with specified username\n");
222 printf(" -batch disable all interactive prompts\n");
223 printf("The following options only apply to SSH connections:\n");
224 printf(" -pw passw login with specified password\n");
225 printf(" -D [listen-IP:]listen-port\n");
226 printf(" Dynamic SOCKS-based port forwarding\n");
227 printf(" -L [listen-IP:]listen-port:host:port\n");
228 printf(" Forward local port to remote address\n");
229 printf(" -R [listen-IP:]listen-port:host:port\n");
230 printf(" Forward remote port to local address\n");
231 printf(" -X -x enable / disable X11 forwarding\n");
232 printf(" -A -a enable / disable agent forwarding\n");
233 printf(" -t -T enable / disable pty allocation\n");
234 printf(" -1 -2 force use of particular protocol version\n");
235 printf(" -4 -6 force use of IPv4 or IPv6\n");
236 printf(" -C enable compression\n");
237 printf(" -i key private key file for authentication\n");
238 printf(" -m file read remote command(s) from file\n");
239 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
240 printf(" -N don't start a shell/command (SSH-2 only)\n");
244 static void version(void)
246 printf("plink: %s\n", ver
);
250 int main(int argc
, char **argv
)
256 int i
, fdcount
, fdsize
, fdstate
;
260 int use_subsystem
= 0;
261 void *ldisc
, *logctx
;
264 ssh_get_line
= console_get_line
;
267 fdcount
= fdsize
= 0;
269 * Initialise port and protocol to sensible defaults. (These
270 * will be overridden by more or less anything.)
272 default_protocol
= PROT_SSH
;
277 * Process the command line.
279 do_defaults(NULL
, &cfg
);
280 loaded_session
= FALSE
;
281 default_protocol
= cfg
.protocol
;
282 default_port
= cfg
.port
;
286 * Override the default protocol if PLINK_PROTOCOL is set.
288 char *p
= getenv("PLINK_PROTOCOL");
291 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
292 if (!strcmp(backends
[i
].name
, p
)) {
293 default_protocol
= cfg
.protocol
= backends
[i
].protocol
;
294 default_port
= cfg
.port
=
295 backends
[i
].backend
->default_port
;
304 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
),
308 "plink: option \"%s\" requires an argument\n", p
);
310 } else if (ret
== 2) {
312 } else if (ret
== 1) {
314 } else if (!strcmp(p
, "-batch")) {
315 console_batch_mode
= 1;
316 } else if (!strcmp(p
, "-s")) {
317 /* Save status to write to cfg later. */
319 } else if (!strcmp(p
, "-V")) {
321 } else if (!strcmp(p
, "-o")) {
324 "plink: option \"-o\" requires an argument\n");
328 provide_xrm_string(*++argv
);
331 fprintf(stderr
, "plink: unknown option \"%s\"\n", p
);
338 do_defaults(NULL
, &cfg
);
341 * If the hostname starts with "telnet:", set the
342 * protocol to Telnet and process the string as a
345 if (!strncmp(q
, "telnet:", 7)) {
349 if (q
[0] == '/' && q
[1] == '/')
351 cfg
.protocol
= PROT_TELNET
;
353 while (*p
&& *p
!= ':' && *p
!= '/')
362 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
363 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
365 char *r
, *user
, *host
;
367 * Before we process the [user@]host string, we
368 * first check for the presence of a protocol
369 * prefix (a protocol name followed by ",").
374 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
375 j
= strlen(backends
[i
].name
);
377 !memcmp(backends
[i
].name
, p
, j
)) {
378 default_protocol
= cfg
.protocol
=
379 backends
[i
].protocol
;
381 backends
[i
].backend
->default_port
;
389 * A nonzero length string followed by an @ is treated
390 * as a username. (We discount an _initial_ @.) The
391 * rest of the string (or the whole string if no @)
392 * is treated as a session name and/or hostname.
396 p
++, r
= NULL
; /* discount initial @ */
401 user
= NULL
, host
= p
;
405 * Now attempt to load a saved session with the
406 * same name as the hostname.
410 do_defaults(host
, &cfg2
);
411 if (loaded_session
|| cfg2
.host
[0] == '\0') {
412 /* No settings for this host; use defaults */
413 /* (or session was already loaded with -load) */
414 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
415 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
416 cfg
.port
= default_port
;
423 /* Patch in specified username. */
424 strncpy(cfg
.username
, user
,
425 sizeof(cfg
.username
) - 1);
426 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
433 cmdlen
= cmdsize
= 0;
438 if (cmdlen
>= cmdsize
) {
439 cmdsize
= cmdlen
+ 512;
440 command
= sresize(command
, cmdsize
, char);
442 command
[cmdlen
++]=*p
++;
444 if (cmdlen
>= cmdsize
) {
445 cmdsize
= cmdlen
+ 512;
446 command
= sresize(command
, cmdsize
, char);
448 command
[cmdlen
++]=' '; /* always add trailing space */
449 if (--argc
) p
= *++argv
;
451 if (cmdlen
) command
[--cmdlen
]='\0';
452 /* change trailing blank to NUL */
453 cfg
.remote_cmd_ptr
= command
;
454 cfg
.remote_cmd_ptr2
= NULL
;
455 cfg
.nopty
= TRUE
; /* command => no terminal */
457 break; /* done with cmdline */
470 * Trim leading whitespace off the hostname if it's there.
473 int space
= strspn(cfg
.host
, " \t");
474 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
477 /* See if host is of the form user@host */
478 if (cfg
.host
[0] != '\0') {
479 char *atsign
= strrchr(cfg
.host
, '@');
480 /* Make sure we're not overflowing the user field */
482 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
483 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
484 cfg
.username
[atsign
- cfg
.host
] = '\0';
486 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
491 * Perform command-line overrides on session configuration.
493 cmdline_run_saved(&cfg
);
496 * Apply subsystem status.
499 cfg
.ssh_subsys
= TRUE
;
502 * Trim a colon suffix off the hostname if it's there.
504 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
507 * Remove any remaining whitespace from the hostname.
511 while (cfg
.host
[p2
] != '\0') {
512 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
513 cfg
.host
[p1
] = cfg
.host
[p2
];
521 if (!cfg
.remote_cmd_ptr
&& !*cfg
.remote_cmd
)
522 flags
|= FLAG_INTERACTIVE
;
525 * Select protocol. This is farmed out into a table in a
526 * separate file to enable an ssh-free variant.
531 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
532 if (backends
[i
].protocol
== cfg
.protocol
) {
533 back
= backends
[i
].backend
;
538 "Internal fault: Unsupported protocol found\n");
546 if (portnumber
!= -1)
547 cfg
.port
= portnumber
;
550 * Set up the pipe we'll use to tell us about SIGWINCH.
552 if (pipe(signalpipe
) < 0) {
556 putty_signal(SIGWINCH
, sigwinch
);
562 * Start up the connection.
564 logctx
= log_init(NULL
, &cfg
);
565 console_provide_logctx(logctx
);
569 /* nodelay is only useful if stdin is a terminal device */
570 int nodelay
= cfg
.tcp_nodelay
&& isatty(0);
572 error
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
,
573 &realhost
, nodelay
, cfg
.tcp_keepalives
);
575 fprintf(stderr
, "Unable to open connection:\n%s\n", error
);
578 back
->provide_logctx(backhandle
, logctx
);
579 ldisc
= ldisc_create(&cfg
, NULL
, back
, backhandle
, NULL
);
585 * Set up the initial console mode. We don't care if this call
586 * fails, because we know we aren't necessarily running in a
589 tcgetattr(0, &orig_termios
);
590 atexit(cleanup_termios
);
591 ldisc_update(NULL
, 1, 1);
593 now
= GETTICKCOUNT();
596 fd_set rset
, wset
, xset
;
606 FD_SET_MAX(signalpipe
[0], maxfd
, rset
);
608 if (connopen
&& !sending
&&
609 back
->socket(backhandle
) != NULL
&&
610 back
->sendok(backhandle
) &&
611 back
->sendbuffer(backhandle
) < MAX_STDIN_BACKLOG
) {
612 /* If we're OK to send, then try to read from stdin. */
613 FD_SET_MAX(0, maxfd
, rset
);
616 if (bufchain_size(&stdout_data
) > 0) {
617 /* If we have data for stdout, try to write to stdout. */
618 FD_SET_MAX(1, maxfd
, wset
);
621 if (bufchain_size(&stderr_data
) > 0) {
622 /* If we have data for stderr, try to write to stderr. */
623 FD_SET_MAX(2, maxfd
, wset
);
626 /* Count the currently active fds. */
628 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
629 fd
= next_fd(&fdstate
, &rwx
)) i
++;
631 /* Expand the fdlist buffer if necessary. */
634 fdlist
= sresize(fdlist
, fdsize
, int);
638 * Add all currently open fds to the select sets, and store
639 * them in fdlist as well.
642 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
643 fd
= next_fd(&fdstate
, &rwx
)) {
644 fdlist
[fdcount
++] = fd
;
646 FD_SET_MAX(fd
, maxfd
, rset
);
648 FD_SET_MAX(fd
, maxfd
, wset
);
650 FD_SET_MAX(fd
, maxfd
, xset
);
655 struct timeval tv
, *ptv
;
657 if (run_timers(now
, &next
)) {
658 ticks
= next
- GETTICKCOUNT();
659 if (ticks
< 0) ticks
= 0; /* just in case */
660 tv
.tv_sec
= ticks
/ 1000;
661 tv
.tv_usec
= ticks
% 1000 * 1000;
666 ret
= select(maxfd
, &rset
, &wset
, &xset
, ptv
);
670 now
= GETTICKCOUNT();
671 } while (ret
< 0 && errno
== EINTR
);
678 for (i
= 0; i
< fdcount
; i
++) {
681 * We must process exceptional notifications before
682 * ordinary readability ones, or we may go straight
683 * past the urgent marker.
685 if (FD_ISSET(fd
, &xset
))
686 select_result(fd
, 4);
687 if (FD_ISSET(fd
, &rset
))
688 select_result(fd
, 1);
689 if (FD_ISSET(fd
, &wset
))
690 select_result(fd
, 2);
693 if (FD_ISSET(signalpipe
[0], &rset
)) {
696 read(signalpipe
[0], c
, 1); /* ignore its value; it'll be `x' */
697 if (ioctl(0, TIOCGWINSZ
, (void *)&size
) >= 0)
698 back
->size(backhandle
, size
.ws_col
, size
.ws_row
);
701 if (FD_ISSET(0, &rset
)) {
705 if (connopen
&& back
->socket(backhandle
) != NULL
) {
706 ret
= read(0, buf
, sizeof(buf
));
708 perror("stdin: read");
710 } else if (ret
== 0) {
711 back
->special(backhandle
, TS_EOF
);
712 sending
= FALSE
; /* send nothing further after this */
714 back
->send(backhandle
, buf
, ret
);
719 if (FD_ISSET(1, &wset
)) {
723 if (FD_ISSET(2, &wset
)) {
727 if ((!connopen
|| back
->socket(backhandle
) == NULL
) &&
728 bufchain_size(&stdout_data
) == 0 &&
729 bufchain_size(&stderr_data
) == 0)
730 break; /* we closed the connection */
732 exitcode
= back
->exitcode(backhandle
);
734 fprintf(stderr
, "Remote process exit code unavailable\n");
735 exitcode
= 1; /* this is an error condition */
737 cleanup_exit(exitcode
);
738 return exitcode
; /* shouldn't happen, but placates gcc */