]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxplink.c
First crack at `terminal-modes' in SSH. PuTTY now sends ERASE by default,
[PuTTY.git] / unix / uxplink.c
1 /*
2  * PLink - a command-line (stdin/stdout) variant of PuTTY.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <errno.h>
8 #include <assert.h>
9 #include <stdarg.h>
10 #include <signal.h>
11 #include <unistd.h>
12 #include <fcntl.h>
13 #include <termios.h>
14 #include <pwd.h>
15 #include <sys/ioctl.h>
16 #include <sys/select.h>
17
18 #define PUTTY_DO_GLOBALS               /* actually _define_ globals */
19 #include "putty.h"
20 #include "storage.h"
21 #include "tree234.h"
22
23 #define MAX_STDIN_BACKLOG 4096
24
25 void fatalbox(char *p, ...)
26 {
27     va_list ap;
28     fprintf(stderr, "FATAL ERROR: ");
29     va_start(ap, p);
30     vfprintf(stderr, p, ap);
31     va_end(ap);
32     fputc('\n', stderr);
33     cleanup_exit(1);
34 }
35 void modalfatalbox(char *p, ...)
36 {
37     va_list ap;
38     fprintf(stderr, "FATAL ERROR: ");
39     va_start(ap, p);
40     vfprintf(stderr, p, ap);
41     va_end(ap);
42     fputc('\n', stderr);
43     cleanup_exit(1);
44 }
45 void connection_fatal(void *frontend, char *p, ...)
46 {
47     va_list ap;
48     fprintf(stderr, "FATAL ERROR: ");
49     va_start(ap, p);
50     vfprintf(stderr, p, ap);
51     va_end(ap);
52     fputc('\n', stderr);
53     cleanup_exit(1);
54 }
55 void cmdline_error(char *p, ...)
56 {
57     va_list ap;
58     fprintf(stderr, "plink: ");
59     va_start(ap, p);
60     vfprintf(stderr, p, ap);
61     va_end(ap);
62     fputc('\n', stderr);
63     exit(1);
64 }
65
66 static int local_tty = 0; /* do we have a local tty? */
67 static struct termios orig_termios;
68
69 static Backend *back;
70 static void *backhandle;
71 static Config cfg;
72
73 /*
74  * Default settings that are specific to pterm.
75  */
76 char *platform_default_s(const char *name)
77 {
78     if (!strcmp(name, "TermType"))
79         return dupstr(getenv("TERM"));
80     if (!strcmp(name, "UserName"))
81         return get_username();
82     return NULL;
83 }
84
85 int platform_default_i(const char *name, int def)
86 {
87     if (!strcmp(name, "TermWidth") ||
88         !strcmp(name, "TermHeight")) {
89         struct winsize size;
90         if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
91             return (!strcmp(name, "TermWidth") ? size.ws_col : size.ws_row);
92     }
93     return def;
94 }
95
96 FontSpec platform_default_fontspec(const char *name)
97 {
98     FontSpec ret;
99     *ret.name = '\0';
100     return ret;
101 }
102
103 Filename platform_default_filename(const char *name)
104 {
105     Filename ret;
106     if (!strcmp(name, "LogFileName"))
107         strcpy(ret.path, "putty.log");
108     else
109         *ret.path = '\0';
110     return ret;
111 }
112
113 char *x_get_default(const char *key)
114 {
115     return NULL;                       /* this is a stub */
116 }
117 int term_ldisc(Terminal *term, int mode)
118 {
119     return FALSE;
120 }
121 void ldisc_update(void *frontend, int echo, int edit)
122 {
123     /* Update stdin read mode to reflect changes in line discipline. */
124     struct termios mode;
125
126     if (!local_tty) return;
127
128     mode = orig_termios;
129
130     if (echo)
131         mode.c_lflag |= ECHO;
132     else
133         mode.c_lflag &= ~ECHO;
134
135     if (edit) {
136         mode.c_iflag |= ICRNL;
137         mode.c_lflag |= ISIG | ICANON;
138     } else {
139         mode.c_iflag &= ~ICRNL;
140         mode.c_lflag &= ~(ISIG | ICANON);
141         /* Solaris sets these to unhelpful values */
142         mode.c_cc[VMIN] = 1;
143         mode.c_cc[VTIME] = 0;
144         /* FIXME: perhaps what we do with IXON/IXOFF should be an
145          * argument to ldisc_update(), to allow implementation of SSH-2
146          * "xon-xoff" and Rlogin's equivalent? */
147         mode.c_iflag &= ~IXON;
148         mode.c_iflag &= ~IXOFF;
149     }
150
151     tcsetattr(0, TCSANOW, &mode);
152 }
153
154 /* Helper function to extract a special character from a termios. */
155 static char *get_ttychar(struct termios *t, int index)
156 {
157     cc_t c = t->c_cc[index];
158 #if defined(_POSIX_VDISABLE)
159     if (c == _POSIX_VDISABLE)
160         return dupprintf("");
161 #endif
162     return dupprintf("^<%d>", c);
163 }
164
165 char *get_ttymode(void *frontend, const char *mode)
166 {
167     /*
168      * Propagate appropriate terminal modes from the local terminal,
169      * if any.
170      */
171     if (!local_tty) return NULL;
172
173 #define GET_CHAR(ourname, uxname) \
174     do { \
175         if (strcmp(mode, ourname) == 0) \
176             return get_ttychar(&orig_termios, uxname); \
177     } while(0)
178 #define GET_BOOL(ourname, uxname, uxmemb, transform) \
179     do { \
180         if (strcmp(mode, ourname) == 0) { \
181             int b = (orig_termios.uxmemb & uxname) != 0; \
182             transform; \
183             return dupprintf("%d", b); \
184         } \
185     } while (0)
186
187     /*
188      * Modes that want to be the same on all terminal devices involved.
189      */
190     /* All the special characters supported by SSH */
191 #if defined(VINTR)
192     GET_CHAR("INTR", VINTR);
193 #endif
194 #if defined(VQUIT)
195     GET_CHAR("QUIT", VQUIT);
196 #endif
197 #if defined(VERASE)
198     GET_CHAR("ERASE", VERASE);
199 #endif
200 #if defined(VKILL)
201     GET_CHAR("KILL", VKILL);
202 #endif
203 #if defined(VEOF)
204     GET_CHAR("EOF", VEOF);
205 #endif
206 #if defined(VEOL)
207     GET_CHAR("EOL", VEOL);
208 #endif
209 #if defined(VEOL2)
210     GET_CHAR("EOL2", VEOL2);
211 #endif
212 #if defined(VSTART)
213     GET_CHAR("START", VSTART);
214 #endif
215 #if defined(VSTOP)
216     GET_CHAR("STOP", VSTOP);
217 #endif
218 #if defined(VSUSP)
219     GET_CHAR("SUSP", VSUSP);
220 #endif
221 #if defined(VDSUSP)
222     GET_CHAR("DSUSP", VDSUSP);
223 #endif
224 #if defined(VREPRINT)
225     GET_CHAR("REPRINT", VREPRINT);
226 #endif
227 #if defined(VWERASE)
228     GET_CHAR("WERASE", VWERASE);
229 #endif
230 #if defined(VLNEXT)
231     GET_CHAR("LNEXT", VLNEXT);
232 #endif
233 #if defined(VFLUSH)
234     GET_CHAR("FLUSH", VFLUSH);
235 #endif
236 #if defined(VSWTCH)
237     GET_CHAR("SWTCH", VSWTCH);
238 #endif
239 #if defined(VSTATUS)
240     GET_CHAR("STATUS", VSTATUS);
241 #endif
242 #if defined(VDISCARD)
243     GET_CHAR("DISCARD", VDISCARD);
244 #endif
245     /* Modes that "configure" other major modes. These should probably be
246      * considered as user preferences. */
247     /* Configuration of ICANON */
248 #if defined(ECHOK)
249     GET_BOOL("ECHOK", ECHOK, c_lflag, );
250 #endif
251 #if defined(ECHOKE)
252     GET_BOOL("ECHOKE", ECHOKE, c_lflag, );
253 #endif
254 #if defined(ECHOE)
255     GET_BOOL("ECHOE", ECHOE, c_lflag, );
256 #endif
257 #if defined(ECHONL)
258     GET_BOOL("ECHONL", ECHONL, c_lflag, );
259 #endif
260 #if defined(XCASE)
261     GET_BOOL("XCASE", XCASE, c_lflag, );
262 #endif
263     /* Configuration of ECHO */
264 #if defined(ECHOCTL)
265     GET_BOOL("ECHOCTL", ECHOCTL, c_lflag, );
266 #endif
267     /* Configuration of IXON/IXOFF */
268 #if defined(IXANY)
269     GET_BOOL("IXANY", IXANY, c_iflag, );
270 #endif
271
272     /*
273      * Modes that want to be set in only one place, and that we have
274      * squashed locally.
275      */
276 #if defined(ISIG)
277     GET_BOOL("ISIG", ISIG, c_lflag, );
278 #endif
279 #if defined(ICANON)
280     GET_BOOL("ICANON", ICANON, c_lflag, );
281 #endif
282 #if defined(ECHO)
283     GET_BOOL("ECHO", ECHO, c_lflag, );
284 #endif
285 #if defined(IXON)
286     GET_BOOL("IXON", IXON, c_iflag, );
287 #endif
288 #if defined(IXOFF)
289     GET_BOOL("IXOFF", IXOFF, c_iflag, );
290 #endif
291
292     /*
293      * We do not propagate the following modes:
294      *  - Parity/serial settings, which are a local affair and don't
295      *    make sense propagated over SSH's 8-bit byte-stream.
296      *      IGNPAR PARMRK INPCK CS7 CS8 PARENB PARODD
297      *  - Things that want to be enabled in one place that we don't
298      *    squash locally.
299      *      IUCLC OLCUC
300      *  - Status bits.
301      *      PENDIN
302      *  - Things I don't know what to do with. (FIXME)
303      *      ISTRIP IMAXBEL NOFLSH TOSTOP IEXTEN OPOST 
304      *      INLCR IGNCR ICRNL ONLCR OCRNL ONOCR ONLRET
305      */
306
307 #undef GET_CHAR
308 #undef GET_BOOL
309
310     /* Fall through to here for unrecognised names, or ones that are
311      * unsupported on this platform */
312     return NULL;
313 }
314
315 void cleanup_termios(void)
316 {
317     if (local_tty)
318         tcsetattr(0, TCSANOW, &orig_termios);
319 }
320
321 bufchain stdout_data, stderr_data;
322
323 void try_output(int is_stderr)
324 {
325     bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
326     int fd = (is_stderr ? 2 : 1);
327     void *senddata;
328     int sendlen, ret;
329
330     if (bufchain_size(chain) == 0)
331         return;
332
333     bufchain_prefix(chain, &senddata, &sendlen);
334     ret = write(fd, senddata, sendlen);
335     if (ret > 0)
336         bufchain_consume(chain, ret);
337     else if (ret < 0) {
338         perror(is_stderr ? "stderr: write" : "stdout: write");
339         exit(1);
340     }
341 }
342
343 int from_backend(void *frontend_handle, int is_stderr,
344                  const char *data, int len)
345 {
346     int osize, esize;
347
348     if (is_stderr) {
349         bufchain_add(&stderr_data, data, len);
350         try_output(1);
351     } else {
352         bufchain_add(&stdout_data, data, len);
353         try_output(0);
354     }
355
356     osize = bufchain_size(&stdout_data);
357     esize = bufchain_size(&stderr_data);
358
359     return osize + esize;
360 }
361
362 int signalpipe[2];
363
364 void sigwinch(int signum)
365 {
366     write(signalpipe[1], "x", 1);
367 }
368
369 /*
370  * In Plink our selects are synchronous, so these functions are
371  * empty stubs.
372  */
373 int uxsel_input_add(int fd, int rwx) { return 0; }
374 void uxsel_input_remove(int id) { }
375
376 /*
377  * Short description of parameters.
378  */
379 static void usage(void)
380 {
381     printf("PuTTY Link: command-line connection utility\n");
382     printf("%s\n", ver);
383     printf("Usage: plink [options] [user@]host [command]\n");
384     printf("       (\"host\" can also be a PuTTY saved session name)\n");
385     printf("Options:\n");
386     printf("  -V        print version information and exit\n");
387     printf("  -pgpfp    print PGP key fingerprints and exit\n");
388     printf("  -v        show verbose messages\n");
389     printf("  -load sessname  Load settings from saved session\n");
390     printf("  -ssh -telnet -rlogin -raw\n");
391     printf("            force use of a particular protocol\n");
392     printf("  -P port   connect to specified port\n");
393     printf("  -l user   connect with specified username\n");
394     printf("  -batch    disable all interactive prompts\n");
395     printf("The following options only apply to SSH connections:\n");
396     printf("  -pw passw login with specified password\n");
397     printf("  -D [listen-IP:]listen-port\n");
398     printf("            Dynamic SOCKS-based port forwarding\n");
399     printf("  -L [listen-IP:]listen-port:host:port\n");
400     printf("            Forward local port to remote address\n");
401     printf("  -R [listen-IP:]listen-port:host:port\n");
402     printf("            Forward remote port to local address\n");
403     printf("  -X -x     enable / disable X11 forwarding\n");
404     printf("  -A -a     enable / disable agent forwarding\n");
405     printf("  -t -T     enable / disable pty allocation\n");
406     printf("  -1 -2     force use of particular protocol version\n");
407     printf("  -4 -6     force use of IPv4 or IPv6\n");
408     printf("  -C        enable compression\n");
409     printf("  -i key    private key file for authentication\n");
410     printf("  -m file   read remote command(s) from file\n");
411     printf("  -s        remote command is an SSH subsystem (SSH-2 only)\n");
412     printf("  -N        don't start a shell/command (SSH-2 only)\n");
413     exit(1);
414 }
415
416 static void version(void)
417 {
418     printf("plink: %s\n", ver);
419     exit(1);
420 }
421
422 int main(int argc, char **argv)
423 {
424     int sending;
425     int portnumber = -1;
426     int *fdlist;
427     int fd;
428     int i, fdcount, fdsize, fdstate;
429     int connopen;
430     int exitcode;
431     int errors;
432     int use_subsystem = 0;
433     void *ldisc, *logctx;
434     long now;
435
436     ssh_get_line = console_get_line;
437
438     fdlist = NULL;
439     fdcount = fdsize = 0;
440     /*
441      * Initialise port and protocol to sensible defaults. (These
442      * will be overridden by more or less anything.)
443      */
444     default_protocol = PROT_SSH;
445     default_port = 22;
446
447     flags = FLAG_STDERR;
448     /*
449      * Process the command line.
450      */
451     do_defaults(NULL, &cfg);
452     loaded_session = FALSE;
453     default_protocol = cfg.protocol;
454     default_port = cfg.port;
455     errors = 0;
456     {
457         /*
458          * Override the default protocol if PLINK_PROTOCOL is set.
459          */
460         char *p = getenv("PLINK_PROTOCOL");
461         int i;
462         if (p) {
463             for (i = 0; backends[i].backend != NULL; i++) {
464                 if (!strcmp(backends[i].name, p)) {
465                     default_protocol = cfg.protocol = backends[i].protocol;
466                     default_port = cfg.port =
467                         backends[i].backend->default_port;
468                     break;
469                 }
470             }
471         }
472     }
473     while (--argc) {
474         char *p = *++argv;
475         if (*p == '-') {
476             int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
477                                             1, &cfg);
478             if (ret == -2) {
479                 fprintf(stderr,
480                         "plink: option \"%s\" requires an argument\n", p);
481                 errors = 1;
482             } else if (ret == 2) {
483                 --argc, ++argv;
484             } else if (ret == 1) {
485                 continue;
486             } else if (!strcmp(p, "-batch")) {
487                 console_batch_mode = 1;
488             } else if (!strcmp(p, "-s")) {
489                 /* Save status to write to cfg later. */
490                 use_subsystem = 1;
491             } else if (!strcmp(p, "-V")) {
492                 version();
493             } else if (!strcmp(p, "-pgpfp")) {
494                 pgp_fingerprints();
495                 exit(1);
496             } else if (!strcmp(p, "-o")) {
497                 if (argc <= 1) {
498                     fprintf(stderr,
499                             "plink: option \"-o\" requires an argument\n");
500                     errors = 1;
501                 } else {
502                     --argc;
503                     provide_xrm_string(*++argv);
504                 }
505             } else {
506                 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
507                 errors = 1;
508             }
509         } else if (*p) {
510             if (!*cfg.host) {
511                 char *q = p;
512
513                 do_defaults(NULL, &cfg);
514
515                 /*
516                  * If the hostname starts with "telnet:", set the
517                  * protocol to Telnet and process the string as a
518                  * Telnet URL.
519                  */
520                 if (!strncmp(q, "telnet:", 7)) {
521                     char c;
522
523                     q += 7;
524                     if (q[0] == '/' && q[1] == '/')
525                         q += 2;
526                     cfg.protocol = PROT_TELNET;
527                     p = q;
528                     while (*p && *p != ':' && *p != '/')
529                         p++;
530                     c = *p;
531                     if (*p)
532                         *p++ = '\0';
533                     if (c == ':')
534                         cfg.port = atoi(p);
535                     else
536                         cfg.port = -1;
537                     strncpy(cfg.host, q, sizeof(cfg.host) - 1);
538                     cfg.host[sizeof(cfg.host) - 1] = '\0';
539                 } else {
540                     char *r, *user, *host;
541                     /*
542                      * Before we process the [user@]host string, we
543                      * first check for the presence of a protocol
544                      * prefix (a protocol name followed by ",").
545                      */
546                     r = strchr(p, ',');
547                     if (r) {
548                         int i, j;
549                         for (i = 0; backends[i].backend != NULL; i++) {
550                             j = strlen(backends[i].name);
551                             if (j == r - p &&
552                                 !memcmp(backends[i].name, p, j)) {
553                                 default_protocol = cfg.protocol =
554                                     backends[i].protocol;
555                                 portnumber =
556                                     backends[i].backend->default_port;
557                                 p = r + 1;
558                                 break;
559                             }
560                         }
561                     }
562
563                     /*
564                      * A nonzero length string followed by an @ is treated
565                      * as a username. (We discount an _initial_ @.) The
566                      * rest of the string (or the whole string if no @)
567                      * is treated as a session name and/or hostname.
568                      */
569                     r = strrchr(p, '@');
570                     if (r == p)
571                         p++, r = NULL; /* discount initial @ */
572                     if (r) {
573                         *r++ = '\0';
574                         user = p, host = r;
575                     } else {
576                         user = NULL, host = p;
577                     }
578
579                     /*
580                      * Now attempt to load a saved session with the
581                      * same name as the hostname.
582                      */
583                     {
584                         Config cfg2;
585                         do_defaults(host, &cfg2);
586                         if (loaded_session || cfg2.host[0] == '\0') {
587                             /* No settings for this host; use defaults */
588                             /* (or session was already loaded with -load) */
589                             strncpy(cfg.host, host, sizeof(cfg.host) - 1);
590                             cfg.host[sizeof(cfg.host) - 1] = '\0';
591                             cfg.port = default_port;
592                         } else {
593                             cfg = cfg2;
594                         }
595                     }
596
597                     if (user) {
598                         /* Patch in specified username. */
599                         strncpy(cfg.username, user,
600                                 sizeof(cfg.username) - 1);
601                         cfg.username[sizeof(cfg.username) - 1] = '\0';
602                     }
603
604                 }
605             } else {
606                 char *command;
607                 int cmdlen, cmdsize;
608                 cmdlen = cmdsize = 0;
609                 command = NULL;
610
611                 while (argc) {
612                     while (*p) {
613                         if (cmdlen >= cmdsize) {
614                             cmdsize = cmdlen + 512;
615                             command = sresize(command, cmdsize, char);
616                         }
617                         command[cmdlen++]=*p++;
618                     }
619                     if (cmdlen >= cmdsize) {
620                         cmdsize = cmdlen + 512;
621                         command = sresize(command, cmdsize, char);
622                     }
623                     command[cmdlen++]=' '; /* always add trailing space */
624                     if (--argc) p = *++argv;
625                 }
626                 if (cmdlen) command[--cmdlen]='\0';
627                                        /* change trailing blank to NUL */
628                 cfg.remote_cmd_ptr = command;
629                 cfg.remote_cmd_ptr2 = NULL;
630                 cfg.nopty = TRUE;      /* command => no terminal */
631
632                 break;                 /* done with cmdline */
633             }
634         }
635     }
636
637     if (errors)
638         return 1;
639
640     if (!*cfg.host) {
641         usage();
642     }
643
644     /*
645      * Trim leading whitespace off the hostname if it's there.
646      */
647     {
648         int space = strspn(cfg.host, " \t");
649         memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
650     }
651
652     /* See if host is of the form user@host */
653     if (cfg.host[0] != '\0') {
654         char *atsign = strrchr(cfg.host, '@');
655         /* Make sure we're not overflowing the user field */
656         if (atsign) {
657             if (atsign - cfg.host < sizeof cfg.username) {
658                 strncpy(cfg.username, cfg.host, atsign - cfg.host);
659                 cfg.username[atsign - cfg.host] = '\0';
660             }
661             memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
662         }
663     }
664
665     /*
666      * Perform command-line overrides on session configuration.
667      */
668     cmdline_run_saved(&cfg);
669
670     /*
671      * Apply subsystem status.
672      */
673     if (use_subsystem)
674         cfg.ssh_subsys = TRUE;
675
676     /*
677      * Trim a colon suffix off the hostname if it's there.
678      */
679     cfg.host[strcspn(cfg.host, ":")] = '\0';
680
681     /*
682      * Remove any remaining whitespace from the hostname.
683      */
684     {
685         int p1 = 0, p2 = 0;
686         while (cfg.host[p2] != '\0') {
687             if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
688                 cfg.host[p1] = cfg.host[p2];
689                 p1++;
690             }
691             p2++;
692         }
693         cfg.host[p1] = '\0';
694     }
695
696     if (!cfg.remote_cmd_ptr && !*cfg.remote_cmd)
697         flags |= FLAG_INTERACTIVE;
698
699     /*
700      * Select protocol. This is farmed out into a table in a
701      * separate file to enable an ssh-free variant.
702      */
703     {
704         int i;
705         back = NULL;
706         for (i = 0; backends[i].backend != NULL; i++)
707             if (backends[i].protocol == cfg.protocol) {
708                 back = backends[i].backend;
709                 break;
710             }
711         if (back == NULL) {
712             fprintf(stderr,
713                     "Internal fault: Unsupported protocol found\n");
714             return 1;
715         }
716     }
717
718     /*
719      * Select port.
720      */
721     if (portnumber != -1)
722         cfg.port = portnumber;
723
724     /*
725      * Set up the pipe we'll use to tell us about SIGWINCH.
726      */
727     if (pipe(signalpipe) < 0) {
728         perror("pipe");
729         exit(1);
730     }
731     putty_signal(SIGWINCH, sigwinch);
732
733     sk_init();
734     uxsel_init();
735
736     /*
737      * Start up the connection.
738      */
739     logctx = log_init(NULL, &cfg);
740     console_provide_logctx(logctx);
741     {
742         const char *error;
743         char *realhost;
744         /* nodelay is only useful if stdin is a terminal device */
745         int nodelay = cfg.tcp_nodelay && isatty(0);
746
747         error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
748                            &realhost, nodelay, cfg.tcp_keepalives);
749         if (error) {
750             fprintf(stderr, "Unable to open connection:\n%s\n", error);
751             return 1;
752         }
753         back->provide_logctx(backhandle, logctx);
754         ldisc = ldisc_create(&cfg, NULL, back, backhandle, NULL);
755         sfree(realhost);
756     }
757     connopen = 1;
758
759     /*
760      * Set up the initial console mode. We don't care if this call
761      * fails, because we know we aren't necessarily running in a
762      * console.
763      */
764     local_tty = (tcgetattr(0, &orig_termios) == 0);
765     atexit(cleanup_termios);
766     ldisc_update(NULL, 1, 1);
767     sending = FALSE;
768     now = GETTICKCOUNT();
769
770     while (1) {
771         fd_set rset, wset, xset;
772         int maxfd;
773         int rwx;
774         int ret;
775
776         FD_ZERO(&rset);
777         FD_ZERO(&wset);
778         FD_ZERO(&xset);
779         maxfd = 0;
780
781         FD_SET_MAX(signalpipe[0], maxfd, rset);
782
783         if (connopen && !sending &&
784             back->socket(backhandle) != NULL &&
785             back->sendok(backhandle) &&
786             back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
787             /* If we're OK to send, then try to read from stdin. */
788             FD_SET_MAX(0, maxfd, rset);
789         }
790
791         if (bufchain_size(&stdout_data) > 0) {
792             /* If we have data for stdout, try to write to stdout. */
793             FD_SET_MAX(1, maxfd, wset);
794         }
795
796         if (bufchain_size(&stderr_data) > 0) {
797             /* If we have data for stderr, try to write to stderr. */
798             FD_SET_MAX(2, maxfd, wset);
799         }
800
801         /* Count the currently active fds. */
802         i = 0;
803         for (fd = first_fd(&fdstate, &rwx); fd >= 0;
804              fd = next_fd(&fdstate, &rwx)) i++;
805
806         /* Expand the fdlist buffer if necessary. */
807         if (i > fdsize) {
808             fdsize = i + 16;
809             fdlist = sresize(fdlist, fdsize, int);
810         }
811
812         /*
813          * Add all currently open fds to the select sets, and store
814          * them in fdlist as well.
815          */
816         fdcount = 0;
817         for (fd = first_fd(&fdstate, &rwx); fd >= 0;
818              fd = next_fd(&fdstate, &rwx)) {
819             fdlist[fdcount++] = fd;
820             if (rwx & 1)
821                 FD_SET_MAX(fd, maxfd, rset);
822             if (rwx & 2)
823                 FD_SET_MAX(fd, maxfd, wset);
824             if (rwx & 4)
825                 FD_SET_MAX(fd, maxfd, xset);
826         }
827
828         do {
829             long next, ticks;
830             struct timeval tv, *ptv;
831
832             if (run_timers(now, &next)) {
833                 ticks = next - GETTICKCOUNT();
834                 if (ticks < 0) ticks = 0;   /* just in case */
835                 tv.tv_sec = ticks / 1000;
836                 tv.tv_usec = ticks % 1000 * 1000;
837                 ptv = &tv;
838             } else {
839                 ptv = NULL;
840             }
841             ret = select(maxfd, &rset, &wset, &xset, ptv);
842             if (ret == 0)
843                 now = next;
844             else {
845                 long newnow = GETTICKCOUNT();
846                 /*
847                  * Check to see whether the system clock has
848                  * changed massively during the select.
849                  */
850                 if (newnow - now < 0 || newnow - now > next - now) {
851                     /*
852                      * If so, look at the elapsed time in the
853                      * select and use it to compute a new
854                      * tickcount_offset.
855                      */
856                     long othernow = now + tv.tv_sec * 1000 + tv.tv_usec / 1000;
857                     /* So we'd like GETTICKCOUNT to have returned othernow,
858                      * but instead it return newnow. Hence ... */
859                     tickcount_offset += othernow - newnow;
860                     now = othernow;
861                 } else {
862                     now = newnow;
863                 }
864             }
865         } while (ret < 0 && errno == EINTR);
866
867         if (ret < 0) {
868             perror("select");
869             exit(1);
870         }
871
872         for (i = 0; i < fdcount; i++) {
873             fd = fdlist[i];
874             /*
875              * We must process exceptional notifications before
876              * ordinary readability ones, or we may go straight
877              * past the urgent marker.
878              */
879             if (FD_ISSET(fd, &xset))
880                 select_result(fd, 4);
881             if (FD_ISSET(fd, &rset))
882                 select_result(fd, 1);
883             if (FD_ISSET(fd, &wset))
884                 select_result(fd, 2);
885         }
886
887         if (FD_ISSET(signalpipe[0], &rset)) {
888             char c[1];
889             struct winsize size;
890             read(signalpipe[0], c, 1); /* ignore its value; it'll be `x' */
891             if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
892                 back->size(backhandle, size.ws_col, size.ws_row);
893         }
894
895         if (FD_ISSET(0, &rset)) {
896             char buf[4096];
897             int ret;
898
899             if (connopen && back->socket(backhandle) != NULL) {
900                 ret = read(0, buf, sizeof(buf));
901                 if (ret < 0) {
902                     perror("stdin: read");
903                     exit(1);
904                 } else if (ret == 0) {
905                     back->special(backhandle, TS_EOF);
906                     sending = FALSE;   /* send nothing further after this */
907                 } else {
908                     back->send(backhandle, buf, ret);
909                 }
910             }
911         }
912
913         if (FD_ISSET(1, &wset)) {
914             try_output(0);
915         }
916
917         if (FD_ISSET(2, &wset)) {
918             try_output(1);
919         }
920
921         if ((!connopen || back->socket(backhandle) == NULL) &&
922             bufchain_size(&stdout_data) == 0 &&
923             bufchain_size(&stderr_data) == 0)
924             break;                     /* we closed the connection */
925     }
926     exitcode = back->exitcode(backhandle);
927     if (exitcode < 0) {
928         fprintf(stderr, "Remote process exit code unavailable\n");
929         exitcode = 1;                  /* this is an error condition */
930     }
931     cleanup_exit(exitcode);
932     return exitcode;                   /* shouldn't happen, but placates gcc */
933 }