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("ONLCR", ONLCR
, c_oflag
, );
278 GET_BOOL("OCRNL", OCRNL
, c_oflag
, );
281 GET_BOOL("ONOCR", ONOCR
, c_oflag
, );
284 GET_BOOL("ONLRET", ONLRET
, c_oflag
, );
288 * Modes that want to be set in only one place, and that we have
292 GET_BOOL("ISIG", ISIG
, c_lflag
, );
295 GET_BOOL("ICANON", ICANON
, c_lflag
, );
298 GET_BOOL("ECHO", ECHO
, c_lflag
, );
301 GET_BOOL("IXON", IXON
, c_iflag
, );
304 GET_BOOL("IXOFF", IXOFF
, c_iflag
, );
307 GET_BOOL("OPOST", OPOST
, c_oflag
, );
311 * We do not propagate the following modes:
312 * - Parity/serial settings, which are a local affair and don't
313 * make sense propagated over SSH's 8-bit byte-stream.
314 * IGNPAR PARMRK INPCK CS7 CS8 PARENB PARODD
315 * - Things that want to be enabled in one place that we don't
320 * - Things I don't know what to do with. (FIXME)
321 * ISTRIP IMAXBEL NOFLSH TOSTOP IEXTEN
328 /* Fall through to here for unrecognised names, or ones that are
329 * unsupported on this platform */
333 void cleanup_termios(void)
336 tcsetattr(0, TCSANOW
, &orig_termios
);
339 bufchain stdout_data
, stderr_data
;
341 void try_output(int is_stderr
)
343 bufchain
*chain
= (is_stderr ?
&stderr_data
: &stdout_data
);
344 int fd
= (is_stderr ?
2 : 1);
348 if (bufchain_size(chain
) == 0)
351 bufchain_prefix(chain
, &senddata
, &sendlen
);
352 ret
= write(fd
, senddata
, sendlen
);
354 bufchain_consume(chain
, ret
);
356 perror(is_stderr ?
"stderr: write" : "stdout: write");
361 int from_backend(void *frontend_handle
, int is_stderr
,
362 const char *data
, int len
)
367 bufchain_add(&stderr_data
, data
, len
);
370 bufchain_add(&stdout_data
, data
, len
);
374 osize
= bufchain_size(&stdout_data
);
375 esize
= bufchain_size(&stderr_data
);
377 return osize
+ esize
;
382 void sigwinch(int signum
)
384 write(signalpipe
[1], "x", 1);
388 * In Plink our selects are synchronous, so these functions are
391 int uxsel_input_add(int fd
, int rwx
) { return 0; }
392 void uxsel_input_remove(int id
) { }
395 * Short description of parameters.
397 static void usage(void)
399 printf("PuTTY Link: command-line connection utility\n");
401 printf("Usage: plink [options] [user@]host [command]\n");
402 printf(" (\"host\" can also be a PuTTY saved session name)\n");
403 printf("Options:\n");
404 printf(" -V print version information and exit\n");
405 printf(" -pgpfp print PGP key fingerprints and exit\n");
406 printf(" -v show verbose messages\n");
407 printf(" -load sessname Load settings from saved session\n");
408 printf(" -ssh -telnet -rlogin -raw\n");
409 printf(" force use of a particular protocol\n");
410 printf(" -P port connect to specified port\n");
411 printf(" -l user connect with specified username\n");
412 printf(" -batch disable all interactive prompts\n");
413 printf("The following options only apply to SSH connections:\n");
414 printf(" -pw passw login with specified password\n");
415 printf(" -D [listen-IP:]listen-port\n");
416 printf(" Dynamic SOCKS-based port forwarding\n");
417 printf(" -L [listen-IP:]listen-port:host:port\n");
418 printf(" Forward local port to remote address\n");
419 printf(" -R [listen-IP:]listen-port:host:port\n");
420 printf(" Forward remote port to local address\n");
421 printf(" -X -x enable / disable X11 forwarding\n");
422 printf(" -A -a enable / disable agent forwarding\n");
423 printf(" -t -T enable / disable pty allocation\n");
424 printf(" -1 -2 force use of particular protocol version\n");
425 printf(" -4 -6 force use of IPv4 or IPv6\n");
426 printf(" -C enable compression\n");
427 printf(" -i key private key file for authentication\n");
428 printf(" -m file read remote command(s) from file\n");
429 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
430 printf(" -N don't start a shell/command (SSH-2 only)\n");
434 static void version(void)
436 printf("plink: %s\n", ver
);
440 int main(int argc
, char **argv
)
446 int i
, fdcount
, fdsize
, fdstate
;
450 int use_subsystem
= 0;
451 void *ldisc
, *logctx
;
454 ssh_get_line
= console_get_line
;
457 fdcount
= fdsize
= 0;
459 * Initialise port and protocol to sensible defaults. (These
460 * will be overridden by more or less anything.)
462 default_protocol
= PROT_SSH
;
467 * Process the command line.
469 do_defaults(NULL
, &cfg
);
470 loaded_session
= FALSE
;
471 default_protocol
= cfg
.protocol
;
472 default_port
= cfg
.port
;
476 * Override the default protocol if PLINK_PROTOCOL is set.
478 char *p
= getenv("PLINK_PROTOCOL");
481 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
482 if (!strcmp(backends
[i
].name
, p
)) {
483 default_protocol
= cfg
.protocol
= backends
[i
].protocol
;
484 default_port
= cfg
.port
=
485 backends
[i
].backend
->default_port
;
494 int ret
= cmdline_process_param(p
, (argc
> 1 ? argv
[1] : NULL
),
498 "plink: option \"%s\" requires an argument\n", p
);
500 } else if (ret
== 2) {
502 } else if (ret
== 1) {
504 } else if (!strcmp(p
, "-batch")) {
505 console_batch_mode
= 1;
506 } else if (!strcmp(p
, "-s")) {
507 /* Save status to write to cfg later. */
509 } else if (!strcmp(p
, "-V")) {
511 } else if (!strcmp(p
, "-pgpfp")) {
514 } else if (!strcmp(p
, "-o")) {
517 "plink: option \"-o\" requires an argument\n");
521 provide_xrm_string(*++argv
);
524 fprintf(stderr
, "plink: unknown option \"%s\"\n", p
);
531 do_defaults(NULL
, &cfg
);
534 * If the hostname starts with "telnet:", set the
535 * protocol to Telnet and process the string as a
538 if (!strncmp(q
, "telnet:", 7)) {
542 if (q
[0] == '/' && q
[1] == '/')
544 cfg
.protocol
= PROT_TELNET
;
546 while (*p
&& *p
!= ':' && *p
!= '/')
555 strncpy(cfg
.host
, q
, sizeof(cfg
.host
) - 1);
556 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
558 char *r
, *user
, *host
;
560 * Before we process the [user@]host string, we
561 * first check for the presence of a protocol
562 * prefix (a protocol name followed by ",").
567 for (i
= 0; backends
[i
].backend
!= NULL
; i
++) {
568 j
= strlen(backends
[i
].name
);
570 !memcmp(backends
[i
].name
, p
, j
)) {
571 default_protocol
= cfg
.protocol
=
572 backends
[i
].protocol
;
574 backends
[i
].backend
->default_port
;
582 * A nonzero length string followed by an @ is treated
583 * as a username. (We discount an _initial_ @.) The
584 * rest of the string (or the whole string if no @)
585 * is treated as a session name and/or hostname.
589 p
++, r
= NULL
; /* discount initial @ */
594 user
= NULL
, host
= p
;
598 * Now attempt to load a saved session with the
599 * same name as the hostname.
603 do_defaults(host
, &cfg2
);
604 if (loaded_session
|| cfg2
.host
[0] == '\0') {
605 /* No settings for this host; use defaults */
606 /* (or session was already loaded with -load) */
607 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
608 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
609 cfg
.port
= default_port
;
616 /* Patch in specified username. */
617 strncpy(cfg
.username
, user
,
618 sizeof(cfg
.username
) - 1);
619 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
626 cmdlen
= cmdsize
= 0;
631 if (cmdlen
>= cmdsize
) {
632 cmdsize
= cmdlen
+ 512;
633 command
= sresize(command
, cmdsize
, char);
635 command
[cmdlen
++]=*p
++;
637 if (cmdlen
>= cmdsize
) {
638 cmdsize
= cmdlen
+ 512;
639 command
= sresize(command
, cmdsize
, char);
641 command
[cmdlen
++]=' '; /* always add trailing space */
642 if (--argc
) p
= *++argv
;
644 if (cmdlen
) command
[--cmdlen
]='\0';
645 /* change trailing blank to NUL */
646 cfg
.remote_cmd_ptr
= command
;
647 cfg
.remote_cmd_ptr2
= NULL
;
648 cfg
.nopty
= TRUE
; /* command => no terminal */
650 break; /* done with cmdline */
663 * Trim leading whitespace off the hostname if it's there.
666 int space
= strspn(cfg
.host
, " \t");
667 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
670 /* See if host is of the form user@host */
671 if (cfg
.host
[0] != '\0') {
672 char *atsign
= strrchr(cfg
.host
, '@');
673 /* Make sure we're not overflowing the user field */
675 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
676 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
677 cfg
.username
[atsign
- cfg
.host
] = '\0';
679 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
684 * Perform command-line overrides on session configuration.
686 cmdline_run_saved(&cfg
);
689 * Apply subsystem status.
692 cfg
.ssh_subsys
= TRUE
;
695 * Trim a colon suffix off the hostname if it's there.
697 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
700 * Remove any remaining whitespace from the hostname.
704 while (cfg
.host
[p2
] != '\0') {
705 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
706 cfg
.host
[p1
] = cfg
.host
[p2
];
714 if (!cfg
.remote_cmd_ptr
&& !*cfg
.remote_cmd
)
715 flags
|= FLAG_INTERACTIVE
;
718 * Select protocol. This is farmed out into a table in a
719 * separate file to enable an ssh-free variant.
724 for (i
= 0; backends
[i
].backend
!= NULL
; i
++)
725 if (backends
[i
].protocol
== cfg
.protocol
) {
726 back
= backends
[i
].backend
;
731 "Internal fault: Unsupported protocol found\n");
739 if (portnumber
!= -1)
740 cfg
.port
= portnumber
;
743 * Set up the pipe we'll use to tell us about SIGWINCH.
745 if (pipe(signalpipe
) < 0) {
749 putty_signal(SIGWINCH
, sigwinch
);
755 * Start up the connection.
757 logctx
= log_init(NULL
, &cfg
);
758 console_provide_logctx(logctx
);
762 /* nodelay is only useful if stdin is a terminal device */
763 int nodelay
= cfg
.tcp_nodelay
&& isatty(0);
765 error
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
,
766 &realhost
, nodelay
, cfg
.tcp_keepalives
);
768 fprintf(stderr
, "Unable to open connection:\n%s\n", error
);
771 back
->provide_logctx(backhandle
, logctx
);
772 ldisc
= ldisc_create(&cfg
, NULL
, back
, backhandle
, NULL
);
778 * Set up the initial console mode. We don't care if this call
779 * fails, because we know we aren't necessarily running in a
782 local_tty
= (tcgetattr(0, &orig_termios
) == 0);
783 atexit(cleanup_termios
);
784 ldisc_update(NULL
, 1, 1);
786 now
= GETTICKCOUNT();
789 fd_set rset
, wset
, xset
;
799 FD_SET_MAX(signalpipe
[0], maxfd
, rset
);
801 if (connopen
&& !sending
&&
802 back
->socket(backhandle
) != NULL
&&
803 back
->sendok(backhandle
) &&
804 back
->sendbuffer(backhandle
) < MAX_STDIN_BACKLOG
) {
805 /* If we're OK to send, then try to read from stdin. */
806 FD_SET_MAX(0, maxfd
, rset
);
809 if (bufchain_size(&stdout_data
) > 0) {
810 /* If we have data for stdout, try to write to stdout. */
811 FD_SET_MAX(1, maxfd
, wset
);
814 if (bufchain_size(&stderr_data
) > 0) {
815 /* If we have data for stderr, try to write to stderr. */
816 FD_SET_MAX(2, maxfd
, wset
);
819 /* Count the currently active fds. */
821 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
822 fd
= next_fd(&fdstate
, &rwx
)) i
++;
824 /* Expand the fdlist buffer if necessary. */
827 fdlist
= sresize(fdlist
, fdsize
, int);
831 * Add all currently open fds to the select sets, and store
832 * them in fdlist as well.
835 for (fd
= first_fd(&fdstate
, &rwx
); fd
>= 0;
836 fd
= next_fd(&fdstate
, &rwx
)) {
837 fdlist
[fdcount
++] = fd
;
839 FD_SET_MAX(fd
, maxfd
, rset
);
841 FD_SET_MAX(fd
, maxfd
, wset
);
843 FD_SET_MAX(fd
, maxfd
, xset
);
848 struct timeval tv
, *ptv
;
850 if (run_timers(now
, &next
)) {
851 ticks
= next
- GETTICKCOUNT();
852 if (ticks
< 0) ticks
= 0; /* just in case */
853 tv
.tv_sec
= ticks
/ 1000;
854 tv
.tv_usec
= ticks
% 1000 * 1000;
859 ret
= select(maxfd
, &rset
, &wset
, &xset
, ptv
);
863 long newnow
= GETTICKCOUNT();
865 * Check to see whether the system clock has
866 * changed massively during the select.
868 if (newnow
- now
< 0 || newnow
- now
> next
- now
) {
870 * If so, look at the elapsed time in the
871 * select and use it to compute a new
874 long othernow
= now
+ tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
875 /* So we'd like GETTICKCOUNT to have returned othernow,
876 * but instead it return newnow. Hence ... */
877 tickcount_offset
+= othernow
- newnow
;
883 } while (ret
< 0 && errno
== EINTR
);
890 for (i
= 0; i
< fdcount
; i
++) {
893 * We must process exceptional notifications before
894 * ordinary readability ones, or we may go straight
895 * past the urgent marker.
897 if (FD_ISSET(fd
, &xset
))
898 select_result(fd
, 4);
899 if (FD_ISSET(fd
, &rset
))
900 select_result(fd
, 1);
901 if (FD_ISSET(fd
, &wset
))
902 select_result(fd
, 2);
905 if (FD_ISSET(signalpipe
[0], &rset
)) {
908 read(signalpipe
[0], c
, 1); /* ignore its value; it'll be `x' */
909 if (ioctl(0, TIOCGWINSZ
, (void *)&size
) >= 0)
910 back
->size(backhandle
, size
.ws_col
, size
.ws_row
);
913 if (FD_ISSET(0, &rset
)) {
917 if (connopen
&& back
->socket(backhandle
) != NULL
) {
918 ret
= read(0, buf
, sizeof(buf
));
920 perror("stdin: read");
922 } else if (ret
== 0) {
923 back
->special(backhandle
, TS_EOF
);
924 sending
= FALSE
; /* send nothing further after this */
926 back
->send(backhandle
, buf
, ret
);
931 if (FD_ISSET(1, &wset
)) {
935 if (FD_ISSET(2, &wset
)) {
939 if ((!connopen
|| back
->socket(backhandle
) == NULL
) &&
940 bufchain_size(&stdout_data
) == 0 &&
941 bufchain_size(&stderr_data
) == 0)
942 break; /* we closed the connection */
944 exitcode
= back
->exitcode(backhandle
);
946 fprintf(stderr
, "Remote process exit code unavailable\n");
947 exitcode
= 1; /* this is an error condition */
949 cleanup_exit(exitcode
);
950 return exitcode
; /* shouldn't happen, but placates gcc */