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