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