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 * Mark parity errors and (more important) BREAK on input. This
154 * is more complex than it need be because POSIX-2001 suggests
155 * that escaping of valid 0xff in the input stream is dependent on
156 * IGNPAR being clear even though marking of BREAK isn't. NetBSD
157 * 2.0 goes one worse and makes it dependent on INPCK too. We
158 * deal with this by forcing these flags into a useful state and
159 * then faking the state in which we found them in from_tty() if
160 * we get passed a parity or framing error.
162 mode.c_iflag = (mode.c_iflag | INPCK | PARMRK) & ~IGNPAR;
164 tcsetattr(0, TCSANOW, &mode);
167 /* Helper function to extract a special character from a termios. */
168 static char *get_ttychar(struct termios *t, int index)
170 cc_t c = t->c_cc[index];
171 #if defined(_POSIX_VDISABLE)
172 if (c == _POSIX_VDISABLE)
173 return dupprintf("");
175 return dupprintf("^<%d>", c);
178 char *get_ttymode(void *frontend, const char *mode)
181 * Propagate appropriate terminal modes from the local terminal,
184 if (!local_tty) return NULL;
186 #define GET_CHAR(ourname, uxname) \
188 if (strcmp(mode, ourname) == 0) \
189 return get_ttychar(&orig_termios, uxname); \
191 #define GET_BOOL(ourname, uxname, uxmemb, transform) \
193 if (strcmp(mode, ourname) == 0) { \
194 int b = (orig_termios.uxmemb & uxname) != 0; \
196 return dupprintf("%d", b); \
201 * Modes that want to be the same on all terminal devices involved.
203 /* All the special characters supported by SSH */
205 GET_CHAR("INTR", VINTR);
208 GET_CHAR("QUIT", VQUIT);
211 GET_CHAR("ERASE", VERASE);
214 GET_CHAR("KILL", VKILL);
217 GET_CHAR("EOF", VEOF);
220 GET_CHAR("EOL", VEOL);
223 GET_CHAR("EOL2", VEOL2);
226 GET_CHAR("START", VSTART);
229 GET_CHAR("STOP", VSTOP);
232 GET_CHAR("SUSP", VSUSP);
235 GET_CHAR("DSUSP", VDSUSP);
237 #if defined(VREPRINT)
238 GET_CHAR("REPRINT", VREPRINT);
241 GET_CHAR("WERASE", VWERASE);
244 GET_CHAR("LNEXT", VLNEXT);
247 GET_CHAR("FLUSH", VFLUSH);
250 GET_CHAR("SWTCH", VSWTCH);
253 GET_CHAR("STATUS", VSTATUS);
255 #if defined(VDISCARD)
256 GET_CHAR("DISCARD", VDISCARD);
258 /* Modes that "configure" other major modes. These should probably be
259 * considered as user preferences. */
260 /* Configuration of ICANON */
262 GET_BOOL("ECHOK", ECHOK, c_lflag, );
265 GET_BOOL("ECHOKE", ECHOKE, c_lflag, );
268 GET_BOOL("ECHOE", ECHOE, c_lflag, );
271 GET_BOOL("ECHONL", ECHONL, c_lflag, );
274 GET_BOOL("XCASE", XCASE, c_lflag, );
276 /* Configuration of ECHO */
278 GET_BOOL("ECHOCTL", ECHOCTL, c_lflag, );
280 /* Configuration of IXON/IXOFF */
282 GET_BOOL("IXANY", IXANY, c_iflag, );
284 /* Configuration of OPOST */
286 GET_BOOL("OLCUC", OLCUC, c_oflag, );
289 GET_BOOL("ONLCR", ONLCR, c_oflag, );
292 GET_BOOL("OCRNL", OCRNL, c_oflag, );
295 GET_BOOL("ONOCR", ONOCR, c_oflag, );
298 GET_BOOL("ONLRET", ONLRET, c_oflag, );
302 * Modes that want to be set in only one place, and that we have
306 GET_BOOL("ISIG", ISIG, c_lflag, );
309 GET_BOOL("ICANON", ICANON, c_lflag, );
312 GET_BOOL("ECHO", ECHO, c_lflag, );
315 GET_BOOL("IXON", IXON, c_iflag, );
318 GET_BOOL("IXOFF", IXOFF, c_iflag, );
321 GET_BOOL("OPOST", OPOST, c_oflag, );
325 * We do not propagate the following modes:
326 * - Parity/serial settings, which are a local affair and don't
327 * make sense propagated over SSH's 8-bit byte-stream.
328 * IGNPAR PARMRK INPCK CS7 CS8 PARENB PARODD
329 * - Things that want to be enabled in one place that we don't
334 * - Things I don't know what to do with. (FIXME)
335 * ISTRIP IMAXBEL NOFLSH TOSTOP IEXTEN
342 /* Fall through to here for unrecognised names, or ones that are
343 * unsupported on this platform */
347 void cleanup_termios(void)
350 tcsetattr(0, TCSANOW, &orig_termios);
353 bufchain stdout_data, stderr_data;
355 void try_output(int is_stderr)
357 bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
358 int fd = (is_stderr ? 2 : 1);
362 if (bufchain_size(chain) == 0)
365 bufchain_prefix(chain, &senddata, &sendlen);
366 ret = write(fd, senddata, sendlen);
368 bufchain_consume(chain, ret);
370 perror(is_stderr ? "stderr: write" : "stdout: write");
375 int from_backend(void *frontend_handle, int is_stderr,
376 const char *data, int len)
381 bufchain_add(&stderr_data, data, len);
384 bufchain_add(&stdout_data, data, len);
388 osize = bufchain_size(&stdout_data);
389 esize = bufchain_size(&stderr_data);
391 return osize + esize;
395 * Handle data from a local tty in PARMRK format.
397 static void from_tty(void *buf, unsigned len)
400 static enum {NORMAL, FF, FF00} state = NORMAL;
402 p = buf; end = buf + len;
410 q = memchr(p, '\xff', end - p);
411 if (q == NULL) q = end;
412 back->send(backhandle, p, q - p);
418 back->send(backhandle, p, 1);
421 } else if (*p == '\0') {
428 back->special(backhandle, TS_BRK);
431 * Pretend that PARMRK wasn't set. This involves
432 * faking what INPCK and IGNPAR would have done if
433 * we hadn't overridden them. Unfortunately, we
434 * can't do this entirely correctly because INPCK
435 * distinguishes between framing and parity
436 * errors, but PARMRK format represents both in
437 * the same way. We assume that parity errors are
438 * more common than framing errors, and hence
439 * treat all input errors as being subject to
442 if (orig_termios.c_iflag & INPCK) {
443 /* If IGNPAR is set, we throw away the character. */
444 if (!(orig_termios.c_iflag & IGNPAR)) {
445 /* PE/FE get passed on as NUL. */
447 back->send(backhandle, p, 1);
450 /* INPCK not set. Assume we got a parity error. */
451 back->send(backhandle, p, 1);
462 void sigwinch(int signum)
464 write(signalpipe[1], "x", 1);
468 * In Plink our selects are synchronous, so these functions are
471 int uxsel_input_add(int fd, int rwx) { return 0; }
472 void uxsel_input_remove(int id) { }
475 * Short description of parameters.
477 static void usage(void)
479 printf("PuTTY Link: command-line connection utility\n");
481 printf("Usage: plink [options] [user@]host [command]\n");
482 printf(" (\"host\" can also be a PuTTY saved session name)\n");
483 printf("Options:\n");
484 printf(" -V print version information and exit\n");
485 printf(" -pgpfp print PGP key fingerprints and exit\n");
486 printf(" -v show verbose messages\n");
487 printf(" -load sessname Load settings from saved session\n");
488 printf(" -ssh -telnet -rlogin -raw\n");
489 printf(" force use of a particular protocol\n");
490 printf(" -P port connect to specified port\n");
491 printf(" -l user connect with specified username\n");
492 printf(" -batch disable all interactive prompts\n");
493 printf("The following options only apply to SSH connections:\n");
494 printf(" -pw passw login with specified password\n");
495 printf(" -D [listen-IP:]listen-port\n");
496 printf(" Dynamic SOCKS-based port forwarding\n");
497 printf(" -L [listen-IP:]listen-port:host:port\n");
498 printf(" Forward local port to remote address\n");
499 printf(" -R [listen-IP:]listen-port:host:port\n");
500 printf(" Forward remote port to local address\n");
501 printf(" -X -x enable / disable X11 forwarding\n");
502 printf(" -A -a enable / disable agent forwarding\n");
503 printf(" -t -T enable / disable pty allocation\n");
504 printf(" -1 -2 force use of particular protocol version\n");
505 printf(" -4 -6 force use of IPv4 or IPv6\n");
506 printf(" -C enable compression\n");
507 printf(" -i key private key file for authentication\n");
508 printf(" -m file read remote command(s) from file\n");
509 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
510 printf(" -N don't start a shell/command (SSH-2 only)\n");
514 static void version(void)
516 printf("plink: %s\n", ver);
520 int main(int argc, char **argv)
526 int i, fdcount, fdsize, fdstate;
530 int use_subsystem = 0;
531 void *ldisc, *logctx;
534 ssh_get_line = console_get_line;
537 fdcount = fdsize = 0;
539 * Initialise port and protocol to sensible defaults. (These
540 * will be overridden by more or less anything.)
542 default_protocol = PROT_SSH;
547 * Process the command line.
549 do_defaults(NULL, &cfg);
550 loaded_session = FALSE;
551 default_protocol = cfg.protocol;
552 default_port = cfg.port;
556 * Override the default protocol if PLINK_PROTOCOL is set.
558 char *p = getenv("PLINK_PROTOCOL");
561 for (i = 0; backends[i].backend != NULL; i++) {
562 if (!strcmp(backends[i].name, p)) {
563 default_protocol = cfg.protocol = backends[i].protocol;
564 default_port = cfg.port =
565 backends[i].backend->default_port;
574 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
578 "plink: option \"%s\" requires an argument\n", p);
580 } else if (ret == 2) {
582 } else if (ret == 1) {
584 } else if (!strcmp(p, "-batch")) {
585 console_batch_mode = 1;
586 } else if (!strcmp(p, "-s")) {
587 /* Save status to write to cfg later. */
589 } else if (!strcmp(p, "-V")) {
591 } else if (!strcmp(p, "-pgpfp")) {
594 } else if (!strcmp(p, "-o")) {
597 "plink: option \"-o\" requires an argument\n");
601 provide_xrm_string(*++argv);
604 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
611 do_defaults(NULL, &cfg);
614 * If the hostname starts with "telnet:", set the
615 * protocol to Telnet and process the string as a
618 if (!strncmp(q, "telnet:", 7)) {
622 if (q[0] == '/' && q[1] == '/')
624 cfg.protocol = PROT_TELNET;
626 while (*p && *p != ':' && *p != '/')
635 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
636 cfg.host[sizeof(cfg.host) - 1] = '\0';
638 char *r, *user, *host;
640 * Before we process the [user@]host string, we
641 * first check for the presence of a protocol
642 * prefix (a protocol name followed by ",").
647 for (i = 0; backends[i].backend != NULL; i++) {
648 j = strlen(backends[i].name);
650 !memcmp(backends[i].name, p, j)) {
651 default_protocol = cfg.protocol =
652 backends[i].protocol;
654 backends[i].backend->default_port;
662 * A nonzero length string followed by an @ is treated
663 * as a username. (We discount an _initial_ @.) The
664 * rest of the string (or the whole string if no @)
665 * is treated as a session name and/or hostname.
669 p++, r = NULL; /* discount initial @ */
674 user = NULL, host = p;
678 * Now attempt to load a saved session with the
679 * same name as the hostname.
683 do_defaults(host, &cfg2);
684 if (loaded_session || cfg2.host[0] == '\0') {
685 /* No settings for this host; use defaults */
686 /* (or session was already loaded with -load) */
687 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
688 cfg.host[sizeof(cfg.host) - 1] = '\0';
689 cfg.port = default_port;
696 /* Patch in specified username. */
697 strncpy(cfg.username, user,
698 sizeof(cfg.username) - 1);
699 cfg.username[sizeof(cfg.username) - 1] = '\0';
706 cmdlen = cmdsize = 0;
711 if (cmdlen >= cmdsize) {
712 cmdsize = cmdlen + 512;
713 command = sresize(command, cmdsize, char);
715 command[cmdlen++]=*p++;
717 if (cmdlen >= cmdsize) {
718 cmdsize = cmdlen + 512;
719 command = sresize(command, cmdsize, char);
721 command[cmdlen++]=' '; /* always add trailing space */
722 if (--argc) p = *++argv;
724 if (cmdlen) command[--cmdlen]='\0';
725 /* change trailing blank to NUL */
726 cfg.remote_cmd_ptr = command;
727 cfg.remote_cmd_ptr2 = NULL;
728 cfg.nopty = TRUE; /* command => no terminal */
730 break; /* done with cmdline */
743 * Trim leading whitespace off the hostname if it's there.
746 int space = strspn(cfg.host, " \t");
747 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
750 /* See if host is of the form user@host */
751 if (cfg.host[0] != '\0') {
752 char *atsign = strrchr(cfg.host, '@');
753 /* Make sure we're not overflowing the user field */
755 if (atsign - cfg.host < sizeof cfg.username) {
756 strncpy(cfg.username, cfg.host, atsign - cfg.host);
757 cfg.username[atsign - cfg.host] = '\0';
759 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
764 * Perform command-line overrides on session configuration.
766 cmdline_run_saved(&cfg);
769 * Apply subsystem status.
772 cfg.ssh_subsys = TRUE;
775 * Trim a colon suffix off the hostname if it's there.
777 cfg.host[strcspn(cfg.host, ":")] = '\0';
780 * Remove any remaining whitespace from the hostname.
784 while (cfg.host[p2] != '\0') {
785 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
786 cfg.host[p1] = cfg.host[p2];
794 if (!cfg.remote_cmd_ptr && !*cfg.remote_cmd)
795 flags |= FLAG_INTERACTIVE;
798 * Select protocol. This is farmed out into a table in a
799 * separate file to enable an ssh-free variant.
804 for (i = 0; backends[i].backend != NULL; i++)
805 if (backends[i].protocol == cfg.protocol) {
806 back = backends[i].backend;
811 "Internal fault: Unsupported protocol found\n");
819 if (portnumber != -1)
820 cfg.port = portnumber;
823 * Set up the pipe we'll use to tell us about SIGWINCH.
825 if (pipe(signalpipe) < 0) {
829 putty_signal(SIGWINCH, sigwinch);
835 * Start up the connection.
837 logctx = log_init(NULL, &cfg);
838 console_provide_logctx(logctx);
842 /* nodelay is only useful if stdin is a terminal device */
843 int nodelay = cfg.tcp_nodelay && isatty(0);
845 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
846 &realhost, nodelay, cfg.tcp_keepalives);
848 fprintf(stderr, "Unable to open connection:\n%s\n", error);
851 back->provide_logctx(backhandle, logctx);
852 ldisc = ldisc_create(&cfg, NULL, back, backhandle, NULL);
858 * Set up the initial console mode. We don't care if this call
859 * fails, because we know we aren't necessarily running in a
862 local_tty = (tcgetattr(0, &orig_termios) == 0);
863 atexit(cleanup_termios);
864 ldisc_update(NULL, 1, 1);
866 now = GETTICKCOUNT();
869 fd_set rset, wset, xset;
879 FD_SET_MAX(signalpipe[0], maxfd, rset);
881 if (connopen && !sending &&
882 back->socket(backhandle) != NULL &&
883 back->sendok(backhandle) &&
884 back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
885 /* If we're OK to send, then try to read from stdin. */
886 FD_SET_MAX(0, maxfd, rset);
889 if (bufchain_size(&stdout_data) > 0) {
890 /* If we have data for stdout, try to write to stdout. */
891 FD_SET_MAX(1, maxfd, wset);
894 if (bufchain_size(&stderr_data) > 0) {
895 /* If we have data for stderr, try to write to stderr. */
896 FD_SET_MAX(2, maxfd, wset);
899 /* Count the currently active fds. */
901 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
902 fd = next_fd(&fdstate, &rwx)) i++;
904 /* Expand the fdlist buffer if necessary. */
907 fdlist = sresize(fdlist, fdsize, int);
911 * Add all currently open fds to the select sets, and store
912 * them in fdlist as well.
915 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
916 fd = next_fd(&fdstate, &rwx)) {
917 fdlist[fdcount++] = fd;
919 FD_SET_MAX(fd, maxfd, rset);
921 FD_SET_MAX(fd, maxfd, wset);
923 FD_SET_MAX(fd, maxfd, xset);
928 struct timeval tv, *ptv;
930 if (run_timers(now, &next)) {
931 ticks = next - GETTICKCOUNT();
932 if (ticks < 0) ticks = 0; /* just in case */
933 tv.tv_sec = ticks / 1000;
934 tv.tv_usec = ticks % 1000 * 1000;
939 ret = select(maxfd, &rset, &wset, &xset, ptv);
943 long newnow = GETTICKCOUNT();
945 * Check to see whether the system clock has
946 * changed massively during the select.
948 if (newnow - now < 0 || newnow - now > next - now) {
950 * If so, look at the elapsed time in the
951 * select and use it to compute a new
954 long othernow = now + tv.tv_sec * 1000 + tv.tv_usec / 1000;
955 /* So we'd like GETTICKCOUNT to have returned othernow,
956 * but instead it return newnow. Hence ... */
957 tickcount_offset += othernow - newnow;
963 } while (ret < 0 && errno == EINTR);
970 for (i = 0; i < fdcount; i++) {
973 * We must process exceptional notifications before
974 * ordinary readability ones, or we may go straight
975 * past the urgent marker.
977 if (FD_ISSET(fd, &xset))
978 select_result(fd, 4);
979 if (FD_ISSET(fd, &rset))
980 select_result(fd, 1);
981 if (FD_ISSET(fd, &wset))
982 select_result(fd, 2);
985 if (FD_ISSET(signalpipe[0], &rset)) {
988 read(signalpipe[0], c, 1); /* ignore its value; it'll be `x' */
989 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
990 back->size(backhandle, size.ws_col, size.ws_row);
993 if (FD_ISSET(0, &rset)) {
997 if (connopen && back->socket(backhandle) != NULL) {
998 ret = read(0, buf, sizeof(buf));
1000 perror("stdin: read");
1002 } else if (ret == 0) {
1003 back->special(backhandle, TS_EOF);
1004 sending = FALSE; /* send nothing further after this */
1009 back->send(backhandle, buf, ret);
1014 if (FD_ISSET(1, &wset)) {
1018 if (FD_ISSET(2, &wset)) {
1022 if ((!connopen || back->socket(backhandle) == NULL) &&
1023 bufchain_size(&stdout_data) == 0 &&
1024 bufchain_size(&stderr_data) == 0)
1025 break; /* we closed the connection */
1027 exitcode = back->exitcode(backhandle);
1029 fprintf(stderr, "Remote process exit code unavailable\n");
1030 exitcode = 1; /* this is an error condition */
1032 cleanup_exit(exitcode);
1033 return exitcode; /* shouldn't happen, but placates gcc */