Integrate unfix.org's IPv6 patches up to level 10, with rather a lot
[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>
c5e438ec 16
c5e438ec 17#define PUTTY_DO_GLOBALS /* actually _define_ globals */
18#include "putty.h"
19#include "storage.h"
20#include "tree234.h"
21
22#define MAX_STDIN_BACKLOG 4096
23
24void fatalbox(char *p, ...)
25{
26 va_list ap;
27 fprintf(stderr, "FATAL ERROR: ");
28 va_start(ap, p);
29 vfprintf(stderr, p, ap);
30 va_end(ap);
31 fputc('\n', stderr);
32 cleanup_exit(1);
33}
34void modalfatalbox(char *p, ...)
35{
36 va_list ap;
37 fprintf(stderr, "FATAL ERROR: ");
38 va_start(ap, p);
39 vfprintf(stderr, p, ap);
40 va_end(ap);
41 fputc('\n', stderr);
42 cleanup_exit(1);
43}
44void connection_fatal(void *frontend, char *p, ...)
45{
46 va_list ap;
47 fprintf(stderr, "FATAL ERROR: ");
48 va_start(ap, p);
49 vfprintf(stderr, p, ap);
50 va_end(ap);
51 fputc('\n', stderr);
52 cleanup_exit(1);
53}
54void cmdline_error(char *p, ...)
55{
56 va_list ap;
57 fprintf(stderr, "plink: ");
58 va_start(ap, p);
59 vfprintf(stderr, p, ap);
60 va_end(ap);
61 fputc('\n', stderr);
62 exit(1);
63}
64
65struct termios orig_termios;
66
67static Backend *back;
68static void *backhandle;
3ea863a3 69static Config cfg;
c5e438ec 70
5a9eb105 71/*
72 * Default settings that are specific to pterm.
73 */
c85623f9 74char *platform_default_s(const char *name)
5a9eb105 75{
5a9eb105 76 if (!strcmp(name, "TermType"))
799dfcfa 77 return dupstr(getenv("TERM"));
78 if (!strcmp(name, "UserName"))
79 return get_username();
5a9eb105 80 return NULL;
81}
82
c85623f9 83int platform_default_i(const char *name, int def)
5a9eb105 84{
85 if (!strcmp(name, "TermWidth") ||
86 !strcmp(name, "TermHeight")) {
87 struct winsize size;
88 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
89 return (!strcmp(name, "TermWidth") ? size.ws_col : size.ws_row);
90 }
91 return def;
92}
93
9a30e26b 94FontSpec platform_default_fontspec(const char *name)
95{
96 FontSpec ret;
97 *ret.name = '\0';
98 return ret;
99}
100
101Filename platform_default_filename(const char *name)
102{
103 Filename ret;
104 if (!strcmp(name, "LogFileName"))
105 strcpy(ret.path, "putty.log");
106 else
107 *ret.path = '\0';
108 return ret;
109}
110
c85623f9 111char *x_get_default(const char *key)
c5e438ec 112{
113 return NULL; /* this is a stub */
114}
115int term_ldisc(Terminal *term, int mode)
116{
117 return FALSE;
118}
119void ldisc_update(void *frontend, int echo, int edit)
120{
121 /* Update stdin read mode to reflect changes in line discipline. */
122 struct termios mode;
123
124 mode = orig_termios;
125
126 if (echo)
127 mode.c_lflag |= ECHO;
128 else
129 mode.c_lflag &= ~ECHO;
130
131 if (edit)
132 mode.c_lflag |= ISIG | ICANON;
133 else
134 mode.c_lflag &= ~(ISIG | ICANON);
135
136 tcsetattr(0, TCSANOW, &mode);
137}
138
139void cleanup_termios(void)
140{
141 tcsetattr(0, TCSANOW, &orig_termios);
142}
143
144bufchain stdout_data, stderr_data;
145
146void try_output(int is_stderr)
147{
148 bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
149 int fd = (is_stderr ? 2 : 1);
150 void *senddata;
151 int sendlen, ret;
152
d69a46c0 153 if (bufchain_size(chain) == 0)
154 return;
155
c5e438ec 156 bufchain_prefix(chain, &senddata, &sendlen);
157 ret = write(fd, senddata, sendlen);
158 if (ret > 0)
159 bufchain_consume(chain, ret);
160 else if (ret < 0) {
161 perror(is_stderr ? "stderr: write" : "stdout: write");
162 exit(1);
163 }
164}
165
9fab77dc 166int from_backend(void *frontend_handle, int is_stderr,
167 const char *data, int len)
c5e438ec 168{
169 int osize, esize;
170
c5e438ec 171 if (is_stderr) {
172 bufchain_add(&stderr_data, data, len);
173 try_output(1);
174 } else {
175 bufchain_add(&stdout_data, data, len);
176 try_output(0);
177 }
178
179 osize = bufchain_size(&stdout_data);
180 esize = bufchain_size(&stderr_data);
181
182 return osize + esize;
183}
184
5673d44e 185int signalpipe[2];
186
187void sigwinch(int signum)
188{
189 write(signalpipe[1], "x", 1);
190}
191
c5e438ec 192/*
74aca06d 193 * In Plink our selects are synchronous, so these functions are
194 * empty stubs.
195 */
196int uxsel_input_add(int fd, int rwx) { return 0; }
197void uxsel_input_remove(int id) { }
198
199/*
c5e438ec 200 * Short description of parameters.
201 */
202static void usage(void)
203{
204 printf("PuTTY Link: command-line connection utility\n");
205 printf("%s\n", ver);
206 printf("Usage: plink [options] [user@]host [command]\n");
207 printf(" (\"host\" can also be a PuTTY saved session name)\n");
208 printf("Options:\n");
c9a13be6 209 printf(" -V print version information\n");
c5e438ec 210 printf(" -v show verbose messages\n");
211 printf(" -load sessname Load settings from saved session\n");
212 printf(" -ssh -telnet -rlogin -raw\n");
afd4d0d2 213 printf(" force use of a particular protocol\n");
c5e438ec 214 printf(" -P port connect to specified port\n");
215 printf(" -l user connect with specified username\n");
216 printf(" -m file read remote command(s) from file\n");
217 printf(" -batch disable all interactive prompts\n");
218 printf("The following options only apply to SSH connections:\n");
219 printf(" -pw passw login with specified password\n");
dbe6c525 220 printf(" -D [listen-IP:]listen-port\n");
221 printf(" Dynamic SOCKS-based port forwarding\n");
222 printf(" -L [listen-IP:]listen-port:host:port\n");
223 printf(" Forward local port to remote address\n");
224 printf(" -R [listen-IP:]listen-port:host:port\n");
225 printf(" Forward remote port to local address\n");
c5e438ec 226 printf(" -X -x enable / disable X11 forwarding\n");
227 printf(" -A -a enable / disable agent forwarding\n");
228 printf(" -t -T enable / disable pty allocation\n");
229 printf(" -1 -2 force use of particular protocol version\n");
05581745 230 printf(" -4 -6 force use of IPv4 or IPv6\n");
c5e438ec 231 printf(" -C enable compression\n");
232 printf(" -i key private key file for authentication\n");
09bdfcbb 233 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
b72c366d 234 printf(" -N don't start a shell/command (SSH-2 only)\n");
dc108ebc 235 exit(1);
236}
237
238static void version(void)
239{
240 printf("plink: %s\n", ver);
c5e438ec 241 exit(1);
242}
243
244int main(int argc, char **argv)
245{
246 int sending;
247 int portnumber = -1;
0ff9ea38 248 int *fdlist;
249 int fd;
250 int i, fdcount, fdsize, fdstate;
c5e438ec 251 int connopen;
252 int exitcode;
86256dc6 253 int errors;
09bdfcbb 254 int use_subsystem = 0;
b51259f6 255 void *ldisc, *logctx;
39934deb 256 long now;
c5e438ec 257
258 ssh_get_line = console_get_line;
259
0ff9ea38 260 fdlist = NULL;
261 fdcount = fdsize = 0;
c5e438ec 262 /*
263 * Initialise port and protocol to sensible defaults. (These
264 * will be overridden by more or less anything.)
265 */
266 default_protocol = PROT_SSH;
267 default_port = 22;
268
269 flags = FLAG_STDERR;
270 /*
271 * Process the command line.
272 */
273 do_defaults(NULL, &cfg);
18e62ad8 274 loaded_session = FALSE;
c5e438ec 275 default_protocol = cfg.protocol;
276 default_port = cfg.port;
86256dc6 277 errors = 0;
c5e438ec 278 {
279 /*
280 * Override the default protocol if PLINK_PROTOCOL is set.
281 */
282 char *p = getenv("PLINK_PROTOCOL");
283 int i;
284 if (p) {
285 for (i = 0; backends[i].backend != NULL; i++) {
286 if (!strcmp(backends[i].name, p)) {
287 default_protocol = cfg.protocol = backends[i].protocol;
288 default_port = cfg.port =
289 backends[i].backend->default_port;
290 break;
291 }
292 }
293 }
294 }
295 while (--argc) {
296 char *p = *++argv;
297 if (*p == '-') {
9b41d3a8 298 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
299 1, &cfg);
c5e438ec 300 if (ret == -2) {
301 fprintf(stderr,
302 "plink: option \"%s\" requires an argument\n", p);
86256dc6 303 errors = 1;
c5e438ec 304 } else if (ret == 2) {
305 --argc, ++argv;
306 } else if (ret == 1) {
307 continue;
308 } else if (!strcmp(p, "-batch")) {
309 console_batch_mode = 1;
09bdfcbb 310 } else if (!strcmp(p, "-s")) {
311 /* Save status to write to cfg later. */
312 use_subsystem = 1;
dc108ebc 313 } else if (!strcmp(p, "-V")) {
314 version();
a0e5ed33 315 } else if (!strcmp(p, "-o")) {
86256dc6 316 if (argc <= 1) {
a0e5ed33 317 fprintf(stderr,
318 "plink: option \"-o\" requires an argument\n");
86256dc6 319 errors = 1;
320 } else {
321 --argc;
322 provide_xrm_string(*++argv);
323 }
324 } else {
325 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
326 errors = 1;
c5e438ec 327 }
328 } else if (*p) {
329 if (!*cfg.host) {
330 char *q = p;
a0e5ed33 331
332 do_defaults(NULL, &cfg);
333
c5e438ec 334 /*
335 * If the hostname starts with "telnet:", set the
336 * protocol to Telnet and process the string as a
337 * Telnet URL.
338 */
339 if (!strncmp(q, "telnet:", 7)) {
340 char c;
341
342 q += 7;
343 if (q[0] == '/' && q[1] == '/')
344 q += 2;
345 cfg.protocol = PROT_TELNET;
346 p = q;
347 while (*p && *p != ':' && *p != '/')
348 p++;
349 c = *p;
350 if (*p)
351 *p++ = '\0';
352 if (c == ':')
353 cfg.port = atoi(p);
354 else
355 cfg.port = -1;
356 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
357 cfg.host[sizeof(cfg.host) - 1] = '\0';
358 } else {
3608528b 359 char *r, *user, *host;
c5e438ec 360 /*
361 * Before we process the [user@]host string, we
362 * first check for the presence of a protocol
363 * prefix (a protocol name followed by ",").
364 */
365 r = strchr(p, ',');
366 if (r) {
367 int i, j;
368 for (i = 0; backends[i].backend != NULL; i++) {
369 j = strlen(backends[i].name);
370 if (j == r - p &&
371 !memcmp(backends[i].name, p, j)) {
372 default_protocol = cfg.protocol =
373 backends[i].protocol;
374 portnumber =
375 backends[i].backend->default_port;
376 p = r + 1;
377 break;
378 }
379 }
380 }
381
382 /*
3608528b 383 * A nonzero length string followed by an @ is treated
384 * as a username. (We discount an _initial_ @.) The
385 * rest of the string (or the whole string if no @)
386 * is treated as a session name and/or hostname.
c5e438ec 387 */
388 r = strrchr(p, '@');
389 if (r == p)
390 p++, r = NULL; /* discount initial @ */
3608528b 391 if (r) {
392 *r++ = '\0';
393 user = p, host = r;
394 } else {
395 user = NULL, host = p;
396 }
397
398 /*
399 * Now attempt to load a saved session with the
400 * same name as the hostname.
401 */
402 {
c5e438ec 403 Config cfg2;
3608528b 404 do_defaults(host, &cfg2);
18e62ad8 405 if (loaded_session || cfg2.host[0] == '\0') {
c5e438ec 406 /* No settings for this host; use defaults */
18e62ad8 407 /* (or session was already loaded with -load) */
3608528b 408 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
c5e438ec 409 cfg.host[sizeof(cfg.host) - 1] = '\0';
410 cfg.port = default_port;
411 } else {
412 cfg = cfg2;
18e62ad8 413 /* Ick: patch up internal pointer after copy */
c5e438ec 414 cfg.remote_cmd_ptr = cfg.remote_cmd;
415 }
3608528b 416 }
417
418 if (user) {
419 /* Patch in specified username. */
420 strncpy(cfg.username, user,
421 sizeof(cfg.username) - 1);
c5e438ec 422 cfg.username[sizeof(cfg.username) - 1] = '\0';
c5e438ec 423 }
3608528b 424
c5e438ec 425 }
426 } else {
427 char *command;
428 int cmdlen, cmdsize;
429 cmdlen = cmdsize = 0;
430 command = NULL;
431
432 while (argc) {
433 while (*p) {
434 if (cmdlen >= cmdsize) {
435 cmdsize = cmdlen + 512;
3d88e64d 436 command = sresize(command, cmdsize, char);
c5e438ec 437 }
438 command[cmdlen++]=*p++;
439 }
440 if (cmdlen >= cmdsize) {
441 cmdsize = cmdlen + 512;
3d88e64d 442 command = sresize(command, cmdsize, char);
c5e438ec 443 }
444 command[cmdlen++]=' '; /* always add trailing space */
445 if (--argc) p = *++argv;
446 }
447 if (cmdlen) command[--cmdlen]='\0';
448 /* change trailing blank to NUL */
449 cfg.remote_cmd_ptr = command;
450 cfg.remote_cmd_ptr2 = NULL;
451 cfg.nopty = TRUE; /* command => no terminal */
452
453 break; /* done with cmdline */
454 }
455 }
456 }
457
86256dc6 458 if (errors)
459 return 1;
460
c5e438ec 461 if (!*cfg.host) {
462 usage();
463 }
464
465 /*
466 * Trim leading whitespace off the hostname if it's there.
467 */
468 {
469 int space = strspn(cfg.host, " \t");
470 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
471 }
472
473 /* See if host is of the form user@host */
474 if (cfg.host[0] != '\0') {
5dd103a8 475 char *atsign = strrchr(cfg.host, '@');
c5e438ec 476 /* Make sure we're not overflowing the user field */
477 if (atsign) {
478 if (atsign - cfg.host < sizeof cfg.username) {
479 strncpy(cfg.username, cfg.host, atsign - cfg.host);
480 cfg.username[atsign - cfg.host] = '\0';
481 }
482 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
483 }
484 }
485
486 /*
487 * Perform command-line overrides on session configuration.
488 */
9b41d3a8 489 cmdline_run_saved(&cfg);
c5e438ec 490
491 /*
09bdfcbb 492 * Apply subsystem status.
493 */
494 if (use_subsystem)
495 cfg.ssh_subsys = TRUE;
496
497 /*
c5e438ec 498 * Trim a colon suffix off the hostname if it's there.
499 */
500 cfg.host[strcspn(cfg.host, ":")] = '\0';
501
502 /*
503 * Remove any remaining whitespace from the hostname.
504 */
505 {
506 int p1 = 0, p2 = 0;
507 while (cfg.host[p2] != '\0') {
508 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
509 cfg.host[p1] = cfg.host[p2];
510 p1++;
511 }
512 p2++;
513 }
514 cfg.host[p1] = '\0';
515 }
516
517 if (!*cfg.remote_cmd_ptr)
518 flags |= FLAG_INTERACTIVE;
519
520 /*
521 * Select protocol. This is farmed out into a table in a
522 * separate file to enable an ssh-free variant.
523 */
524 {
525 int i;
526 back = NULL;
527 for (i = 0; backends[i].backend != NULL; i++)
528 if (backends[i].protocol == cfg.protocol) {
529 back = backends[i].backend;
530 break;
531 }
532 if (back == NULL) {
533 fprintf(stderr,
534 "Internal fault: Unsupported protocol found\n");
535 return 1;
536 }
537 }
538
539 /*
540 * Select port.
541 */
542 if (portnumber != -1)
543 cfg.port = portnumber;
544
5673d44e 545 /*
546 * Set up the pipe we'll use to tell us about SIGWINCH.
547 */
548 if (pipe(signalpipe) < 0) {
549 perror("pipe");
550 exit(1);
551 }
552 putty_signal(SIGWINCH, sigwinch);
553
c5e438ec 554 sk_init();
0ff9ea38 555 uxsel_init();
c5e438ec 556
557 /*
558 * Start up the connection.
559 */
c229ef97 560 logctx = log_init(NULL, &cfg);
b51259f6 561 console_provide_logctx(logctx);
c5e438ec 562 {
cbe2d68f 563 const char *error;
c5e438ec 564 char *realhost;
565 /* nodelay is only useful if stdin is a terminal device */
566 int nodelay = cfg.tcp_nodelay && isatty(0);
567
86916870 568 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
79bf227b 569 &realhost, nodelay, cfg.tcp_keepalives);
c5e438ec 570 if (error) {
984992ef 571 fprintf(stderr, "Unable to open connection:\n%s\n", error);
c5e438ec 572 return 1;
573 }
c5e438ec 574 back->provide_logctx(backhandle, logctx);
fe5634f6 575 ldisc = ldisc_create(&cfg, NULL, back, backhandle, NULL);
c5e438ec 576 sfree(realhost);
577 }
578 connopen = 1;
579
580 /*
581 * Set up the initial console mode. We don't care if this call
582 * fails, because we know we aren't necessarily running in a
583 * console.
584 */
585 tcgetattr(0, &orig_termios);
586 atexit(cleanup_termios);
587 ldisc_update(NULL, 1, 1);
588 sending = FALSE;
39934deb 589 now = GETTICKCOUNT();
c5e438ec 590
591 while (1) {
592 fd_set rset, wset, xset;
593 int maxfd;
594 int rwx;
595 int ret;
596
597 FD_ZERO(&rset);
598 FD_ZERO(&wset);
599 FD_ZERO(&xset);
600 maxfd = 0;
601
5673d44e 602 FD_SET_MAX(signalpipe[0], maxfd, rset);
603
c5e438ec 604 if (connopen && !sending &&
605 back->socket(backhandle) != NULL &&
606 back->sendok(backhandle) &&
607 back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
608 /* If we're OK to send, then try to read from stdin. */
609 FD_SET_MAX(0, maxfd, rset);
610 }
611
612 if (bufchain_size(&stdout_data) > 0) {
613 /* If we have data for stdout, try to write to stdout. */
614 FD_SET_MAX(1, maxfd, wset);
615 }
616
617 if (bufchain_size(&stderr_data) > 0) {
618 /* If we have data for stderr, try to write to stderr. */
619 FD_SET_MAX(2, maxfd, wset);
620 }
621
0ff9ea38 622 /* Count the currently active fds. */
c5e438ec 623 i = 0;
0ff9ea38 624 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
625 fd = next_fd(&fdstate, &rwx)) i++;
c5e438ec 626
0ff9ea38 627 /* Expand the fdlist buffer if necessary. */
628 if (i > fdsize) {
629 fdsize = i + 16;
630 fdlist = sresize(fdlist, fdsize, int);
c5e438ec 631 }
632
633 /*
0ff9ea38 634 * Add all currently open fds to the select sets, and store
635 * them in fdlist as well.
c5e438ec 636 */
0ff9ea38 637 fdcount = 0;
638 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
639 fd = next_fd(&fdstate, &rwx)) {
640 fdlist[fdcount++] = fd;
c5e438ec 641 if (rwx & 1)
0ff9ea38 642 FD_SET_MAX(fd, maxfd, rset);
c5e438ec 643 if (rwx & 2)
0ff9ea38 644 FD_SET_MAX(fd, maxfd, wset);
c5e438ec 645 if (rwx & 4)
0ff9ea38 646 FD_SET_MAX(fd, maxfd, xset);
c5e438ec 647 }
648
5673d44e 649 do {
39934deb 650 long next, ticks;
651 struct timeval tv, *ptv;
652
653 if (run_timers(now, &next)) {
654 ticks = next - GETTICKCOUNT();
655 if (ticks < 0) ticks = 0; /* just in case */
656 tv.tv_sec = ticks / 1000;
657 tv.tv_usec = ticks % 1000 * 1000;
658 ptv = &tv;
659 } else {
660 ptv = NULL;
661 }
662 ret = select(maxfd, &rset, &wset, &xset, ptv);
663 if (ret == 0)
664 now = next;
665 else
666 now = GETTICKCOUNT();
5673d44e 667 } while (ret < 0 && errno == EINTR);
c5e438ec 668
669 if (ret < 0) {
670 perror("select");
671 exit(1);
672 }
673
0ff9ea38 674 for (i = 0; i < fdcount; i++) {
675 fd = fdlist[i];
56e5b2db 676 /*
677 * We must process exceptional notifications before
678 * ordinary readability ones, or we may go straight
679 * past the urgent marker.
680 */
0ff9ea38 681 if (FD_ISSET(fd, &xset))
682 select_result(fd, 4);
683 if (FD_ISSET(fd, &rset))
684 select_result(fd, 1);
685 if (FD_ISSET(fd, &wset))
686 select_result(fd, 2);
c5e438ec 687 }
688
5673d44e 689 if (FD_ISSET(signalpipe[0], &rset)) {
690 char c[1];
691 struct winsize size;
692 read(signalpipe[0], c, 1); /* ignore its value; it'll be `x' */
693 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
694 back->size(backhandle, size.ws_col, size.ws_row);
695 }
696
c5e438ec 697 if (FD_ISSET(0, &rset)) {
698 char buf[4096];
699 int ret;
700
701 if (connopen && back->socket(backhandle) != NULL) {
702 ret = read(0, buf, sizeof(buf));
703 if (ret < 0) {
704 perror("stdin: read");
705 exit(1);
706 } else if (ret == 0) {
707 back->special(backhandle, TS_EOF);
708 sending = FALSE; /* send nothing further after this */
709 } else {
710 back->send(backhandle, buf, ret);
711 }
712 }
713 }
714
715 if (FD_ISSET(1, &wset)) {
716 try_output(0);
717 }
718
719 if (FD_ISSET(2, &wset)) {
720 try_output(1);
721 }
722
723 if ((!connopen || back->socket(backhandle) == NULL) &&
724 bufchain_size(&stdout_data) == 0 &&
725 bufchain_size(&stderr_data) == 0)
726 break; /* we closed the connection */
727 }
728 exitcode = back->exitcode(backhandle);
729 if (exitcode < 0) {
730 fprintf(stderr, "Remote process exit code unavailable\n");
731 exitcode = 1; /* this is an error condition */
732 }
d9c40fd6 733 cleanup_exit(exitcode);
734 return exitcode; /* shouldn't happen, but placates gcc */
c5e438ec 735}