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