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