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