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