e2b4d3d97d4890ff366c8165b2374778cb29a692
[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
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
24 void 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 }
34 void 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 }
44 void 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 }
54 void 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
65 struct termios orig_termios;
66
67 static Backend *back;
68 static void *backhandle;
69 static Config cfg;
70
71 /*
72 * Default settings that are specific to pterm.
73 */
74 char *platform_default_s(const char *name)
75 {
76 if (!strcmp(name, "TermType"))
77 return dupstr(getenv("TERM"));
78 if (!strcmp(name, "UserName"))
79 return get_username();
80 return NULL;
81 }
82
83 int platform_default_i(const char *name, int def)
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
94 FontSpec platform_default_fontspec(const char *name)
95 {
96 FontSpec ret;
97 *ret.name = '\0';
98 return ret;
99 }
100
101 Filename 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
111 char *x_get_default(const char *key)
112 {
113 return NULL; /* this is a stub */
114 }
115 int term_ldisc(Terminal *term, int mode)
116 {
117 return FALSE;
118 }
119 void 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
139 void cleanup_termios(void)
140 {
141 tcsetattr(0, TCSANOW, &orig_termios);
142 }
143
144 bufchain stdout_data, stderr_data;
145
146 void 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
153 if (bufchain_size(chain) == 0)
154 return;
155
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
166 int from_backend(void *frontend_handle, int is_stderr,
167 const char *data, int len)
168 {
169 int osize, esize;
170
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
185 int signalpipe[2];
186
187 void sigwinch(int signum)
188 {
189 write(signalpipe[1], "x", 1);
190 }
191
192 /*
193 * In Plink our selects are synchronous, so these functions are
194 * empty stubs.
195 */
196 int uxsel_input_add(int fd, int rwx) { return 0; }
197 void uxsel_input_remove(int id) { }
198
199 /*
200 * Short description of parameters.
201 */
202 static 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");
209 printf(" -V print version information\n");
210 printf(" -v show verbose messages\n");
211 printf(" -load sessname Load settings from saved session\n");
212 printf(" -ssh -telnet -rlogin -raw\n");
213 printf(" force use of a particular protocol\n");
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");
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");
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");
230 printf(" -C enable compression\n");
231 printf(" -i key private key file for authentication\n");
232 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
233 printf(" -N don't start a shell/command (SSH-2 only)\n");
234 exit(1);
235 }
236
237 static void version(void)
238 {
239 printf("plink: %s\n", ver);
240 exit(1);
241 }
242
243 int main(int argc, char **argv)
244 {
245 int sending;
246 int portnumber = -1;
247 int *fdlist;
248 int fd;
249 int i, fdcount, fdsize, fdstate;
250 int connopen;
251 int exitcode;
252 int errors;
253 int use_subsystem = 0;
254 void *ldisc, *logctx;
255
256 ssh_get_line = console_get_line;
257
258 fdlist = NULL;
259 fdcount = fdsize = 0;
260 /*
261 * Initialise port and protocol to sensible defaults. (These
262 * will be overridden by more or less anything.)
263 */
264 default_protocol = PROT_SSH;
265 default_port = 22;
266
267 flags = FLAG_STDERR;
268 /*
269 * Process the command line.
270 */
271 do_defaults(NULL, &cfg);
272 loaded_session = FALSE;
273 default_protocol = cfg.protocol;
274 default_port = cfg.port;
275 errors = 0;
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 == '-') {
296 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
297 1, &cfg);
298 if (ret == -2) {
299 fprintf(stderr,
300 "plink: option \"%s\" requires an argument\n", p);
301 errors = 1;
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;
308 } else if (!strcmp(p, "-s")) {
309 /* Save status to write to cfg later. */
310 use_subsystem = 1;
311 } else if (!strcmp(p, "-V")) {
312 version();
313 } else if (!strcmp(p, "-o")) {
314 if (argc <= 1) {
315 fprintf(stderr,
316 "plink: option \"-o\" requires an argument\n");
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;
325 }
326 } else if (*p) {
327 if (!*cfg.host) {
328 char *q = p;
329
330 do_defaults(NULL, &cfg);
331
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, *user, *host;
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 * A nonzero length string followed by an @ is treated
382 * as a username. (We discount an _initial_ @.) The
383 * rest of the string (or the whole string if no @)
384 * is treated as a session name and/or hostname.
385 */
386 r = strrchr(p, '@');
387 if (r == p)
388 p++, r = NULL; /* discount initial @ */
389 if (r) {
390 *r++ = '\0';
391 user = p, host = r;
392 } else {
393 user = NULL, host = p;
394 }
395
396 /*
397 * Now attempt to load a saved session with the
398 * same name as the hostname.
399 */
400 {
401 Config cfg2;
402 do_defaults(host, &cfg2);
403 if (loaded_session || cfg2.host[0] == '\0') {
404 /* No settings for this host; use defaults */
405 /* (or session was already loaded with -load) */
406 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
407 cfg.host[sizeof(cfg.host) - 1] = '\0';
408 cfg.port = default_port;
409 } else {
410 cfg = cfg2;
411 /* Ick: patch up internal pointer after copy */
412 cfg.remote_cmd_ptr = cfg.remote_cmd;
413 }
414 }
415
416 if (user) {
417 /* Patch in specified username. */
418 strncpy(cfg.username, user,
419 sizeof(cfg.username) - 1);
420 cfg.username[sizeof(cfg.username) - 1] = '\0';
421 }
422
423 }
424 } else {
425 char *command;
426 int cmdlen, cmdsize;
427 cmdlen = cmdsize = 0;
428 command = NULL;
429
430 while (argc) {
431 while (*p) {
432 if (cmdlen >= cmdsize) {
433 cmdsize = cmdlen + 512;
434 command = sresize(command, cmdsize, char);
435 }
436 command[cmdlen++]=*p++;
437 }
438 if (cmdlen >= cmdsize) {
439 cmdsize = cmdlen + 512;
440 command = sresize(command, cmdsize, char);
441 }
442 command[cmdlen++]=' '; /* always add trailing space */
443 if (--argc) p = *++argv;
444 }
445 if (cmdlen) command[--cmdlen]='\0';
446 /* change trailing blank to NUL */
447 cfg.remote_cmd_ptr = command;
448 cfg.remote_cmd_ptr2 = NULL;
449 cfg.nopty = TRUE; /* command => no terminal */
450
451 break; /* done with cmdline */
452 }
453 }
454 }
455
456 if (errors)
457 return 1;
458
459 if (!*cfg.host) {
460 usage();
461 }
462
463 /*
464 * Trim leading whitespace off the hostname if it's there.
465 */
466 {
467 int space = strspn(cfg.host, " \t");
468 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
469 }
470
471 /* See if host is of the form user@host */
472 if (cfg.host[0] != '\0') {
473 char *atsign = strrchr(cfg.host, '@');
474 /* Make sure we're not overflowing the user field */
475 if (atsign) {
476 if (atsign - cfg.host < sizeof cfg.username) {
477 strncpy(cfg.username, cfg.host, atsign - cfg.host);
478 cfg.username[atsign - cfg.host] = '\0';
479 }
480 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
481 }
482 }
483
484 /*
485 * Perform command-line overrides on session configuration.
486 */
487 cmdline_run_saved(&cfg);
488
489 /*
490 * Apply subsystem status.
491 */
492 if (use_subsystem)
493 cfg.ssh_subsys = TRUE;
494
495 /*
496 * Trim a colon suffix off the hostname if it's there.
497 */
498 cfg.host[strcspn(cfg.host, ":")] = '\0';
499
500 /*
501 * Remove any remaining whitespace from the hostname.
502 */
503 {
504 int p1 = 0, p2 = 0;
505 while (cfg.host[p2] != '\0') {
506 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
507 cfg.host[p1] = cfg.host[p2];
508 p1++;
509 }
510 p2++;
511 }
512 cfg.host[p1] = '\0';
513 }
514
515 if (!*cfg.remote_cmd_ptr)
516 flags |= FLAG_INTERACTIVE;
517
518 /*
519 * Select protocol. This is farmed out into a table in a
520 * separate file to enable an ssh-free variant.
521 */
522 {
523 int i;
524 back = NULL;
525 for (i = 0; backends[i].backend != NULL; i++)
526 if (backends[i].protocol == cfg.protocol) {
527 back = backends[i].backend;
528 break;
529 }
530 if (back == NULL) {
531 fprintf(stderr,
532 "Internal fault: Unsupported protocol found\n");
533 return 1;
534 }
535 }
536
537 /*
538 * Select port.
539 */
540 if (portnumber != -1)
541 cfg.port = portnumber;
542
543 /*
544 * Set up the pipe we'll use to tell us about SIGWINCH.
545 */
546 if (pipe(signalpipe) < 0) {
547 perror("pipe");
548 exit(1);
549 }
550 putty_signal(SIGWINCH, sigwinch);
551
552 sk_init();
553 uxsel_init();
554
555 /*
556 * Start up the connection.
557 */
558 logctx = log_init(NULL, &cfg);
559 console_provide_logctx(logctx);
560 {
561 const char *error;
562 char *realhost;
563 /* nodelay is only useful if stdin is a terminal device */
564 int nodelay = cfg.tcp_nodelay && isatty(0);
565
566 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
567 &realhost, nodelay, cfg.tcp_keepalives);
568 if (error) {
569 fprintf(stderr, "Unable to open connection:\n%s\n", error);
570 return 1;
571 }
572 back->provide_logctx(backhandle, logctx);
573 ldisc = ldisc_create(&cfg, NULL, back, backhandle, NULL);
574 sfree(realhost);
575 }
576 connopen = 1;
577
578 /*
579 * Set up the initial console mode. We don't care if this call
580 * fails, because we know we aren't necessarily running in a
581 * console.
582 */
583 tcgetattr(0, &orig_termios);
584 atexit(cleanup_termios);
585 ldisc_update(NULL, 1, 1);
586 sending = FALSE;
587
588 while (1) {
589 fd_set rset, wset, xset;
590 int maxfd;
591 int rwx;
592 int ret;
593
594 FD_ZERO(&rset);
595 FD_ZERO(&wset);
596 FD_ZERO(&xset);
597 maxfd = 0;
598
599 FD_SET_MAX(signalpipe[0], maxfd, rset);
600
601 if (connopen && !sending &&
602 back->socket(backhandle) != NULL &&
603 back->sendok(backhandle) &&
604 back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
605 /* If we're OK to send, then try to read from stdin. */
606 FD_SET_MAX(0, maxfd, rset);
607 }
608
609 if (bufchain_size(&stdout_data) > 0) {
610 /* If we have data for stdout, try to write to stdout. */
611 FD_SET_MAX(1, maxfd, wset);
612 }
613
614 if (bufchain_size(&stderr_data) > 0) {
615 /* If we have data for stderr, try to write to stderr. */
616 FD_SET_MAX(2, maxfd, wset);
617 }
618
619 /* Count the currently active fds. */
620 i = 0;
621 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
622 fd = next_fd(&fdstate, &rwx)) i++;
623
624 /* Expand the fdlist buffer if necessary. */
625 if (i > fdsize) {
626 fdsize = i + 16;
627 fdlist = sresize(fdlist, fdsize, int);
628 }
629
630 /*
631 * Add all currently open fds to the select sets, and store
632 * them in fdlist as well.
633 */
634 fdcount = 0;
635 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
636 fd = next_fd(&fdstate, &rwx)) {
637 fdlist[fdcount++] = fd;
638 if (rwx & 1)
639 FD_SET_MAX(fd, maxfd, rset);
640 if (rwx & 2)
641 FD_SET_MAX(fd, maxfd, wset);
642 if (rwx & 4)
643 FD_SET_MAX(fd, maxfd, xset);
644 }
645
646 do {
647 ret = select(maxfd, &rset, &wset, &xset, NULL);
648 } while (ret < 0 && errno == EINTR);
649
650 if (ret < 0) {
651 perror("select");
652 exit(1);
653 }
654
655 for (i = 0; i < fdcount; i++) {
656 fd = fdlist[i];
657 /*
658 * We must process exceptional notifications before
659 * ordinary readability ones, or we may go straight
660 * past the urgent marker.
661 */
662 if (FD_ISSET(fd, &xset))
663 select_result(fd, 4);
664 if (FD_ISSET(fd, &rset))
665 select_result(fd, 1);
666 if (FD_ISSET(fd, &wset))
667 select_result(fd, 2);
668 }
669
670 if (FD_ISSET(signalpipe[0], &rset)) {
671 char c[1];
672 struct winsize size;
673 read(signalpipe[0], c, 1); /* ignore its value; it'll be `x' */
674 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
675 back->size(backhandle, size.ws_col, size.ws_row);
676 }
677
678 if (FD_ISSET(0, &rset)) {
679 char buf[4096];
680 int ret;
681
682 if (connopen && back->socket(backhandle) != NULL) {
683 ret = read(0, buf, sizeof(buf));
684 if (ret < 0) {
685 perror("stdin: read");
686 exit(1);
687 } else if (ret == 0) {
688 back->special(backhandle, TS_EOF);
689 sending = FALSE; /* send nothing further after this */
690 } else {
691 back->send(backhandle, buf, ret);
692 }
693 }
694 }
695
696 if (FD_ISSET(1, &wset)) {
697 try_output(0);
698 }
699
700 if (FD_ISSET(2, &wset)) {
701 try_output(1);
702 }
703
704 if ((!connopen || back->socket(backhandle) == NULL) &&
705 bufchain_size(&stdout_data) == 0 &&
706 bufchain_size(&stderr_data) == 0)
707 break; /* we closed the connection */
708 }
709 exitcode = back->exitcode(backhandle);
710 if (exitcode < 0) {
711 fprintf(stderr, "Remote process exit code unavailable\n");
712 exitcode = 1; /* this is an error condition */
713 }
714 cleanup_exit(exitcode);
715 return exitcode; /* shouldn't happen, but placates gcc */
716 }