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