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