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