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