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
30 static struct termios orig_termios;
32 void fatalbox(const char *p, ...)
37 fprintf(stderr, "FATAL ERROR: ");
39 vfprintf(stderr, p, ap);
49 void modalfatalbox(const char *p, ...)
54 fprintf(stderr, "FATAL ERROR: ");
56 vfprintf(stderr, p, ap);
66 void nonfatal(const char *p, ...)
71 fprintf(stderr, "ERROR: ");
73 vfprintf(stderr, p, ap);
78 void connection_fatal(void *frontend, const char *p, ...)
83 fprintf(stderr, "FATAL ERROR: ");
85 vfprintf(stderr, p, ap);
95 void cmdline_error(const char *p, ...)
100 fprintf(stderr, "plink: ");
102 vfprintf(stderr, p, ap);
109 static int local_tty = FALSE; /* do we have a local tty? */
111 static Backend *back;
112 static void *backhandle;
116 * Default settings that are specific to Unix plink.
118 char *platform_default_s(const char *name)
120 if (!strcmp(name, "TermType"))
121 return dupstr(getenv("TERM"));
122 if (!strcmp(name, "SerialLine"))
123 return dupstr("/dev/ttyS0");
127 int platform_default_i(const char *name, int def)
132 FontSpec *platform_default_fontspec(const char *name)
134 return fontspec_new("");
137 Filename *platform_default_filename(const char *name)
139 if (!strcmp(name, "LogFileName"))
140 return filename_from_str("putty.log");
142 return filename_from_str("");
145 char *x_get_default(const char *key)
147 return NULL; /* this is a stub */
149 int term_ldisc(Terminal *term, int mode)
153 void frontend_echoedit_update(void *frontend, int echo, int edit)
155 /* Update stdin read mode to reflect changes in line discipline. */
158 if (!local_tty) return;
163 mode.c_lflag |= ECHO;
165 mode.c_lflag &= ~ECHO;
168 mode.c_iflag |= ICRNL;
169 mode.c_lflag |= ISIG | ICANON;
170 mode.c_oflag |= OPOST;
172 mode.c_iflag &= ~ICRNL;
173 mode.c_lflag &= ~(ISIG | ICANON);
174 mode.c_oflag &= ~OPOST;
175 /* Solaris sets these to unhelpful values */
177 mode.c_cc[VTIME] = 0;
178 /* FIXME: perhaps what we do with IXON/IXOFF should be an
179 * argument to frontend_echoedit_update(), to allow
180 * implementation of SSH-2 "xon-xoff" and Rlogin's
182 mode.c_iflag &= ~IXON;
183 mode.c_iflag &= ~IXOFF;
186 * Mark parity errors and (more important) BREAK on input. This
187 * is more complex than it need be because POSIX-2001 suggests
188 * that escaping of valid 0xff in the input stream is dependent on
189 * IGNPAR being clear even though marking of BREAK isn't. NetBSD
190 * 2.0 goes one worse and makes it dependent on INPCK too. We
191 * deal with this by forcing these flags into a useful state and
192 * then faking the state in which we found them in from_tty() if
193 * we get passed a parity or framing error.
195 mode.c_iflag = (mode.c_iflag | INPCK | PARMRK) & ~IGNPAR;
197 tcsetattr(STDIN_FILENO, TCSANOW, &mode);
200 /* Helper function to extract a special character from a termios. */
201 static char *get_ttychar(struct termios *t, int index)
203 cc_t c = t->c_cc[index];
204 #if defined(_POSIX_VDISABLE)
205 if (c == _POSIX_VDISABLE)
208 return dupprintf("^<%d>", c);
211 char *get_ttymode(void *frontend, const char *mode)
214 * Propagate appropriate terminal modes from the local terminal,
217 if (!local_tty) return NULL;
219 #define GET_CHAR(ourname, uxname) \
221 if (strcmp(mode, ourname) == 0) \
222 return get_ttychar(&orig_termios, uxname); \
224 #define GET_BOOL(ourname, uxname, uxmemb, transform) \
226 if (strcmp(mode, ourname) == 0) { \
227 int b = (orig_termios.uxmemb & uxname) != 0; \
229 return dupprintf("%d", b); \
234 * Modes that want to be the same on all terminal devices involved.
236 /* All the special characters supported by SSH */
238 GET_CHAR("INTR", VINTR);
241 GET_CHAR("QUIT", VQUIT);
244 GET_CHAR("ERASE", VERASE);
247 GET_CHAR("KILL", VKILL);
250 GET_CHAR("EOF", VEOF);
253 GET_CHAR("EOL", VEOL);
256 GET_CHAR("EOL2", VEOL2);
259 GET_CHAR("START", VSTART);
262 GET_CHAR("STOP", VSTOP);
265 GET_CHAR("SUSP", VSUSP);
268 GET_CHAR("DSUSP", VDSUSP);
270 #if defined(VREPRINT)
271 GET_CHAR("REPRINT", VREPRINT);
274 GET_CHAR("WERASE", VWERASE);
277 GET_CHAR("LNEXT", VLNEXT);
280 GET_CHAR("FLUSH", VFLUSH);
283 GET_CHAR("SWTCH", VSWTCH);
286 GET_CHAR("STATUS", VSTATUS);
288 #if defined(VDISCARD)
289 GET_CHAR("DISCARD", VDISCARD);
291 /* Modes that "configure" other major modes. These should probably be
292 * considered as user preferences. */
293 /* Configuration of ICANON */
295 GET_BOOL("ECHOK", ECHOK, c_lflag, );
298 GET_BOOL("ECHOKE", ECHOKE, c_lflag, );
301 GET_BOOL("ECHOE", ECHOE, c_lflag, );
304 GET_BOOL("ECHONL", ECHONL, c_lflag, );
307 GET_BOOL("XCASE", XCASE, c_lflag, );
309 /* Configuration of ECHO */
311 GET_BOOL("ECHOCTL", ECHOCTL, c_lflag, );
313 /* Configuration of IXON/IXOFF */
315 GET_BOOL("IXANY", IXANY, c_iflag, );
317 /* Configuration of OPOST */
319 GET_BOOL("OLCUC", OLCUC, c_oflag, );
322 GET_BOOL("ONLCR", ONLCR, c_oflag, );
325 GET_BOOL("OCRNL", OCRNL, c_oflag, );
328 GET_BOOL("ONOCR", ONOCR, c_oflag, );
331 GET_BOOL("ONLRET", ONLRET, c_oflag, );
335 * Modes that want to be set in only one place, and that we have
339 GET_BOOL("ISIG", ISIG, c_lflag, );
342 GET_BOOL("ICANON", ICANON, c_lflag, );
345 GET_BOOL("ECHO", ECHO, c_lflag, );
348 GET_BOOL("IXON", IXON, c_iflag, );
351 GET_BOOL("IXOFF", IXOFF, c_iflag, );
354 GET_BOOL("OPOST", OPOST, c_oflag, );
358 * We do not propagate the following modes:
359 * - Parity/serial settings, which are a local affair and don't
360 * make sense propagated over SSH's 8-bit byte-stream.
361 * IGNPAR PARMRK INPCK CS7 CS8 PARENB PARODD
362 * - Things that want to be enabled in one place that we don't
367 * - Things I don't know what to do with. (FIXME)
368 * ISTRIP IMAXBEL NOFLSH TOSTOP IEXTEN
375 /* Fall through to here for unrecognised names, or ones that are
376 * unsupported on this platform */
380 void cleanup_termios(void)
383 tcsetattr(STDIN_FILENO, TCSANOW, &orig_termios);
386 bufchain stdout_data, stderr_data;
387 enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
389 int try_output(int is_stderr)
391 bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
392 int fd = (is_stderr ? STDERR_FILENO : STDOUT_FILENO);
396 if (bufchain_size(chain) > 0) {
397 int prev_nonblock = nonblock(fd);
399 bufchain_prefix(chain, &senddata, &sendlen);
400 ret = write(fd, senddata, sendlen);
402 bufchain_consume(chain, ret);
403 } while (ret == sendlen && bufchain_size(chain) != 0);
406 if (ret < 0 && errno != EAGAIN) {
407 perror(is_stderr ? "stderr: write" : "stdout: write");
411 if (outgoingeof == EOF_PENDING && bufchain_size(&stdout_data) == 0) {
412 close(STDOUT_FILENO);
413 outgoingeof = EOF_SENT;
415 return bufchain_size(&stdout_data) + bufchain_size(&stderr_data);
418 int from_backend(void *frontend_handle, int is_stderr,
419 const char *data, int len)
422 bufchain_add(&stderr_data, data, len);
423 return try_output(TRUE);
425 assert(outgoingeof == EOF_NO);
426 bufchain_add(&stdout_data, data, len);
427 return try_output(FALSE);
431 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
434 * No "untrusted" output should get here (the way the code is
435 * currently, it's all diverted by FLAG_STDERR).
437 assert(!"Unexpected call to from_backend_untrusted()");
438 return 0; /* not reached */
441 int from_backend_eof(void *frontend_handle)
443 assert(outgoingeof == EOF_NO);
444 outgoingeof = EOF_PENDING;
446 return FALSE; /* do not respond to incoming EOF with outgoing */
449 int get_userpass_input(prompts_t *p, const unsigned char *in, int inlen)
452 ret = cmdline_get_passwd_input(p, in, inlen);
454 ret = console_get_userpass_input(p, in, inlen);
459 * Handle data from a local tty in PARMRK format.
461 static void from_tty(void *vbuf, unsigned len)
463 char *p, *q, *end, *buf = vbuf;
464 static enum {NORMAL, FF, FF00} state = NORMAL;
466 p = buf; end = buf + len;
474 q = memchr(p, '\xff', end - p);
475 if (q == NULL) q = end;
476 back->send(backhandle, p, q - p);
482 back->send(backhandle, p, 1);
485 } else if (*p == '\0') {
492 back->special(backhandle, TS_BRK);
495 * Pretend that PARMRK wasn't set. This involves
496 * faking what INPCK and IGNPAR would have done if
497 * we hadn't overridden them. Unfortunately, we
498 * can't do this entirely correctly because INPCK
499 * distinguishes between framing and parity
500 * errors, but PARMRK format represents both in
501 * the same way. We assume that parity errors are
502 * more common than framing errors, and hence
503 * treat all input errors as being subject to
506 if (orig_termios.c_iflag & INPCK) {
507 /* If IGNPAR is set, we throw away the character. */
508 if (!(orig_termios.c_iflag & IGNPAR)) {
509 /* PE/FE get passed on as NUL. */
511 back->send(backhandle, p, 1);
514 /* INPCK not set. Assume we got a parity error. */
515 back->send(backhandle, p, 1);
526 void sigwinch(int signum)
528 if (write(signalpipe[1], "x", 1) <= 0)
529 /* not much we can do about it */;
533 * In Plink our selects are synchronous, so these functions are
536 uxsel_id *uxsel_input_add(int fd, int rwx) { return NULL; }
537 void uxsel_input_remove(uxsel_id *id) { }
540 * Short description of parameters.
542 static void usage(void)
544 printf("Plink: command-line connection utility\n");
546 printf("Usage: plink [options] [user@]host [command]\n");
547 printf(" (\"host\" can also be a PuTTY saved session name)\n");
548 printf("Options:\n");
549 printf(" -V print version information and exit\n");
550 printf(" -pgpfp print PGP key fingerprints and exit\n");
551 printf(" -v show verbose messages\n");
552 printf(" -load sessname Load settings from saved session\n");
553 printf(" -ssh -telnet -rlogin -raw -serial\n");
554 printf(" force use of a particular protocol\n");
555 printf(" -P port connect to specified port\n");
556 printf(" -l user connect with specified username\n");
557 printf(" -batch disable all interactive prompts\n");
558 printf(" -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
559 printf(" Specify the serial configuration (serial only)\n");
560 printf("The following options only apply to SSH connections:\n");
561 printf(" -pw passw login with specified password\n");
562 printf(" -D [listen-IP:]listen-port\n");
563 printf(" Dynamic SOCKS-based port forwarding\n");
564 printf(" -L [listen-IP:]listen-port:host:port\n");
565 printf(" Forward local port to remote address\n");
566 printf(" -R [listen-IP:]listen-port:host:port\n");
567 printf(" Forward remote port to local address\n");
568 printf(" -X -x enable / disable X11 forwarding\n");
569 printf(" -A -a enable / disable agent forwarding\n");
570 printf(" -t -T enable / disable pty allocation\n");
571 printf(" -1 -2 force use of particular protocol version\n");
572 printf(" -4 -6 force use of IPv4 or IPv6\n");
573 printf(" -C enable compression\n");
574 printf(" -i key private key file for user authentication\n");
575 printf(" -noagent disable use of Pageant\n");
576 printf(" -agent enable use of Pageant\n");
577 printf(" -hostkey aa:bb:cc:...\n");
578 printf(" manually specify a host key (may be repeated)\n");
579 printf(" -m file read remote command(s) from file\n");
580 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
581 printf(" -N don't start a shell/command (SSH-2 only)\n");
582 printf(" -nc host:port\n");
583 printf(" open tunnel in place of session (SSH-2 only)\n");
584 printf(" -sshlog file\n");
585 printf(" -sshrawlog file\n");
586 printf(" log protocol details to a file\n");
587 printf(" -shareexists\n");
588 printf(" test whether a connection-sharing upstream exists\n");
592 static void version(void)
594 printf("plink: %s\n", ver);
598 void frontend_net_error_pending(void) {}
600 const int share_can_be_downstream = TRUE;
601 const int share_can_be_upstream = TRUE;
603 int main(int argc, char **argv)
609 int i, fdcount, fdsize, fdstate;
613 int use_subsystem = 0;
614 int got_host = FALSE;
615 int just_test_share_exists = FALSE;
620 fdcount = fdsize = 0;
622 * Initialise port and protocol to sensible defaults. (These
623 * will be overridden by more or less anything.)
625 default_protocol = PROT_SSH;
628 bufchain_init(&stdout_data);
629 bufchain_init(&stderr_data);
630 outgoingeof = EOF_NO;
632 flags = FLAG_STDERR | FLAG_STDERR_TTY;
636 * Process the command line.
639 do_defaults(NULL, conf);
640 loaded_session = FALSE;
641 default_protocol = conf_get_int(conf, CONF_protocol);
642 default_port = conf_get_int(conf, CONF_port);
646 * Override the default protocol if PLINK_PROTOCOL is set.
648 char *p = getenv("PLINK_PROTOCOL");
650 const Backend *b = backend_from_name(p);
652 default_protocol = b->protocol;
653 default_port = b->default_port;
654 conf_set_int(conf, CONF_protocol, default_protocol);
655 conf_set_int(conf, CONF_port, default_port);
662 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
666 "plink: option \"%s\" requires an argument\n", p);
668 } else if (ret == 2) {
670 } else if (ret == 1) {
672 } else if (!strcmp(p, "-batch")) {
673 console_batch_mode = 1;
674 } else if (!strcmp(p, "-s")) {
675 /* Save status to write to conf later. */
677 } else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
679 } else if (!strcmp(p, "--help")) {
682 } else if (!strcmp(p, "-pgpfp")) {
685 } else if (!strcmp(p, "-o")) {
688 "plink: option \"-o\" requires an argument\n");
692 provide_xrm_string(*++argv);
694 } else if (!strcmp(p, "-shareexists")) {
695 just_test_share_exists = TRUE;
696 } else if (!strcmp(p, "-fuzznet")) {
697 conf_set_int(conf, CONF_proxy_type, PROXY_FUZZ);
698 conf_set_str(conf, CONF_proxy_telnet_command,
701 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
705 if (!conf_launchable(conf) || !(got_host || loaded_session)) {
709 * If the hostname starts with "telnet:", set the
710 * protocol to Telnet and process the string as a
713 if (!strncmp(q, "telnet:", 7)) {
717 if (q[0] == '/' && q[1] == '/')
719 conf_set_int(conf, CONF_protocol, PROT_TELNET);
721 p += host_strcspn(p, ":/");
726 conf_set_int(conf, CONF_port, atoi(p));
728 conf_set_int(conf, CONF_port, -1);
729 conf_set_str(conf, CONF_host, q);
732 char *r, *user, *host;
734 * Before we process the [user@]host string, we
735 * first check for the presence of a protocol
736 * prefix (a protocol name followed by ",").
742 b = backend_from_name(p);
744 default_protocol = b->protocol;
745 conf_set_int(conf, CONF_protocol,
747 portnumber = b->default_port;
753 * A nonzero length string followed by an @ is treated
754 * as a username. (We discount an _initial_ @.) The
755 * rest of the string (or the whole string if no @)
756 * is treated as a session name and/or hostname.
760 p++, r = NULL; /* discount initial @ */
765 user = NULL, host = p;
769 * Now attempt to load a saved session with the
770 * same name as the hostname.
773 Conf *conf2 = conf_new();
774 do_defaults(host, conf2);
775 if (loaded_session || !conf_launchable(conf2)) {
776 /* No settings for this host; use defaults */
777 /* (or session was already loaded with -load) */
778 conf_set_str(conf, CONF_host, host);
779 conf_set_int(conf, CONF_port, default_port);
782 conf_copy_into(conf, conf2);
783 loaded_session = TRUE;
789 /* Patch in specified username. */
790 conf_set_str(conf, CONF_username, user);
797 cmdlen = cmdsize = 0;
802 if (cmdlen >= cmdsize) {
803 cmdsize = cmdlen + 512;
804 command = sresize(command, cmdsize, char);
806 command[cmdlen++]=*p++;
808 if (cmdlen >= cmdsize) {
809 cmdsize = cmdlen + 512;
810 command = sresize(command, cmdsize, char);
812 command[cmdlen++]=' '; /* always add trailing space */
813 if (--argc) p = *++argv;
815 if (cmdlen) command[--cmdlen]='\0';
816 /* change trailing blank to NUL */
817 conf_set_str(conf, CONF_remote_cmd, command);
818 conf_set_str(conf, CONF_remote_cmd2, "");
819 conf_set_int(conf, CONF_nopty, TRUE); /* command => no tty */
821 break; /* done with cmdline */
829 if (!conf_launchable(conf) || !(got_host || loaded_session)) {
834 * Muck about with the hostname in various ways.
837 char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
838 char *host = hostbuf;
842 * Trim leading whitespace.
844 host += strspn(host, " \t");
847 * See if host is of the form user@host, and separate out
848 * the username if so.
850 if (host[0] != '\0') {
851 char *atsign = strrchr(host, '@');
854 conf_set_str(conf, CONF_username, host);
860 * Trim a colon suffix off the hostname if it's there. In
861 * order to protect unbracketed IPv6 address literals
862 * against this treatment, we do not do this if there's
863 * _more_ than one colon.
866 char *c = host_strchr(host, ':');
869 char *d = host_strchr(c+1, ':');
876 * Remove any remaining whitespace.
881 if (*q != ' ' && *q != '\t')
887 conf_set_str(conf, CONF_host, hostbuf);
892 * Perform command-line overrides on session configuration.
894 cmdline_run_saved(conf);
897 * If we have no better ideas for the remote username, use the local
898 * one, as 'ssh' does.
900 if (conf_get_str(conf, CONF_username)[0] == '\0') {
901 char *user = get_username();
903 conf_set_str(conf, CONF_username, user);
909 * Apply subsystem status.
912 conf_set_int(conf, CONF_ssh_subsys, TRUE);
914 if (!*conf_get_str(conf, CONF_remote_cmd) &&
915 !*conf_get_str(conf, CONF_remote_cmd2) &&
916 !*conf_get_str(conf, CONF_ssh_nc_host))
917 flags |= FLAG_INTERACTIVE;
920 * Select protocol. This is farmed out into a table in a
921 * separate file to enable an ssh-free variant.
923 back = backend_from_proto(conf_get_int(conf, CONF_protocol));
926 "Internal fault: Unsupported protocol found\n");
933 if (portnumber != -1)
934 conf_set_int(conf, CONF_port, portnumber);
937 * Block SIGPIPE, so that we'll get EPIPE individually on
938 * particular network connections that go wrong.
940 putty_signal(SIGPIPE, SIG_IGN);
943 * Set up the pipe we'll use to tell us about SIGWINCH.
945 if (pipe(signalpipe) < 0) {
949 putty_signal(SIGWINCH, sigwinch);
952 * Now that we've got the SIGWINCH handler installed, try to find
953 * out the initial terminal size.
955 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &size) >= 0) {
956 conf_set_int(conf, CONF_width, size.ws_col);
957 conf_set_int(conf, CONF_height, size.ws_row);
964 * Plink doesn't provide any way to add forwardings after the
965 * connection is set up, so if there are none now, we can safely set
968 if (conf_get_int(conf, CONF_protocol) == PROT_SSH &&
969 !conf_get_int(conf, CONF_x11_forward) &&
970 !conf_get_int(conf, CONF_agentfwd) &&
971 !conf_get_str_nthstrkey(conf, CONF_portfwd, 0))
972 conf_set_int(conf, CONF_ssh_simple, TRUE);
974 if (just_test_share_exists) {
975 if (!back->test_for_upstream) {
976 fprintf(stderr, "Connection sharing not supported for connection "
977 "type '%s'\n", back->name);
980 if (back->test_for_upstream(conf_get_str(conf, CONF_host),
981 conf_get_int(conf, CONF_port), conf))
988 * Start up the connection.
990 logctx = log_init(NULL, conf);
991 console_provide_logctx(logctx);
995 /* nodelay is only useful if stdin is a terminal device */
996 int nodelay = conf_get_int(conf, CONF_tcp_nodelay) && isatty(0);
998 /* This is a good place for a fuzzer to fork us. */
999 #ifdef __AFL_HAVE_MANUAL_CONTROL
1003 error = back->init(NULL, &backhandle, conf,
1004 conf_get_str(conf, CONF_host),
1005 conf_get_int(conf, CONF_port),
1007 conf_get_int(conf, CONF_tcp_keepalives));
1009 fprintf(stderr, "Unable to open connection:\n%s\n", error);
1012 back->provide_logctx(backhandle, logctx);
1013 ldisc_create(conf, NULL, back, backhandle, NULL);
1019 * Set up the initial console mode. We don't care if this call
1020 * fails, because we know we aren't necessarily running in a
1023 local_tty = (tcgetattr(STDIN_FILENO, &orig_termios) == 0);
1024 atexit(cleanup_termios);
1025 frontend_echoedit_update(NULL, 1, 1);
1027 now = GETTICKCOUNT();
1030 fd_set rset, wset, xset;
1041 FD_SET_MAX(signalpipe[0], maxfd, rset);
1043 if (connopen && !sending &&
1044 back->connected(backhandle) &&
1045 back->sendok(backhandle) &&
1046 back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
1047 /* If we're OK to send, then try to read from stdin. */
1048 FD_SET_MAX(STDIN_FILENO, maxfd, rset);
1051 if (bufchain_size(&stdout_data) > 0) {
1052 /* If we have data for stdout, try to write to stdout. */
1053 FD_SET_MAX(STDOUT_FILENO, maxfd, wset);
1056 if (bufchain_size(&stderr_data) > 0) {
1057 /* If we have data for stderr, try to write to stderr. */
1058 FD_SET_MAX(STDERR_FILENO, maxfd, wset);
1061 /* Count the currently active fds. */
1063 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
1064 fd = next_fd(&fdstate, &rwx)) i++;
1066 /* Expand the fdlist buffer if necessary. */
1069 fdlist = sresize(fdlist, fdsize, int);
1073 * Add all currently open fds to the select sets, and store
1074 * them in fdlist as well.
1077 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
1078 fd = next_fd(&fdstate, &rwx)) {
1079 fdlist[fdcount++] = fd;
1081 FD_SET_MAX(fd, maxfd, rset);
1083 FD_SET_MAX(fd, maxfd, wset);
1085 FD_SET_MAX(fd, maxfd, xset);
1088 if (toplevel_callback_pending()) {
1092 ret = select(maxfd, &rset, &wset, &xset, &tv);
1093 } else if (run_timers(now, &next)) {
1100 now = GETTICKCOUNT();
1101 if (now - then > next - then)
1105 tv.tv_sec = ticks / 1000;
1106 tv.tv_usec = ticks % 1000 * 1000;
1107 ret = select(maxfd, &rset, &wset, &xset, &tv);
1111 now = GETTICKCOUNT();
1112 } while (ret < 0 && errno == EINTR);
1114 ret = select(maxfd, &rset, &wset, &xset, NULL);
1122 for (i = 0; i < fdcount; i++) {
1125 * We must process exceptional notifications before
1126 * ordinary readability ones, or we may go straight
1127 * past the urgent marker.
1129 if (FD_ISSET(fd, &xset))
1130 select_result(fd, 4);
1131 if (FD_ISSET(fd, &rset))
1132 select_result(fd, 1);
1133 if (FD_ISSET(fd, &wset))
1134 select_result(fd, 2);
1137 if (FD_ISSET(signalpipe[0], &rset)) {
1139 struct winsize size;
1140 if (read(signalpipe[0], c, 1) <= 0)
1142 /* ignore its value; it'll be `x' */
1143 if (ioctl(STDIN_FILENO, TIOCGWINSZ, (void *)&size) >= 0)
1144 back->size(backhandle, size.ws_col, size.ws_row);
1147 if (FD_ISSET(STDIN_FILENO, &rset)) {
1151 if (connopen && back->connected(backhandle)) {
1152 ret = read(STDIN_FILENO, buf, sizeof(buf));
1154 perror("stdin: read");
1156 } else if (ret == 0) {
1157 back->special(backhandle, TS_EOF);
1158 sending = FALSE; /* send nothing further after this */
1163 back->send(backhandle, buf, ret);
1168 if (FD_ISSET(STDOUT_FILENO, &wset)) {
1169 back->unthrottle(backhandle, try_output(FALSE));
1172 if (FD_ISSET(STDERR_FILENO, &wset)) {
1173 back->unthrottle(backhandle, try_output(TRUE));
1176 run_toplevel_callbacks();
1178 if ((!connopen || !back->connected(backhandle)) &&
1179 bufchain_size(&stdout_data) == 0 &&
1180 bufchain_size(&stderr_data) == 0)
1181 break; /* we closed the connection */
1183 exitcode = back->exitcode(backhandle);
1185 fprintf(stderr, "Remote process exit code unavailable\n");
1186 exitcode = 1; /* this is an error condition */
1188 cleanup_exit(exitcode);
1189 return exitcode; /* shouldn't happen, but placates gcc */