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
;
138 mode
.c_oflag
|= OPOST
;
140 mode
.c_iflag
&= ~ICRNL
;
141 mode
.c_lflag
&= ~(ISIG
| ICANON
);
142 mode
.c_oflag
&= ~OPOST
;
143 /* Solaris sets these to unhelpful values */
145 mode
.c_cc
[VTIME
] = 0;
146 /* FIXME: perhaps what we do with IXON/IXOFF should be an
147 * argument to ldisc_update(), to allow implementation of SSH-2
148 * "xon-xoff" and Rlogin's equivalent? */
149 mode
.c_iflag
&= ~IXON
;
150 mode
.c_iflag
&= ~IXOFF
;
153 tcsetattr(0, TCSANOW
, &mode
);
156 /* Helper function to extract a special character from a termios. */
157 static char *get_ttychar(struct termios
*t
, int index
)
159 cc_t c
= t
->c_cc
[index
];
160 #if defined(_POSIX_VDISABLE)
161 if (c
== _POSIX_VDISABLE
)
162 return dupprintf("");
164 return dupprintf("^<%d>", c
);
167 char *get_ttymode(void *frontend
, const char *mode
)
170 * Propagate appropriate terminal modes from the local terminal,
173 if (!local_tty
) return NULL
;
175 #define GET_CHAR(ourname, uxname) \
177 if (strcmp(mode, ourname) == 0) \
178 return get_ttychar(&orig_termios, uxname); \
180 #define GET_BOOL(ourname, uxname, uxmemb, transform) \
182 if (strcmp(mode, ourname) == 0) { \
183 int b = (orig_termios.uxmemb & uxname) != 0; \
185 return dupprintf("%d", b); \
190 * Modes that want to be the same on all terminal devices involved.
192 /* All the special characters supported by SSH */
194 GET_CHAR("INTR", VINTR
);
197 GET_CHAR("QUIT", VQUIT
);
200 GET_CHAR("ERASE", VERASE
);
203 GET_CHAR("KILL", VKILL
);
206 GET_CHAR("EOF", VEOF
);
209 GET_CHAR("EOL", VEOL
);
212 GET_CHAR("EOL2", VEOL2
);
215 GET_CHAR("START", VSTART
);
218 GET_CHAR("STOP", VSTOP
);
221 GET_CHAR("SUSP", VSUSP
);
224 GET_CHAR("DSUSP", VDSUSP
);
226 #if defined(VREPRINT)
227 GET_CHAR("REPRINT", VREPRINT
);
230 GET_CHAR("WERASE", VWERASE
);
233 GET_CHAR("LNEXT", VLNEXT
);
236 GET_CHAR("FLUSH", VFLUSH
);
239 GET_CHAR("SWTCH", VSWTCH
);
242 GET_CHAR("STATUS", VSTATUS
);
244 #if defined(VDISCARD)
245 GET_CHAR("DISCARD", VDISCARD
);
247 /* Modes that "configure" other major modes. These should probably be
248 * considered as user preferences. */
249 /* Configuration of ICANON */
251 GET_BOOL("ECHOK", ECHOK
, c_lflag
, );
254 GET_BOOL("ECHOKE", ECHOKE
, c_lflag
, );
257 GET_BOOL("ECHOE", ECHOE
, c_lflag
, );
260 GET_BOOL("ECHONL", ECHONL
, c_lflag
, );
263 GET_BOOL("XCASE", XCASE
, c_lflag
, );
265 /* Configuration of ECHO */
267 GET_BOOL("ECHOCTL", ECHOCTL
, c_lflag
, );
269 /* Configuration of IXON/IXOFF */
271 GET_BOOL("IXANY", IXANY
, c_iflag
, );
273 /* Configuration of OPOST */
275 GET_BOOL("OLCUC", OLCUC
, c_oflag
, );
278 GET_BOOL("ONLCR", ONLCR
, c_oflag
, );
281 GET_BOOL("OCRNL", OCRNL
, c_oflag
, );
284 GET_BOOL("ONOCR", ONOCR
, c_oflag
, );
287 GET_BOOL("ONLRET", ONLRET
, c_oflag
, );
291 * Modes that want to be set in only one place, and that we have
295 GET_BOOL("ISIG", ISIG
, c_lflag
, );
298 GET_BOOL("ICANON", ICANON
, c_lflag
, );
301 GET_BOOL("ECHO", ECHO
, c_lflag
, );
304 GET_BOOL("IXON", IXON
, c_iflag
, );
307 GET_BOOL("IXOFF", IXOFF
, c_iflag
, );
310 GET_BOOL("OPOST", OPOST
, c_oflag
, );
314 * We do not propagate the following modes:
315 * - Parity/serial settings, which are a local affair and don't
316 * make sense propagated over SSH's 8-bit byte-stream.
317 * IGNPAR PARMRK INPCK CS7 CS8 PARENB PARODD
318 * - Things that want to be enabled in one place that we don't
323 * - Things I don't know what to do with. (FIXME)
324 * ISTRIP IMAXBEL NOFLSH TOSTOP IEXTEN
331 /* Fall through to here for unrecognised names, or ones that are
332 * unsupported on this platform */
336 void cleanup_termios(void)
339 tcsetattr(0, TCSANOW
, &orig_termios
);
342 bufchain stdout_data
, stderr_data
;
344 void try_output(int is_stderr
)
346 bufchain
*chain
= (is_stderr ?
&stderr_data
: &stdout_data
);
347 int fd
= (is_stderr ?
2 : 1);
351 if (bufchain_size(chain
) == 0)
354 bufchain_prefix(chain
, &senddata
, &sendlen
);
355 ret
= write(fd
, senddata
, sendlen
);
357 bufchain_consume(chain
, ret
);
359 perror(is_stderr ?
"stderr: write" : "stdout: write");
364 int from_backend(void *frontend_handle
, int is_stderr
,
365 const char *data
, int len
)
370 bufchain_add(&stderr_data
, data
, len
);
373 bufchain_add(&stdout_data
, data
, len
);
377 osize
= bufchain_size(&stdout_data
);
378 esize
= bufchain_size(&stderr_data
);
380 return osize
+ esize
;
385 void sigwinch(int signum
)
387 write(signalpipe
[1], "x", 1);
391 * In Plink our selects are synchronous, so these functions are
394 int uxsel_input_add(int fd
, int rwx
) { return 0; }
395 void uxsel_input_remove(int id
) { }
398 * Short description of parameters.
400 static void usage(void)
402 printf("PuTTY Link: command-line connection utility\n");
404 printf("Usage: plink [options] [user@]host [command]\n");
405 printf(" (\"host\" can also be a PuTTY saved session name)\n");
406 printf("Options:\n");
407 printf(" -V print version information and exit\n");
408 printf(" -pgpfp print PGP key fingerprints and exit\n");
409 printf(" -v show verbose messages\n");
410 printf(" -load sessname Load settings from saved session\n");
411 printf(" -ssh -telnet -rlogin -raw\n");
412 printf(" force use of a particular protocol\n");
413 printf(" -P port connect to specified port\n");
414 printf(" -l user connect with specified username\n");
415 printf(" -batch disable all interactive prompts\n");
416 printf("The following options only apply to SSH connections:\n");
417 printf(" -pw passw login with specified password\n");
418 printf(" -D [listen-IP:]listen-port\n");
419 printf(" Dynamic SOCKS-based port forwarding\n");
420 printf(" -L [listen-IP:]listen-port:host:port\n");
421 printf(" Forward local port to remote address\n");
422 printf(" -R [listen-IP:]listen-port:host:port\n");
423 printf(" Forward remote port to local address\n");
424 printf(" -X -x enable / disable X11 forwarding\n");
425 printf(" -A -a enable / disable agent forwarding\n");
426 printf(" -t -T enable / disable pty allocation\n");
427 printf(" -1 -2 force use of particular protocol version\n");
428 printf(" -4 -6 force use of IPv4 or IPv6\n");
429 printf(" -C enable compression\n");
430 printf(" -i key private key file for authentication\n");
431 printf(" -m file read remote command(s) from file\n");
432 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
433 printf(" -N don't start a shell/command (SSH-2 only)\n");
437 static void version(void)
439 printf("plink: %s\n", ver
);
443 int main(int argc
, char **argv
)
449 int i
, fdcount
, fdsize
, fdstate
;
453 int use_subsystem
= 0;
454 void *ldisc
, *logctx
;
457 ssh_get_line
= console_get_line
;
460 fdcount
= fdsize
= 0;
462 * Initialise port and protocol to sensible defaults. (These
463 * will be overridden by more or less anything.)
465 default_protocol
= PROT_SSH
;
470 * Process the command line.
472 do_defaults(NULL
, &cfg
);
473 loaded_session
= FALSE
;
474 default_protocol
= cfg
.protocol
;
475 default_port
= cfg
.port
;
479 * Override the default protocol if PLINK_PROTOCOL is set.
481 char *p
= getenv("PLINK_PROTOCOL");
484 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
485 if (!strcmp(backends
[i
].name
, p
)) {
486 default_protocol
= cfg
.protocol
= backends
[i
].protocol
;
487 default_port
= cfg
.port
=
488 backends
[i
].backend
->default_port
;
497 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
),
501 "plink: option \"%s\" requires an argument\n", p
);
503 } else if (ret
== 2) {
505 } else if (ret
== 1) {
507 } else if (!strcmp(p
, "-batch")) {
508 console_batch_mode
= 1;
509 } else if (!strcmp(p
, "-s")) {
510 /* Save status to write to cfg later. */
512 } else if (!strcmp(p
, "-V")) {
514 } else if (!strcmp(p
, "-pgpfp")) {
517 } else if (!strcmp(p
, "-o")) {
520 "plink: option \"-o\" requires an argument\n");
524 provide_xrm_string(*++argv
);
527 fprintf(stderr
, "plink: unknown option \"%s\"\n", p
);
534 do_defaults(NULL
, &cfg
);
537 * If the hostname starts with "telnet:", set the
538 * protocol to Telnet and process the string as a
541 if (!strncmp(q
, "telnet:", 7)) {
545 if (q
[0] == '/' && q
[1] == '/')
547 cfg
.protocol
= PROT_TELNET
;
549 while (*p
&& *p
!= ':' && *p
!= '/')
558 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
559 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
561 char *r
, *user
, *host
;
563 * Before we process the [user@]host string, we
564 * first check for the presence of a protocol
565 * prefix (a protocol name followed by ",").
570 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
571 j
= strlen(backends
[i
].name
);
573 !memcmp(backends
[i
].name
, p
, j
)) {
574 default_protocol
= cfg
.protocol
=
575 backends
[i
].protocol
;
577 backends
[i
].backend
->default_port
;
585 * A nonzero length string followed by an @ is treated
586 * as a username. (We discount an _initial_ @.) The
587 * rest of the string (or the whole string if no @)
588 * is treated as a session name and/or hostname.
592 p
++, r
= NULL
; /* discount initial @ */
597 user
= NULL
, host
= p
;
601 * Now attempt to load a saved session with the
602 * same name as the hostname.
606 do_defaults(host
, &cfg2
);
607 if (loaded_session
|| cfg2
.host
[0] == '\0') {
608 /* No settings for this host; use defaults */
609 /* (or session was already loaded with -load) */
610 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
611 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
612 cfg
.port
= default_port
;
619 /* Patch in specified username. */
620 strncpy(cfg
.username
, user
,
621 sizeof(cfg
.username
) - 1);
622 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
629 cmdlen
= cmdsize
= 0;
634 if (cmdlen
>= cmdsize
) {
635 cmdsize
= cmdlen
+ 512;
636 command
= sresize(command
, cmdsize
, char);
638 command
[cmdlen
++]=*p
++;
640 if (cmdlen
>= cmdsize
) {
641 cmdsize
= cmdlen
+ 512;
642 command
= sresize(command
, cmdsize
, char);
644 command
[cmdlen
++]=' '; /* always add trailing space */
645 if (--argc
) p
= *++argv
;
647 if (cmdlen
) command
[--cmdlen
]='\0';
648 /* change trailing blank to NUL */
649 cfg
.remote_cmd_ptr
= command
;
650 cfg
.remote_cmd_ptr2
= NULL
;
651 cfg
.nopty
= TRUE
; /* command => no terminal */
653 break; /* done with cmdline */
666 * Trim leading whitespace off the hostname if it's there.
669 int space
= strspn(cfg
.host
, " \t");
670 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
673 /* See if host is of the form user@host */
674 if (cfg
.host
[0] != '\0') {
675 char *atsign
= strrchr(cfg
.host
, '@');
676 /* Make sure we're not overflowing the user field */
678 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
679 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
680 cfg
.username
[atsign
- cfg
.host
] = '\0';
682 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
687 * Perform command-line overrides on session configuration.
689 cmdline_run_saved(&cfg
);
692 * Apply subsystem status.
695 cfg
.ssh_subsys
= TRUE
;
698 * Trim a colon suffix off the hostname if it's there.
700 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
703 * Remove any remaining whitespace from the hostname.
707 while (cfg
.host
[p2
] != '\0') {
708 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
709 cfg
.host
[p1
] = cfg
.host
[p2
];
717 if (!cfg
.remote_cmd_ptr
&& !*cfg
.remote_cmd
)
718 flags
|= FLAG_INTERACTIVE
;
721 * Select protocol. This is farmed out into a table in a
722 * separate file to enable an ssh-free variant.
727 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
728 if (backends
[i
].protocol
== cfg
.protocol
) {
729 back
= backends
[i
].backend
;
734 "Internal fault: Unsupported protocol found\n");
742 if (portnumber
!= -1)
743 cfg
.port
= portnumber
;
746 * Set up the pipe we'll use to tell us about SIGWINCH.
748 if (pipe(signalpipe
) < 0) {
752 putty_signal(SIGWINCH
, sigwinch
);
758 * Start up the connection.
760 logctx
= log_init(NULL
, &cfg
);
761 console_provide_logctx(logctx
);
765 /* nodelay is only useful if stdin is a terminal device */
766 int nodelay
= cfg
.tcp_nodelay
&& isatty(0);
768 error
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
,
769 &realhost
, nodelay
, cfg
.tcp_keepalives
);
771 fprintf(stderr
, "Unable to open connection:\n%s\n", error
);
774 back
->provide_logctx(backhandle
, logctx
);
775 ldisc
= ldisc_create(&cfg
, NULL
, back
, backhandle
, NULL
);
781 * Set up the initial console mode. We don't care if this call
782 * fails, because we know we aren't necessarily running in a
785 local_tty
= (tcgetattr(0, &orig_termios
) == 0);
786 atexit(cleanup_termios
);
787 ldisc_update(NULL
, 1, 1);
789 now
= GETTICKCOUNT();
792 fd_set rset
, wset
, xset
;
802 FD_SET_MAX(signalpipe
[0], maxfd
, rset
);
804 if (connopen
&& !sending
&&
805 back
->socket(backhandle
) != NULL
&&
806 back
->sendok(backhandle
) &&
807 back
->sendbuffer(backhandle
) < MAX_STDIN_BACKLOG
) {
808 /* If we're OK to send, then try to read from stdin. */
809 FD_SET_MAX(0, maxfd
, rset
);
812 if (bufchain_size(&stdout_data
) > 0) {
813 /* If we have data for stdout, try to write to stdout. */
814 FD_SET_MAX(1, maxfd
, wset
);
817 if (bufchain_size(&stderr_data
) > 0) {
818 /* If we have data for stderr, try to write to stderr. */
819 FD_SET_MAX(2, maxfd
, wset
);
822 /* Count the currently active fds. */
824 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
825 fd
= next_fd(&fdstate
, &rwx
)) i
++;
827 /* Expand the fdlist buffer if necessary. */
830 fdlist
= sresize(fdlist
, fdsize
, int);
834 * Add all currently open fds to the select sets, and store
835 * them in fdlist as well.
838 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
839 fd
= next_fd(&fdstate
, &rwx
)) {
840 fdlist
[fdcount
++] = fd
;
842 FD_SET_MAX(fd
, maxfd
, rset
);
844 FD_SET_MAX(fd
, maxfd
, wset
);
846 FD_SET_MAX(fd
, maxfd
, xset
);
851 struct timeval tv
, *ptv
;
853 if (run_timers(now
, &next
)) {
854 ticks
= next
- GETTICKCOUNT();
855 if (ticks
< 0) ticks
= 0; /* just in case */
856 tv
.tv_sec
= ticks
/ 1000;
857 tv
.tv_usec
= ticks
% 1000 * 1000;
862 ret
= select(maxfd
, &rset
, &wset
, &xset
, ptv
);
866 long newnow
= GETTICKCOUNT();
868 * Check to see whether the system clock has
869 * changed massively during the select.
871 if (newnow
- now
< 0 || newnow
- now
> next
- now
) {
873 * If so, look at the elapsed time in the
874 * select and use it to compute a new
877 long othernow
= now
+ tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
878 /* So we'd like GETTICKCOUNT to have returned othernow,
879 * but instead it return newnow. Hence ... */
880 tickcount_offset
+= othernow
- newnow
;
886 } while (ret
< 0 && errno
== EINTR
);
893 for (i
= 0; i
< fdcount
; i
++) {
896 * We must process exceptional notifications before
897 * ordinary readability ones, or we may go straight
898 * past the urgent marker.
900 if (FD_ISSET(fd
, &xset
))
901 select_result(fd
, 4);
902 if (FD_ISSET(fd
, &rset
))
903 select_result(fd
, 1);
904 if (FD_ISSET(fd
, &wset
))
905 select_result(fd
, 2);
908 if (FD_ISSET(signalpipe
[0], &rset
)) {
911 read(signalpipe
[0], c
, 1); /* ignore its value; it'll be `x' */
912 if (ioctl(0, TIOCGWINSZ
, (void *)&size
) >= 0)
913 back
->size(backhandle
, size
.ws_col
, size
.ws_row
);
916 if (FD_ISSET(0, &rset
)) {
920 if (connopen
&& back
->socket(backhandle
) != NULL
) {
921 ret
= read(0, buf
, sizeof(buf
));
923 perror("stdin: read");
925 } else if (ret
== 0) {
926 back
->special(backhandle
, TS_EOF
);
927 sending
= FALSE
; /* send nothing further after this */
929 back
->send(backhandle
, buf
, ret
);
934 if (FD_ISSET(1, &wset
)) {
938 if (FD_ISSET(2, &wset
)) {
942 if ((!connopen
|| back
->socket(backhandle
) == NULL
) &&
943 bufchain_size(&stdout_data
) == 0 &&
944 bufchain_size(&stderr_data
) == 0)
945 break; /* we closed the connection */
947 exitcode
= back
->exitcode(backhandle
);
949 fprintf(stderr
, "Remote process exit code unavailable\n");
950 exitcode
= 1; /* this is an error condition */
952 cleanup_exit(exitcode
);
953 return exitcode
; /* shouldn't happen, but placates gcc */