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