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