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