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