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