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