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