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