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