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