2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
15 #include <sys/ioctl.h>
17 #ifndef HAVE_NO_SYS_SELECT_H
18 #include <sys/select.h>
21 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
26 #define MAX_STDIN_BACKLOG 4096
28 void fatalbox(char *p, ...)
31 fprintf(stderr, "FATAL ERROR: ");
33 vfprintf(stderr, p, ap);
38 void modalfatalbox(char *p, ...)
41 fprintf(stderr, "FATAL ERROR: ");
43 vfprintf(stderr, p, ap);
48 void connection_fatal(void *frontend, char *p, ...)
51 fprintf(stderr, "FATAL ERROR: ");
53 vfprintf(stderr, p, ap);
58 void cmdline_error(char *p, ...)
61 fprintf(stderr, "plink: ");
63 vfprintf(stderr, p, ap);
69 static int local_tty = 0; /* do we have a local tty? */
70 static struct termios orig_termios;
73 static void *backhandle;
77 * Default settings that are specific to pterm.
79 char *platform_default_s(const char *name)
81 if (!strcmp(name, "TermType"))
82 return dupstr(getenv("TERM"));
83 if (!strcmp(name, "UserName"))
84 return get_username();
85 if (!strcmp(name, "SerialLine"))
86 return dupstr("/dev/ttyS0");
90 int platform_default_i(const char *name, int def)
92 if (!strcmp(name, "TermWidth") ||
93 !strcmp(name, "TermHeight")) {
95 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
96 return (!strcmp(name, "TermWidth") ? size.ws_col : size.ws_row);
101 FontSpec platform_default_fontspec(const char *name)
108 Filename platform_default_filename(const char *name)
111 if (!strcmp(name, "LogFileName"))
112 strcpy(ret.path, "putty.log");
118 char *x_get_default(const char *key)
120 return NULL; /* this is a stub */
122 int term_ldisc(Terminal *term, int mode)
126 void ldisc_update(void *frontend, int echo, int edit)
128 /* Update stdin read mode to reflect changes in line discipline. */
131 if (!local_tty) return;
136 mode.c_lflag |= ECHO;
138 mode.c_lflag &= ~ECHO;
141 mode.c_iflag |= ICRNL;
142 mode.c_lflag |= ISIG | ICANON;
143 mode.c_oflag |= OPOST;
145 mode.c_iflag &= ~ICRNL;
146 mode.c_lflag &= ~(ISIG | ICANON);
147 mode.c_oflag &= ~OPOST;
148 /* Solaris sets these to unhelpful values */
150 mode.c_cc[VTIME] = 0;
151 /* FIXME: perhaps what we do with IXON/IXOFF should be an
152 * argument to ldisc_update(), to allow implementation of SSH-2
153 * "xon-xoff" and Rlogin's equivalent? */
154 mode.c_iflag &= ~IXON;
155 mode.c_iflag &= ~IXOFF;
158 * Mark parity errors and (more important) BREAK on input. This
159 * is more complex than it need be because POSIX-2001 suggests
160 * that escaping of valid 0xff in the input stream is dependent on
161 * IGNPAR being clear even though marking of BREAK isn't. NetBSD
162 * 2.0 goes one worse and makes it dependent on INPCK too. We
163 * deal with this by forcing these flags into a useful state and
164 * then faking the state in which we found them in from_tty() if
165 * we get passed a parity or framing error.
167 mode.c_iflag = (mode.c_iflag | INPCK | PARMRK) & ~IGNPAR;
169 tcsetattr(0, TCSANOW, &mode);
172 /* Helper function to extract a special character from a termios. */
173 static char *get_ttychar(struct termios *t, int index)
175 cc_t c = t->c_cc[index];
176 #if defined(_POSIX_VDISABLE)
177 if (c == _POSIX_VDISABLE)
178 return dupprintf("");
180 return dupprintf("^<%d>", c);
183 char *get_ttymode(void *frontend, const char *mode)
186 * Propagate appropriate terminal modes from the local terminal,
189 if (!local_tty) return NULL;
191 #define GET_CHAR(ourname, uxname) \
193 if (strcmp(mode, ourname) == 0) \
194 return get_ttychar(&orig_termios, uxname); \
196 #define GET_BOOL(ourname, uxname, uxmemb, transform) \
198 if (strcmp(mode, ourname) == 0) { \
199 int b = (orig_termios.uxmemb & uxname) != 0; \
201 return dupprintf("%d", b); \
206 * Modes that want to be the same on all terminal devices involved.
208 /* All the special characters supported by SSH */
210 GET_CHAR("INTR", VINTR);
213 GET_CHAR("QUIT", VQUIT);
216 GET_CHAR("ERASE", VERASE);
219 GET_CHAR("KILL", VKILL);
222 GET_CHAR("EOF", VEOF);
225 GET_CHAR("EOL", VEOL);
228 GET_CHAR("EOL2", VEOL2);
231 GET_CHAR("START", VSTART);
234 GET_CHAR("STOP", VSTOP);
237 GET_CHAR("SUSP", VSUSP);
240 GET_CHAR("DSUSP", VDSUSP);
242 #if defined(VREPRINT)
243 GET_CHAR("REPRINT", VREPRINT);
246 GET_CHAR("WERASE", VWERASE);
249 GET_CHAR("LNEXT", VLNEXT);
252 GET_CHAR("FLUSH", VFLUSH);
255 GET_CHAR("SWTCH", VSWTCH);
258 GET_CHAR("STATUS", VSTATUS);
260 #if defined(VDISCARD)
261 GET_CHAR("DISCARD", VDISCARD);
263 /* Modes that "configure" other major modes. These should probably be
264 * considered as user preferences. */
265 /* Configuration of ICANON */
267 GET_BOOL("ECHOK", ECHOK, c_lflag, );
270 GET_BOOL("ECHOKE", ECHOKE, c_lflag, );
273 GET_BOOL("ECHOE", ECHOE, c_lflag, );
276 GET_BOOL("ECHONL", ECHONL, c_lflag, );
279 GET_BOOL("XCASE", XCASE, c_lflag, );
281 /* Configuration of ECHO */
283 GET_BOOL("ECHOCTL", ECHOCTL, c_lflag, );
285 /* Configuration of IXON/IXOFF */
287 GET_BOOL("IXANY", IXANY, c_iflag, );
289 /* Configuration of OPOST */
291 GET_BOOL("OLCUC", OLCUC, c_oflag, );
294 GET_BOOL("ONLCR", ONLCR, c_oflag, );
297 GET_BOOL("OCRNL", OCRNL, c_oflag, );
300 GET_BOOL("ONOCR", ONOCR, c_oflag, );
303 GET_BOOL("ONLRET", ONLRET, c_oflag, );
307 * Modes that want to be set in only one place, and that we have
311 GET_BOOL("ISIG", ISIG, c_lflag, );
314 GET_BOOL("ICANON", ICANON, c_lflag, );
317 GET_BOOL("ECHO", ECHO, c_lflag, );
320 GET_BOOL("IXON", IXON, c_iflag, );
323 GET_BOOL("IXOFF", IXOFF, c_iflag, );
326 GET_BOOL("OPOST", OPOST, c_oflag, );
330 * We do not propagate the following modes:
331 * - Parity/serial settings, which are a local affair and don't
332 * make sense propagated over SSH's 8-bit byte-stream.
333 * IGNPAR PARMRK INPCK CS7 CS8 PARENB PARODD
334 * - Things that want to be enabled in one place that we don't
339 * - Things I don't know what to do with. (FIXME)
340 * ISTRIP IMAXBEL NOFLSH TOSTOP IEXTEN
347 /* Fall through to here for unrecognised names, or ones that are
348 * unsupported on this platform */
352 void cleanup_termios(void)
355 tcsetattr(0, TCSANOW, &orig_termios);
358 bufchain stdout_data, stderr_data;
360 void try_output(int is_stderr)
362 bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
363 int fd = (is_stderr ? 2 : 1);
367 if (bufchain_size(chain) == 0)
370 bufchain_prefix(chain, &senddata, &sendlen);
371 ret = write(fd, senddata, sendlen);
373 bufchain_consume(chain, ret);
375 perror(is_stderr ? "stderr: write" : "stdout: write");
380 int from_backend(void *frontend_handle, int is_stderr,
381 const char *data, int len)
386 bufchain_add(&stderr_data, data, len);
389 bufchain_add(&stdout_data, data, len);
393 osize = bufchain_size(&stdout_data);
394 esize = bufchain_size(&stderr_data);
396 return osize + esize;
399 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
402 * No "untrusted" output should get here (the way the code is
403 * currently, it's all diverted by FLAG_STDERR).
405 assert(!"Unexpected call to from_backend_untrusted()");
406 return 0; /* not reached */
409 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
412 ret = cmdline_get_passwd_input(p, in, inlen);
414 ret = console_get_userpass_input(p, in, inlen);
419 * Handle data from a local tty in PARMRK format.
421 static void from_tty(void *buf, unsigned len)
424 static enum {NORMAL, FF, FF00} state = NORMAL;
426 p = buf; end = buf + len;
434 q = memchr(p, '\xff', end - p);
435 if (q == NULL) q = end;
436 back->send(backhandle, p, q - p);
442 back->send(backhandle, p, 1);
445 } else if (*p == '\0') {
452 back->special(backhandle, TS_BRK);
455 * Pretend that PARMRK wasn't set. This involves
456 * faking what INPCK and IGNPAR would have done if
457 * we hadn't overridden them. Unfortunately, we
458 * can't do this entirely correctly because INPCK
459 * distinguishes between framing and parity
460 * errors, but PARMRK format represents both in
461 * the same way. We assume that parity errors are
462 * more common than framing errors, and hence
463 * treat all input errors as being subject to
466 if (orig_termios.c_iflag & INPCK) {
467 /* If IGNPAR is set, we throw away the character. */
468 if (!(orig_termios.c_iflag & IGNPAR)) {
469 /* PE/FE get passed on as NUL. */
471 back->send(backhandle, p, 1);
474 /* INPCK not set. Assume we got a parity error. */
475 back->send(backhandle, p, 1);
486 void sigwinch(int signum)
488 write(signalpipe[1], "x", 1);
492 * In Plink our selects are synchronous, so these functions are
495 int uxsel_input_add(int fd, int rwx) { return 0; }
496 void uxsel_input_remove(int id) { }
499 * Short description of parameters.
501 static void usage(void)
503 printf("PuTTY Link: command-line connection utility\n");
505 printf("Usage: plink [options] [user@]host [command]\n");
506 printf(" (\"host\" can also be a PuTTY saved session name)\n");
507 printf("Options:\n");
508 printf(" -V print version information and exit\n");
509 printf(" -pgpfp print PGP key fingerprints and exit\n");
510 printf(" -v show verbose messages\n");
511 printf(" -load sessname Load settings from saved session\n");
512 printf(" -ssh -telnet -rlogin -raw\n");
513 printf(" force use of a particular protocol\n");
514 printf(" -P port connect to specified port\n");
515 printf(" -l user connect with specified username\n");
516 printf(" -batch disable all interactive prompts\n");
517 printf("The following options only apply to SSH connections:\n");
518 printf(" -pw passw login with specified password\n");
519 printf(" -D [listen-IP:]listen-port\n");
520 printf(" Dynamic SOCKS-based port forwarding\n");
521 printf(" -L [listen-IP:]listen-port:host:port\n");
522 printf(" Forward local port to remote address\n");
523 printf(" -R [listen-IP:]listen-port:host:port\n");
524 printf(" Forward remote port to local address\n");
525 printf(" -X -x enable / disable X11 forwarding\n");
526 printf(" -A -a enable / disable agent forwarding\n");
527 printf(" -t -T enable / disable pty allocation\n");
528 printf(" -1 -2 force use of particular protocol version\n");
529 printf(" -4 -6 force use of IPv4 or IPv6\n");
530 printf(" -C enable compression\n");
531 printf(" -i key private key file for authentication\n");
532 printf(" -noagent disable use of Pageant\n");
533 printf(" -agent enable use of Pageant\n");
534 printf(" -m file read remote command(s) from file\n");
535 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
536 printf(" -N don't start a shell/command (SSH-2 only)\n");
537 printf(" -nc host:port\n");
538 printf(" open tunnel in place of session (SSH-2 only)\n");
542 static void version(void)
544 printf("plink: %s\n", ver);
548 int main(int argc, char **argv)
554 int i, fdcount, fdsize, fdstate;
558 int use_subsystem = 0;
559 void *ldisc, *logctx;
563 fdcount = fdsize = 0;
565 * Initialise port and protocol to sensible defaults. (These
566 * will be overridden by more or less anything.)
568 default_protocol = PROT_SSH;
573 * Process the command line.
575 do_defaults(NULL, &cfg);
576 loaded_session = FALSE;
577 default_protocol = cfg.protocol;
578 default_port = cfg.port;
582 * Override the default protocol if PLINK_PROTOCOL is set.
584 char *p = getenv("PLINK_PROTOCOL");
587 for (i = 0; backends[i].backend != NULL; i++) {
588 if (!strcmp(backends[i].name, p)) {
589 default_protocol = cfg.protocol = backends[i].protocol;
590 default_port = cfg.port =
591 backends[i].backend->default_port;
600 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
604 "plink: option \"%s\" requires an argument\n", p);
606 } else if (ret == 2) {
608 } else if (ret == 1) {
610 } else if (!strcmp(p, "-batch")) {
611 console_batch_mode = 1;
612 } else if (!strcmp(p, "-s")) {
613 /* Save status to write to cfg later. */
615 } else if (!strcmp(p, "-V")) {
617 } else if (!strcmp(p, "-pgpfp")) {
620 } else if (!strcmp(p, "-o")) {
623 "plink: option \"-o\" requires an argument\n");
627 provide_xrm_string(*++argv);
630 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
634 if (!cfg_launchable(&cfg)) {
638 * If the hostname starts with "telnet:", set the
639 * protocol to Telnet and process the string as a
642 if (!strncmp(q, "telnet:", 7)) {
646 if (q[0] == '/' && q[1] == '/')
648 cfg.protocol = PROT_TELNET;
650 while (*p && *p != ':' && *p != '/')
659 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
660 cfg.host[sizeof(cfg.host) - 1] = '\0';
662 char *r, *user, *host;
664 * Before we process the [user@]host string, we
665 * first check for the presence of a protocol
666 * prefix (a protocol name followed by ",").
671 for (i = 0; backends[i].backend != NULL; i++) {
672 j = strlen(backends[i].name);
674 !memcmp(backends[i].name, p, j)) {
675 default_protocol = cfg.protocol =
676 backends[i].protocol;
678 backends[i].backend->default_port;
686 * A nonzero length string followed by an @ is treated
687 * as a username. (We discount an _initial_ @.) The
688 * rest of the string (or the whole string if no @)
689 * is treated as a session name and/or hostname.
693 p++, r = NULL; /* discount initial @ */
698 user = NULL, host = p;
702 * Now attempt to load a saved session with the
703 * same name as the hostname.
707 do_defaults(host, &cfg2);
708 if (loaded_session || !cfg_launchable(&cfg2)) {
709 /* No settings for this host; use defaults */
710 /* (or session was already loaded with -load) */
711 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
712 cfg.host[sizeof(cfg.host) - 1] = '\0';
713 cfg.port = default_port;
720 /* Patch in specified username. */
721 strncpy(cfg.username, user,
722 sizeof(cfg.username) - 1);
723 cfg.username[sizeof(cfg.username) - 1] = '\0';
730 cmdlen = cmdsize = 0;
735 if (cmdlen >= cmdsize) {
736 cmdsize = cmdlen + 512;
737 command = sresize(command, cmdsize, char);
739 command[cmdlen++]=*p++;
741 if (cmdlen >= cmdsize) {
742 cmdsize = cmdlen + 512;
743 command = sresize(command, cmdsize, char);
745 command[cmdlen++]=' '; /* always add trailing space */
746 if (--argc) p = *++argv;
748 if (cmdlen) command[--cmdlen]='\0';
749 /* change trailing blank to NUL */
750 cfg.remote_cmd_ptr = command;
751 cfg.remote_cmd_ptr2 = NULL;
752 cfg.nopty = TRUE; /* command => no terminal */
754 break; /* done with cmdline */
762 if (!cfg_launchable(&cfg)) {
767 * Trim leading whitespace off the hostname if it's there.
770 int space = strspn(cfg.host, " \t");
771 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
774 /* See if host is of the form user@host */
775 if (cfg.host[0] != '\0') {
776 char *atsign = strrchr(cfg.host, '@');
777 /* Make sure we're not overflowing the user field */
779 if (atsign - cfg.host < sizeof cfg.username) {
780 strncpy(cfg.username, cfg.host, atsign - cfg.host);
781 cfg.username[atsign - cfg.host] = '\0';
783 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
788 * Perform command-line overrides on session configuration.
790 cmdline_run_saved(&cfg);
793 * Apply subsystem status.
796 cfg.ssh_subsys = TRUE;
799 * Trim a colon suffix off the hostname if it's there.
801 cfg.host[strcspn(cfg.host, ":")] = '\0';
804 * Remove any remaining whitespace from the hostname.
808 while (cfg.host[p2] != '\0') {
809 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
810 cfg.host[p1] = cfg.host[p2];
818 if (!cfg.remote_cmd_ptr && !*cfg.remote_cmd && !*cfg.ssh_nc_host)
819 flags |= FLAG_INTERACTIVE;
822 * Select protocol. This is farmed out into a table in a
823 * separate file to enable an ssh-free variant.
828 for (i = 0; backends[i].backend != NULL; i++)
829 if (backends[i].protocol == cfg.protocol) {
830 back = backends[i].backend;
835 "Internal fault: Unsupported protocol found\n");
843 if (portnumber != -1)
844 cfg.port = portnumber;
847 * Set up the pipe we'll use to tell us about SIGWINCH.
849 if (pipe(signalpipe) < 0) {
853 putty_signal(SIGWINCH, sigwinch);
859 * Start up the connection.
861 logctx = log_init(NULL, &cfg);
862 console_provide_logctx(logctx);
866 /* nodelay is only useful if stdin is a terminal device */
867 int nodelay = cfg.tcp_nodelay && isatty(0);
869 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
870 &realhost, nodelay, cfg.tcp_keepalives);
872 fprintf(stderr, "Unable to open connection:\n%s\n", error);
875 back->provide_logctx(backhandle, logctx);
876 ldisc = ldisc_create(&cfg, NULL, back, backhandle, NULL);
882 * Set up the initial console mode. We don't care if this call
883 * fails, because we know we aren't necessarily running in a
886 local_tty = (tcgetattr(0, &orig_termios) == 0);
887 atexit(cleanup_termios);
888 ldisc_update(NULL, 1, 1);
890 now = GETTICKCOUNT();
893 fd_set rset, wset, xset;
903 FD_SET_MAX(signalpipe[0], maxfd, rset);
905 if (connopen && !sending &&
906 back->connected(backhandle) &&
907 back->sendok(backhandle) &&
908 back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
909 /* If we're OK to send, then try to read from stdin. */
910 FD_SET_MAX(0, maxfd, rset);
913 if (bufchain_size(&stdout_data) > 0) {
914 /* If we have data for stdout, try to write to stdout. */
915 FD_SET_MAX(1, maxfd, wset);
918 if (bufchain_size(&stderr_data) > 0) {
919 /* If we have data for stderr, try to write to stderr. */
920 FD_SET_MAX(2, maxfd, wset);
923 /* Count the currently active fds. */
925 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
926 fd = next_fd(&fdstate, &rwx)) i++;
928 /* Expand the fdlist buffer if necessary. */
931 fdlist = sresize(fdlist, fdsize, int);
935 * Add all currently open fds to the select sets, and store
936 * them in fdlist as well.
939 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
940 fd = next_fd(&fdstate, &rwx)) {
941 fdlist[fdcount++] = fd;
943 FD_SET_MAX(fd, maxfd, rset);
945 FD_SET_MAX(fd, maxfd, wset);
947 FD_SET_MAX(fd, maxfd, xset);
952 struct timeval tv, *ptv;
954 if (run_timers(now, &next)) {
955 ticks = next - GETTICKCOUNT();
956 if (ticks < 0) ticks = 0; /* just in case */
957 tv.tv_sec = ticks / 1000;
958 tv.tv_usec = ticks % 1000 * 1000;
963 ret = select(maxfd, &rset, &wset, &xset, ptv);
967 long newnow = GETTICKCOUNT();
969 * Check to see whether the system clock has
970 * changed massively during the select.
972 if (newnow - now < 0 || newnow - now > next - now) {
974 * If so, look at the elapsed time in the
975 * select and use it to compute a new
978 long othernow = now + tv.tv_sec * 1000 + tv.tv_usec / 1000;
979 /* So we'd like GETTICKCOUNT to have returned othernow,
980 * but instead it return newnow. Hence ... */
981 tickcount_offset += othernow - newnow;
987 } while (ret < 0 && errno == EINTR);
994 for (i = 0; i < fdcount; i++) {
997 * We must process exceptional notifications before
998 * ordinary readability ones, or we may go straight
999 * past the urgent marker.
1001 if (FD_ISSET(fd, &xset))
1002 select_result(fd, 4);
1003 if (FD_ISSET(fd, &rset))
1004 select_result(fd, 1);
1005 if (FD_ISSET(fd, &wset))
1006 select_result(fd, 2);
1009 if (FD_ISSET(signalpipe[0], &rset)) {
1011 struct winsize size;
1012 read(signalpipe[0], c, 1); /* ignore its value; it'll be `x' */
1013 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
1014 back->size(backhandle, size.ws_col, size.ws_row);
1017 if (FD_ISSET(0, &rset)) {
1021 if (connopen && back->connected(backhandle)) {
1022 ret = read(0, buf, sizeof(buf));
1024 perror("stdin: read");
1026 } else if (ret == 0) {
1027 back->special(backhandle, TS_EOF);
1028 sending = FALSE; /* send nothing further after this */
1033 back->send(backhandle, buf, ret);
1038 if (FD_ISSET(1, &wset)) {
1042 if (FD_ISSET(2, &wset)) {
1046 if ((!connopen || !back->connected(backhandle)) &&
1047 bufchain_size(&stdout_data) == 0 &&
1048 bufchain_size(&stderr_data) == 0)
1049 break; /* we closed the connection */
1051 exitcode = back->exitcode(backhandle);
1053 fprintf(stderr, "Remote process exit code unavailable\n");
1054 exitcode = 1; /* this is an error condition */
1056 cleanup_exit(exitcode);
1057 return exitcode; /* shouldn't happen, but placates gcc */