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