OSDN Git Service

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