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 static int local_tty
= 0; /* do we have a local tty? */
67 static struct termios orig_termios
;
70 static void *backhandle
;
74 * Default settings that are specific to pterm.
76 char *platform_default_s(const char *name
)
78 if (!strcmp(name
, "TermType"))
79 return dupstr(getenv("TERM"));
80 if (!strcmp(name
, "UserName"))
81 return get_username();
85 int platform_default_i(const char *name
, int def
)
87 if (!strcmp(name
, "TermWidth") ||
88 !strcmp(name
, "TermHeight")) {
90 if (ioctl(0, TIOCGWINSZ
, (void *)&size
) >= 0)
91 return (!strcmp(name
, "TermWidth") ? size
.ws_col
: size
.ws_row
);
96 FontSpec
platform_default_fontspec(const char *name
)
103 Filename
platform_default_filename(const char *name
)
106 if (!strcmp(name
, "LogFileName"))
107 strcpy(ret
.path
, "putty.log");
113 char *x_get_default(const char *key
)
115 return NULL
; /* this is a stub */
117 int term_ldisc(Terminal
*term
, int mode
)
121 void ldisc_update(void *frontend
, int echo
, int edit
)
123 /* Update stdin read mode to reflect changes in line discipline. */
126 if (!local_tty
) return;
131 mode
.c_lflag
|= ECHO
;
133 mode
.c_lflag
&= ~ECHO
;
136 mode
.c_iflag
|= ICRNL
;
137 mode
.c_lflag
|= ISIG
| ICANON
;
139 mode
.c_iflag
&= ~ICRNL
;
140 mode
.c_lflag
&= ~(ISIG
| ICANON
);
141 /* Solaris sets these to unhelpful values */
143 mode
.c_cc
[VTIME
] = 0;
144 /* FIXME: perhaps what we do with IXON/IXOFF should be an
145 * argument to ldisc_update(), to allow implementation of SSH-2
146 * "xon-xoff" and Rlogin's equivalent? */
147 mode
.c_iflag
&= ~IXON
;
148 mode
.c_iflag
&= ~IXOFF
;
151 tcsetattr(0, TCSANOW
, &mode
);
154 /* Helper function to extract a special character from a termios. */
155 static char *get_ttychar(struct termios
*t
, int index
)
157 cc_t c
= t
->c_cc
[index
];
158 #if defined(_POSIX_VDISABLE)
159 if (c
== _POSIX_VDISABLE
)
160 return dupprintf("");
162 return dupprintf("^<%d>", c
);
165 char *get_ttymode(void *frontend
, const char *mode
)
168 * Propagate appropriate terminal modes from the local terminal,
171 if (!local_tty
) return NULL
;
173 #define GET_CHAR(ourname, uxname) \
175 if (strcmp(mode, ourname) == 0) \
176 return get_ttychar(&orig_termios, uxname); \
178 #define GET_BOOL(ourname, uxname, uxmemb, transform) \
180 if (strcmp(mode, ourname) == 0) { \
181 int b = (orig_termios.uxmemb & uxname) != 0; \
183 return dupprintf("%d", b); \
188 * Modes that want to be the same on all terminal devices involved.
190 /* All the special characters supported by SSH */
192 GET_CHAR("INTR", VINTR
);
195 GET_CHAR("QUIT", VQUIT
);
198 GET_CHAR("ERASE", VERASE
);
201 GET_CHAR("KILL", VKILL
);
204 GET_CHAR("EOF", VEOF
);
207 GET_CHAR("EOL", VEOL
);
210 GET_CHAR("EOL2", VEOL2
);
213 GET_CHAR("START", VSTART
);
216 GET_CHAR("STOP", VSTOP
);
219 GET_CHAR("SUSP", VSUSP
);
222 GET_CHAR("DSUSP", VDSUSP
);
224 #if defined(VREPRINT)
225 GET_CHAR("REPRINT", VREPRINT
);
228 GET_CHAR("WERASE", VWERASE
);
231 GET_CHAR("LNEXT", VLNEXT
);
234 GET_CHAR("FLUSH", VFLUSH
);
237 GET_CHAR("SWTCH", VSWTCH
);
240 GET_CHAR("STATUS", VSTATUS
);
242 #if defined(VDISCARD)
243 GET_CHAR("DISCARD", VDISCARD
);
245 /* Modes that "configure" other major modes. These should probably be
246 * considered as user preferences. */
247 /* Configuration of ICANON */
249 GET_BOOL("ECHOK", ECHOK
, c_lflag
, );
252 GET_BOOL("ECHOKE", ECHOKE
, c_lflag
, );
255 GET_BOOL("ECHOE", ECHOE
, c_lflag
, );
258 GET_BOOL("ECHONL", ECHONL
, c_lflag
, );
261 GET_BOOL("XCASE", XCASE
, c_lflag
, );
263 /* Configuration of ECHO */
265 GET_BOOL("ECHOCTL", ECHOCTL
, c_lflag
, );
267 /* Configuration of IXON/IXOFF */
269 GET_BOOL("IXANY", IXANY
, c_iflag
, );
273 * Modes that want to be set in only one place, and that we have
277 GET_BOOL("ISIG", ISIG
, c_lflag
, );
280 GET_BOOL("ICANON", ICANON
, c_lflag
, );
283 GET_BOOL("ECHO", ECHO
, c_lflag
, );
286 GET_BOOL("IXON", IXON
, c_iflag
, );
289 GET_BOOL("IXOFF", IXOFF
, c_iflag
, );
293 * We do not propagate the following modes:
294 * - Parity/serial settings, which are a local affair and don't
295 * make sense propagated over SSH's 8-bit byte-stream.
296 * IGNPAR PARMRK INPCK CS7 CS8 PARENB PARODD
297 * - Things that want to be enabled in one place that we don't
302 * - Things I don't know what to do with. (FIXME)
303 * ISTRIP IMAXBEL NOFLSH TOSTOP IEXTEN OPOST
304 * INLCR IGNCR ICRNL ONLCR OCRNL ONOCR ONLRET
310 /* Fall through to here for unrecognised names, or ones that are
311 * unsupported on this platform */
315 void cleanup_termios(void)
318 tcsetattr(0, TCSANOW
, &orig_termios
);
321 bufchain stdout_data
, stderr_data
;
323 void try_output(int is_stderr
)
325 bufchain
*chain
= (is_stderr ?
&stderr_data
: &stdout_data
);
326 int fd
= (is_stderr ?
2 : 1);
330 if (bufchain_size(chain
) == 0)
333 bufchain_prefix(chain
, &senddata
, &sendlen
);
334 ret
= write(fd
, senddata
, sendlen
);
336 bufchain_consume(chain
, ret
);
338 perror(is_stderr ?
"stderr: write" : "stdout: write");
343 int from_backend(void *frontend_handle
, int is_stderr
,
344 const char *data
, int len
)
349 bufchain_add(&stderr_data
, data
, len
);
352 bufchain_add(&stdout_data
, data
, len
);
356 osize
= bufchain_size(&stdout_data
);
357 esize
= bufchain_size(&stderr_data
);
359 return osize
+ esize
;
364 void sigwinch(int signum
)
366 write(signalpipe
[1], "x", 1);
370 * In Plink our selects are synchronous, so these functions are
373 int uxsel_input_add(int fd
, int rwx
) { return 0; }
374 void uxsel_input_remove(int id
) { }
377 * Short description of parameters.
379 static void usage(void)
381 printf("PuTTY Link: command-line connection utility\n");
383 printf("Usage: plink [options] [user@]host [command]\n");
384 printf(" (\"host\" can also be a PuTTY saved session name)\n");
385 printf("Options:\n");
386 printf(" -V print version information and exit\n");
387 printf(" -pgpfp print PGP key fingerprints and exit\n");
388 printf(" -v show verbose messages\n");
389 printf(" -load sessname Load settings from saved session\n");
390 printf(" -ssh -telnet -rlogin -raw\n");
391 printf(" force use of a particular protocol\n");
392 printf(" -P port connect to specified port\n");
393 printf(" -l user connect with specified username\n");
394 printf(" -batch disable all interactive prompts\n");
395 printf("The following options only apply to SSH connections:\n");
396 printf(" -pw passw login with specified password\n");
397 printf(" -D [listen-IP:]listen-port\n");
398 printf(" Dynamic SOCKS-based port forwarding\n");
399 printf(" -L [listen-IP:]listen-port:host:port\n");
400 printf(" Forward local port to remote address\n");
401 printf(" -R [listen-IP:]listen-port:host:port\n");
402 printf(" Forward remote port to local address\n");
403 printf(" -X -x enable / disable X11 forwarding\n");
404 printf(" -A -a enable / disable agent forwarding\n");
405 printf(" -t -T enable / disable pty allocation\n");
406 printf(" -1 -2 force use of particular protocol version\n");
407 printf(" -4 -6 force use of IPv4 or IPv6\n");
408 printf(" -C enable compression\n");
409 printf(" -i key private key file for authentication\n");
410 printf(" -m file read remote command(s) from file\n");
411 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
412 printf(" -N don't start a shell/command (SSH-2 only)\n");
416 static void version(void)
418 printf("plink: %s\n", ver
);
422 int main(int argc
, char **argv
)
428 int i
, fdcount
, fdsize
, fdstate
;
432 int use_subsystem
= 0;
433 void *ldisc
, *logctx
;
436 ssh_get_line
= console_get_line
;
439 fdcount
= fdsize
= 0;
441 * Initialise port and protocol to sensible defaults. (These
442 * will be overridden by more or less anything.)
444 default_protocol
= PROT_SSH
;
449 * Process the command line.
451 do_defaults(NULL
, &cfg
);
452 loaded_session
= FALSE
;
453 default_protocol
= cfg
.protocol
;
454 default_port
= cfg
.port
;
458 * Override the default protocol if PLINK_PROTOCOL is set.
460 char *p
= getenv("PLINK_PROTOCOL");
463 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
464 if (!strcmp(backends
[i
].name
, p
)) {
465 default_protocol
= cfg
.protocol
= backends
[i
].protocol
;
466 default_port
= cfg
.port
=
467 backends
[i
].backend
->default_port
;
476 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
),
480 "plink: option \"%s\" requires an argument\n", p
);
482 } else if (ret
== 2) {
484 } else if (ret
== 1) {
486 } else if (!strcmp(p
, "-batch")) {
487 console_batch_mode
= 1;
488 } else if (!strcmp(p
, "-s")) {
489 /* Save status to write to cfg later. */
491 } else if (!strcmp(p
, "-V")) {
493 } else if (!strcmp(p
, "-pgpfp")) {
496 } else if (!strcmp(p
, "-o")) {
499 "plink: option \"-o\" requires an argument\n");
503 provide_xrm_string(*++argv
);
506 fprintf(stderr
, "plink: unknown option \"%s\"\n", p
);
513 do_defaults(NULL
, &cfg
);
516 * If the hostname starts with "telnet:", set the
517 * protocol to Telnet and process the string as a
520 if (!strncmp(q
, "telnet:", 7)) {
524 if (q
[0] == '/' && q
[1] == '/')
526 cfg
.protocol
= PROT_TELNET
;
528 while (*p
&& *p
!= ':' && *p
!= '/')
537 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
538 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
540 char *r
, *user
, *host
;
542 * Before we process the [user@]host string, we
543 * first check for the presence of a protocol
544 * prefix (a protocol name followed by ",").
549 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
550 j
= strlen(backends
[i
].name
);
552 !memcmp(backends
[i
].name
, p
, j
)) {
553 default_protocol
= cfg
.protocol
=
554 backends
[i
].protocol
;
556 backends
[i
].backend
->default_port
;
564 * A nonzero length string followed by an @ is treated
565 * as a username. (We discount an _initial_ @.) The
566 * rest of the string (or the whole string if no @)
567 * is treated as a session name and/or hostname.
571 p
++, r
= NULL
; /* discount initial @ */
576 user
= NULL
, host
= p
;
580 * Now attempt to load a saved session with the
581 * same name as the hostname.
585 do_defaults(host
, &cfg2
);
586 if (loaded_session
|| cfg2
.host
[0] == '\0') {
587 /* No settings for this host; use defaults */
588 /* (or session was already loaded with -load) */
589 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
590 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
591 cfg
.port
= default_port
;
598 /* Patch in specified username. */
599 strncpy(cfg
.username
, user
,
600 sizeof(cfg
.username
) - 1);
601 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
608 cmdlen
= cmdsize
= 0;
613 if (cmdlen
>= cmdsize
) {
614 cmdsize
= cmdlen
+ 512;
615 command
= sresize(command
, cmdsize
, char);
617 command
[cmdlen
++]=*p
++;
619 if (cmdlen
>= cmdsize
) {
620 cmdsize
= cmdlen
+ 512;
621 command
= sresize(command
, cmdsize
, char);
623 command
[cmdlen
++]=' '; /* always add trailing space */
624 if (--argc
) p
= *++argv
;
626 if (cmdlen
) command
[--cmdlen
]='\0';
627 /* change trailing blank to NUL */
628 cfg
.remote_cmd_ptr
= command
;
629 cfg
.remote_cmd_ptr2
= NULL
;
630 cfg
.nopty
= TRUE
; /* command => no terminal */
632 break; /* done with cmdline */
645 * Trim leading whitespace off the hostname if it's there.
648 int space
= strspn(cfg
.host
, " \t");
649 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
652 /* See if host is of the form user@host */
653 if (cfg
.host
[0] != '\0') {
654 char *atsign
= strrchr(cfg
.host
, '@');
655 /* Make sure we're not overflowing the user field */
657 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
658 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
659 cfg
.username
[atsign
- cfg
.host
] = '\0';
661 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
666 * Perform command-line overrides on session configuration.
668 cmdline_run_saved(&cfg
);
671 * Apply subsystem status.
674 cfg
.ssh_subsys
= TRUE
;
677 * Trim a colon suffix off the hostname if it's there.
679 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
682 * Remove any remaining whitespace from the hostname.
686 while (cfg
.host
[p2
] != '\0') {
687 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
688 cfg
.host
[p1
] = cfg
.host
[p2
];
696 if (!cfg
.remote_cmd_ptr
&& !*cfg
.remote_cmd
)
697 flags
|= FLAG_INTERACTIVE
;
700 * Select protocol. This is farmed out into a table in a
701 * separate file to enable an ssh-free variant.
706 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
707 if (backends
[i
].protocol
== cfg
.protocol
) {
708 back
= backends
[i
].backend
;
713 "Internal fault: Unsupported protocol found\n");
721 if (portnumber
!= -1)
722 cfg
.port
= portnumber
;
725 * Set up the pipe we'll use to tell us about SIGWINCH.
727 if (pipe(signalpipe
) < 0) {
731 putty_signal(SIGWINCH
, sigwinch
);
737 * Start up the connection.
739 logctx
= log_init(NULL
, &cfg
);
740 console_provide_logctx(logctx
);
744 /* nodelay is only useful if stdin is a terminal device */
745 int nodelay
= cfg
.tcp_nodelay
&& isatty(0);
747 error
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
,
748 &realhost
, nodelay
, cfg
.tcp_keepalives
);
750 fprintf(stderr
, "Unable to open connection:\n%s\n", error
);
753 back
->provide_logctx(backhandle
, logctx
);
754 ldisc
= ldisc_create(&cfg
, NULL
, back
, backhandle
, NULL
);
760 * Set up the initial console mode. We don't care if this call
761 * fails, because we know we aren't necessarily running in a
764 local_tty
= (tcgetattr(0, &orig_termios
) == 0);
765 atexit(cleanup_termios
);
766 ldisc_update(NULL
, 1, 1);
768 now
= GETTICKCOUNT();
771 fd_set rset
, wset
, xset
;
781 FD_SET_MAX(signalpipe
[0], maxfd
, rset
);
783 if (connopen
&& !sending
&&
784 back
->socket(backhandle
) != NULL
&&
785 back
->sendok(backhandle
) &&
786 back
->sendbuffer(backhandle
) < MAX_STDIN_BACKLOG
) {
787 /* If we're OK to send, then try to read from stdin. */
788 FD_SET_MAX(0, maxfd
, rset
);
791 if (bufchain_size(&stdout_data
) > 0) {
792 /* If we have data for stdout, try to write to stdout. */
793 FD_SET_MAX(1, maxfd
, wset
);
796 if (bufchain_size(&stderr_data
) > 0) {
797 /* If we have data for stderr, try to write to stderr. */
798 FD_SET_MAX(2, maxfd
, wset
);
801 /* Count the currently active fds. */
803 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
804 fd
= next_fd(&fdstate
, &rwx
)) i
++;
806 /* Expand the fdlist buffer if necessary. */
809 fdlist
= sresize(fdlist
, fdsize
, int);
813 * Add all currently open fds to the select sets, and store
814 * them in fdlist as well.
817 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
818 fd
= next_fd(&fdstate
, &rwx
)) {
819 fdlist
[fdcount
++] = fd
;
821 FD_SET_MAX(fd
, maxfd
, rset
);
823 FD_SET_MAX(fd
, maxfd
, wset
);
825 FD_SET_MAX(fd
, maxfd
, xset
);
830 struct timeval tv
, *ptv
;
832 if (run_timers(now
, &next
)) {
833 ticks
= next
- GETTICKCOUNT();
834 if (ticks
< 0) ticks
= 0; /* just in case */
835 tv
.tv_sec
= ticks
/ 1000;
836 tv
.tv_usec
= ticks
% 1000 * 1000;
841 ret
= select(maxfd
, &rset
, &wset
, &xset
, ptv
);
845 long newnow
= GETTICKCOUNT();
847 * Check to see whether the system clock has
848 * changed massively during the select.
850 if (newnow
- now
< 0 || newnow
- now
> next
- now
) {
852 * If so, look at the elapsed time in the
853 * select and use it to compute a new
856 long othernow
= now
+ tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
857 /* So we'd like GETTICKCOUNT to have returned othernow,
858 * but instead it return newnow. Hence ... */
859 tickcount_offset
+= othernow
- newnow
;
865 } while (ret
< 0 && errno
== EINTR
);
872 for (i
= 0; i
< fdcount
; i
++) {
875 * We must process exceptional notifications before
876 * ordinary readability ones, or we may go straight
877 * past the urgent marker.
879 if (FD_ISSET(fd
, &xset
))
880 select_result(fd
, 4);
881 if (FD_ISSET(fd
, &rset
))
882 select_result(fd
, 1);
883 if (FD_ISSET(fd
, &wset
))
884 select_result(fd
, 2);
887 if (FD_ISSET(signalpipe
[0], &rset
)) {
890 read(signalpipe
[0], c
, 1); /* ignore its value; it'll be `x' */
891 if (ioctl(0, TIOCGWINSZ
, (void *)&size
) >= 0)
892 back
->size(backhandle
, size
.ws_col
, size
.ws_row
);
895 if (FD_ISSET(0, &rset
)) {
899 if (connopen
&& back
->socket(backhandle
) != NULL
) {
900 ret
= read(0, buf
, sizeof(buf
));
902 perror("stdin: read");
904 } else if (ret
== 0) {
905 back
->special(backhandle
, TS_EOF
);
906 sending
= FALSE
; /* send nothing further after this */
908 back
->send(backhandle
, buf
, ret
);
913 if (FD_ISSET(1, &wset
)) {
917 if (FD_ISSET(2, &wset
)) {
921 if ((!connopen
|| back
->socket(backhandle
) == NULL
) &&
922 bufchain_size(&stdout_data
) == 0 &&
923 bufchain_size(&stderr_data
) == 0)
924 break; /* we closed the connection */
926 exitcode
= back
->exitcode(backhandle
);
928 fprintf(stderr
, "Remote process exit code unavailable\n");
929 exitcode
= 1; /* this is an error condition */
931 cleanup_exit(exitcode
);
932 return exitcode
; /* shouldn't happen, but placates gcc */