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