Squash OPOST locally when we're not in line-editing mode, and propagate
[sgt/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 static int local_tty = 0; /* do we have a local tty? */
67 static struct termios orig_termios;
68
69 static Backend *back;
70 static void *backhandle;
71 static Config cfg;
72
73 /*
74 * Default settings that are specific to pterm.
75 */
76 char *platform_default_s(const char *name)
77 {
78 if (!strcmp(name, "TermType"))
79 return dupstr(getenv("TERM"));
80 if (!strcmp(name, "UserName"))
81 return get_username();
82 return NULL;
83 }
84
85 int platform_default_i(const char *name, int def)
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
96 FontSpec platform_default_fontspec(const char *name)
97 {
98 FontSpec ret;
99 *ret.name = '\0';
100 return ret;
101 }
102
103 Filename 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
113 char *x_get_default(const char *key)
114 {
115 return NULL; /* this is a stub */
116 }
117 int term_ldisc(Terminal *term, int mode)
118 {
119 return FALSE;
120 }
121 void 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 if (!local_tty) return;
127
128 mode = orig_termios;
129
130 if (echo)
131 mode.c_lflag |= ECHO;
132 else
133 mode.c_lflag &= ~ECHO;
134
135 if (edit) {
136 mode.c_iflag |= ICRNL;
137 mode.c_lflag |= ISIG | ICANON;
138 mode.c_oflag |= OPOST;
139 } else {
140 mode.c_iflag &= ~ICRNL;
141 mode.c_lflag &= ~(ISIG | ICANON);
142 mode.c_oflag &= ~OPOST;
143 /* Solaris sets these to unhelpful values */
144 mode.c_cc[VMIN] = 1;
145 mode.c_cc[VTIME] = 0;
146 /* FIXME: perhaps what we do with IXON/IXOFF should be an
147 * argument to ldisc_update(), to allow implementation of SSH-2
148 * "xon-xoff" and Rlogin's equivalent? */
149 mode.c_iflag &= ~IXON;
150 mode.c_iflag &= ~IXOFF;
151 }
152
153 tcsetattr(0, TCSANOW, &mode);
154 }
155
156 /* Helper function to extract a special character from a termios. */
157 static char *get_ttychar(struct termios *t, int index)
158 {
159 cc_t c = t->c_cc[index];
160 #if defined(_POSIX_VDISABLE)
161 if (c == _POSIX_VDISABLE)
162 return dupprintf("");
163 #endif
164 return dupprintf("^<%d>", c);
165 }
166
167 char *get_ttymode(void *frontend, const char *mode)
168 {
169 /*
170 * Propagate appropriate terminal modes from the local terminal,
171 * if any.
172 */
173 if (!local_tty) return NULL;
174
175 #define GET_CHAR(ourname, uxname) \
176 do { \
177 if (strcmp(mode, ourname) == 0) \
178 return get_ttychar(&orig_termios, uxname); \
179 } while(0)
180 #define GET_BOOL(ourname, uxname, uxmemb, transform) \
181 do { \
182 if (strcmp(mode, ourname) == 0) { \
183 int b = (orig_termios.uxmemb & uxname) != 0; \
184 transform; \
185 return dupprintf("%d", b); \
186 } \
187 } while (0)
188
189 /*
190 * Modes that want to be the same on all terminal devices involved.
191 */
192 /* All the special characters supported by SSH */
193 #if defined(VINTR)
194 GET_CHAR("INTR", VINTR);
195 #endif
196 #if defined(VQUIT)
197 GET_CHAR("QUIT", VQUIT);
198 #endif
199 #if defined(VERASE)
200 GET_CHAR("ERASE", VERASE);
201 #endif
202 #if defined(VKILL)
203 GET_CHAR("KILL", VKILL);
204 #endif
205 #if defined(VEOF)
206 GET_CHAR("EOF", VEOF);
207 #endif
208 #if defined(VEOL)
209 GET_CHAR("EOL", VEOL);
210 #endif
211 #if defined(VEOL2)
212 GET_CHAR("EOL2", VEOL2);
213 #endif
214 #if defined(VSTART)
215 GET_CHAR("START", VSTART);
216 #endif
217 #if defined(VSTOP)
218 GET_CHAR("STOP", VSTOP);
219 #endif
220 #if defined(VSUSP)
221 GET_CHAR("SUSP", VSUSP);
222 #endif
223 #if defined(VDSUSP)
224 GET_CHAR("DSUSP", VDSUSP);
225 #endif
226 #if defined(VREPRINT)
227 GET_CHAR("REPRINT", VREPRINT);
228 #endif
229 #if defined(VWERASE)
230 GET_CHAR("WERASE", VWERASE);
231 #endif
232 #if defined(VLNEXT)
233 GET_CHAR("LNEXT", VLNEXT);
234 #endif
235 #if defined(VFLUSH)
236 GET_CHAR("FLUSH", VFLUSH);
237 #endif
238 #if defined(VSWTCH)
239 GET_CHAR("SWTCH", VSWTCH);
240 #endif
241 #if defined(VSTATUS)
242 GET_CHAR("STATUS", VSTATUS);
243 #endif
244 #if defined(VDISCARD)
245 GET_CHAR("DISCARD", VDISCARD);
246 #endif
247 /* Modes that "configure" other major modes. These should probably be
248 * considered as user preferences. */
249 /* Configuration of ICANON */
250 #if defined(ECHOK)
251 GET_BOOL("ECHOK", ECHOK, c_lflag, );
252 #endif
253 #if defined(ECHOKE)
254 GET_BOOL("ECHOKE", ECHOKE, c_lflag, );
255 #endif
256 #if defined(ECHOE)
257 GET_BOOL("ECHOE", ECHOE, c_lflag, );
258 #endif
259 #if defined(ECHONL)
260 GET_BOOL("ECHONL", ECHONL, c_lflag, );
261 #endif
262 #if defined(XCASE)
263 GET_BOOL("XCASE", XCASE, c_lflag, );
264 #endif
265 /* Configuration of ECHO */
266 #if defined(ECHOCTL)
267 GET_BOOL("ECHOCTL", ECHOCTL, c_lflag, );
268 #endif
269 /* Configuration of IXON/IXOFF */
270 #if defined(IXANY)
271 GET_BOOL("IXANY", IXANY, c_iflag, );
272 #endif
273 /* Configuration of OPOST */
274 #if defined(ONLCR)
275 GET_BOOL("ONLCR", ONLCR, c_oflag, );
276 #endif
277 #if defined(OCRNL)
278 GET_BOOL("OCRNL", OCRNL, c_oflag, );
279 #endif
280 #if defined(ONOCR)
281 GET_BOOL("ONOCR", ONOCR, c_oflag, );
282 #endif
283 #if defined(ONLCR)
284 GET_BOOL("ONLRET", ONLRET, c_oflag, );
285 #endif
286
287 /*
288 * Modes that want to be set in only one place, and that we have
289 * squashed locally.
290 */
291 #if defined(ISIG)
292 GET_BOOL("ISIG", ISIG, c_lflag, );
293 #endif
294 #if defined(ICANON)
295 GET_BOOL("ICANON", ICANON, c_lflag, );
296 #endif
297 #if defined(ECHO)
298 GET_BOOL("ECHO", ECHO, c_lflag, );
299 #endif
300 #if defined(IXON)
301 GET_BOOL("IXON", IXON, c_iflag, );
302 #endif
303 #if defined(IXOFF)
304 GET_BOOL("IXOFF", IXOFF, c_iflag, );
305 #endif
306 #if defined(OPOST)
307 GET_BOOL("OPOST", OPOST, c_oflag, );
308 #endif
309
310 /*
311 * We do not propagate the following modes:
312 * - Parity/serial settings, which are a local affair and don't
313 * make sense propagated over SSH's 8-bit byte-stream.
314 * IGNPAR PARMRK INPCK CS7 CS8 PARENB PARODD
315 * - Things that want to be enabled in one place that we don't
316 * squash locally.
317 * IUCLC OLCUC
318 * - Status bits.
319 * PENDIN
320 * - Things I don't know what to do with. (FIXME)
321 * ISTRIP IMAXBEL NOFLSH TOSTOP IEXTEN
322 * INLCR IGNCR ICRNL
323 */
324
325 #undef GET_CHAR
326 #undef GET_BOOL
327
328 /* Fall through to here for unrecognised names, or ones that are
329 * unsupported on this platform */
330 return NULL;
331 }
332
333 void cleanup_termios(void)
334 {
335 if (local_tty)
336 tcsetattr(0, TCSANOW, &orig_termios);
337 }
338
339 bufchain stdout_data, stderr_data;
340
341 void try_output(int is_stderr)
342 {
343 bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
344 int fd = (is_stderr ? 2 : 1);
345 void *senddata;
346 int sendlen, ret;
347
348 if (bufchain_size(chain) == 0)
349 return;
350
351 bufchain_prefix(chain, &senddata, &sendlen);
352 ret = write(fd, senddata, sendlen);
353 if (ret > 0)
354 bufchain_consume(chain, ret);
355 else if (ret < 0) {
356 perror(is_stderr ? "stderr: write" : "stdout: write");
357 exit(1);
358 }
359 }
360
361 int from_backend(void *frontend_handle, int is_stderr,
362 const char *data, int len)
363 {
364 int osize, esize;
365
366 if (is_stderr) {
367 bufchain_add(&stderr_data, data, len);
368 try_output(1);
369 } else {
370 bufchain_add(&stdout_data, data, len);
371 try_output(0);
372 }
373
374 osize = bufchain_size(&stdout_data);
375 esize = bufchain_size(&stderr_data);
376
377 return osize + esize;
378 }
379
380 int signalpipe[2];
381
382 void sigwinch(int signum)
383 {
384 write(signalpipe[1], "x", 1);
385 }
386
387 /*
388 * In Plink our selects are synchronous, so these functions are
389 * empty stubs.
390 */
391 int uxsel_input_add(int fd, int rwx) { return 0; }
392 void uxsel_input_remove(int id) { }
393
394 /*
395 * Short description of parameters.
396 */
397 static void usage(void)
398 {
399 printf("PuTTY Link: command-line connection utility\n");
400 printf("%s\n", ver);
401 printf("Usage: plink [options] [user@]host [command]\n");
402 printf(" (\"host\" can also be a PuTTY saved session name)\n");
403 printf("Options:\n");
404 printf(" -V print version information and exit\n");
405 printf(" -pgpfp print PGP key fingerprints and exit\n");
406 printf(" -v show verbose messages\n");
407 printf(" -load sessname Load settings from saved session\n");
408 printf(" -ssh -telnet -rlogin -raw\n");
409 printf(" force use of a particular protocol\n");
410 printf(" -P port connect to specified port\n");
411 printf(" -l user connect with specified username\n");
412 printf(" -batch disable all interactive prompts\n");
413 printf("The following options only apply to SSH connections:\n");
414 printf(" -pw passw login with specified password\n");
415 printf(" -D [listen-IP:]listen-port\n");
416 printf(" Dynamic SOCKS-based port forwarding\n");
417 printf(" -L [listen-IP:]listen-port:host:port\n");
418 printf(" Forward local port to remote address\n");
419 printf(" -R [listen-IP:]listen-port:host:port\n");
420 printf(" Forward remote port to local address\n");
421 printf(" -X -x enable / disable X11 forwarding\n");
422 printf(" -A -a enable / disable agent forwarding\n");
423 printf(" -t -T enable / disable pty allocation\n");
424 printf(" -1 -2 force use of particular protocol version\n");
425 printf(" -4 -6 force use of IPv4 or IPv6\n");
426 printf(" -C enable compression\n");
427 printf(" -i key private key file for authentication\n");
428 printf(" -m file read remote command(s) from file\n");
429 printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
430 printf(" -N don't start a shell/command (SSH-2 only)\n");
431 exit(1);
432 }
433
434 static void version(void)
435 {
436 printf("plink: %s\n", ver);
437 exit(1);
438 }
439
440 int main(int argc, char **argv)
441 {
442 int sending;
443 int portnumber = -1;
444 int *fdlist;
445 int fd;
446 int i, fdcount, fdsize, fdstate;
447 int connopen;
448 int exitcode;
449 int errors;
450 int use_subsystem = 0;
451 void *ldisc, *logctx;
452 long now;
453
454 ssh_get_line = console_get_line;
455
456 fdlist = NULL;
457 fdcount = fdsize = 0;
458 /*
459 * Initialise port and protocol to sensible defaults. (These
460 * will be overridden by more or less anything.)
461 */
462 default_protocol = PROT_SSH;
463 default_port = 22;
464
465 flags = FLAG_STDERR;
466 /*
467 * Process the command line.
468 */
469 do_defaults(NULL, &cfg);
470 loaded_session = FALSE;
471 default_protocol = cfg.protocol;
472 default_port = cfg.port;
473 errors = 0;
474 {
475 /*
476 * Override the default protocol if PLINK_PROTOCOL is set.
477 */
478 char *p = getenv("PLINK_PROTOCOL");
479 int i;
480 if (p) {
481 for (i = 0; backends[i].backend != NULL; i++) {
482 if (!strcmp(backends[i].name, p)) {
483 default_protocol = cfg.protocol = backends[i].protocol;
484 default_port = cfg.port =
485 backends[i].backend->default_port;
486 break;
487 }
488 }
489 }
490 }
491 while (--argc) {
492 char *p = *++argv;
493 if (*p == '-') {
494 int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
495 1, &cfg);
496 if (ret == -2) {
497 fprintf(stderr,
498 "plink: option \"%s\" requires an argument\n", p);
499 errors = 1;
500 } else if (ret == 2) {
501 --argc, ++argv;
502 } else if (ret == 1) {
503 continue;
504 } else if (!strcmp(p, "-batch")) {
505 console_batch_mode = 1;
506 } else if (!strcmp(p, "-s")) {
507 /* Save status to write to cfg later. */
508 use_subsystem = 1;
509 } else if (!strcmp(p, "-V")) {
510 version();
511 } else if (!strcmp(p, "-pgpfp")) {
512 pgp_fingerprints();
513 exit(1);
514 } else if (!strcmp(p, "-o")) {
515 if (argc <= 1) {
516 fprintf(stderr,
517 "plink: option \"-o\" requires an argument\n");
518 errors = 1;
519 } else {
520 --argc;
521 provide_xrm_string(*++argv);
522 }
523 } else {
524 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
525 errors = 1;
526 }
527 } else if (*p) {
528 if (!*cfg.host) {
529 char *q = p;
530
531 do_defaults(NULL, &cfg);
532
533 /*
534 * If the hostname starts with "telnet:", set the
535 * protocol to Telnet and process the string as a
536 * Telnet URL.
537 */
538 if (!strncmp(q, "telnet:", 7)) {
539 char c;
540
541 q += 7;
542 if (q[0] == '/' && q[1] == '/')
543 q += 2;
544 cfg.protocol = PROT_TELNET;
545 p = q;
546 while (*p && *p != ':' && *p != '/')
547 p++;
548 c = *p;
549 if (*p)
550 *p++ = '\0';
551 if (c == ':')
552 cfg.port = atoi(p);
553 else
554 cfg.port = -1;
555 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
556 cfg.host[sizeof(cfg.host) - 1] = '\0';
557 } else {
558 char *r, *user, *host;
559 /*
560 * Before we process the [user@]host string, we
561 * first check for the presence of a protocol
562 * prefix (a protocol name followed by ",").
563 */
564 r = strchr(p, ',');
565 if (r) {
566 int i, j;
567 for (i = 0; backends[i].backend != NULL; i++) {
568 j = strlen(backends[i].name);
569 if (j == r - p &&
570 !memcmp(backends[i].name, p, j)) {
571 default_protocol = cfg.protocol =
572 backends[i].protocol;
573 portnumber =
574 backends[i].backend->default_port;
575 p = r + 1;
576 break;
577 }
578 }
579 }
580
581 /*
582 * A nonzero length string followed by an @ is treated
583 * as a username. (We discount an _initial_ @.) The
584 * rest of the string (or the whole string if no @)
585 * is treated as a session name and/or hostname.
586 */
587 r = strrchr(p, '@');
588 if (r == p)
589 p++, r = NULL; /* discount initial @ */
590 if (r) {
591 *r++ = '\0';
592 user = p, host = r;
593 } else {
594 user = NULL, host = p;
595 }
596
597 /*
598 * Now attempt to load a saved session with the
599 * same name as the hostname.
600 */
601 {
602 Config cfg2;
603 do_defaults(host, &cfg2);
604 if (loaded_session || cfg2.host[0] == '\0') {
605 /* No settings for this host; use defaults */
606 /* (or session was already loaded with -load) */
607 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
608 cfg.host[sizeof(cfg.host) - 1] = '\0';
609 cfg.port = default_port;
610 } else {
611 cfg = cfg2;
612 }
613 }
614
615 if (user) {
616 /* Patch in specified username. */
617 strncpy(cfg.username, user,
618 sizeof(cfg.username) - 1);
619 cfg.username[sizeof(cfg.username) - 1] = '\0';
620 }
621
622 }
623 } else {
624 char *command;
625 int cmdlen, cmdsize;
626 cmdlen = cmdsize = 0;
627 command = NULL;
628
629 while (argc) {
630 while (*p) {
631 if (cmdlen >= cmdsize) {
632 cmdsize = cmdlen + 512;
633 command = sresize(command, cmdsize, char);
634 }
635 command[cmdlen++]=*p++;
636 }
637 if (cmdlen >= cmdsize) {
638 cmdsize = cmdlen + 512;
639 command = sresize(command, cmdsize, char);
640 }
641 command[cmdlen++]=' '; /* always add trailing space */
642 if (--argc) p = *++argv;
643 }
644 if (cmdlen) command[--cmdlen]='\0';
645 /* change trailing blank to NUL */
646 cfg.remote_cmd_ptr = command;
647 cfg.remote_cmd_ptr2 = NULL;
648 cfg.nopty = TRUE; /* command => no terminal */
649
650 break; /* done with cmdline */
651 }
652 }
653 }
654
655 if (errors)
656 return 1;
657
658 if (!*cfg.host) {
659 usage();
660 }
661
662 /*
663 * Trim leading whitespace off the hostname if it's there.
664 */
665 {
666 int space = strspn(cfg.host, " \t");
667 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
668 }
669
670 /* See if host is of the form user@host */
671 if (cfg.host[0] != '\0') {
672 char *atsign = strrchr(cfg.host, '@');
673 /* Make sure we're not overflowing the user field */
674 if (atsign) {
675 if (atsign - cfg.host < sizeof cfg.username) {
676 strncpy(cfg.username, cfg.host, atsign - cfg.host);
677 cfg.username[atsign - cfg.host] = '\0';
678 }
679 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
680 }
681 }
682
683 /*
684 * Perform command-line overrides on session configuration.
685 */
686 cmdline_run_saved(&cfg);
687
688 /*
689 * Apply subsystem status.
690 */
691 if (use_subsystem)
692 cfg.ssh_subsys = TRUE;
693
694 /*
695 * Trim a colon suffix off the hostname if it's there.
696 */
697 cfg.host[strcspn(cfg.host, ":")] = '\0';
698
699 /*
700 * Remove any remaining whitespace from the hostname.
701 */
702 {
703 int p1 = 0, p2 = 0;
704 while (cfg.host[p2] != '\0') {
705 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
706 cfg.host[p1] = cfg.host[p2];
707 p1++;
708 }
709 p2++;
710 }
711 cfg.host[p1] = '\0';
712 }
713
714 if (!cfg.remote_cmd_ptr && !*cfg.remote_cmd)
715 flags |= FLAG_INTERACTIVE;
716
717 /*
718 * Select protocol. This is farmed out into a table in a
719 * separate file to enable an ssh-free variant.
720 */
721 {
722 int i;
723 back = NULL;
724 for (i = 0; backends[i].backend != NULL; i++)
725 if (backends[i].protocol == cfg.protocol) {
726 back = backends[i].backend;
727 break;
728 }
729 if (back == NULL) {
730 fprintf(stderr,
731 "Internal fault: Unsupported protocol found\n");
732 return 1;
733 }
734 }
735
736 /*
737 * Select port.
738 */
739 if (portnumber != -1)
740 cfg.port = portnumber;
741
742 /*
743 * Set up the pipe we'll use to tell us about SIGWINCH.
744 */
745 if (pipe(signalpipe) < 0) {
746 perror("pipe");
747 exit(1);
748 }
749 putty_signal(SIGWINCH, sigwinch);
750
751 sk_init();
752 uxsel_init();
753
754 /*
755 * Start up the connection.
756 */
757 logctx = log_init(NULL, &cfg);
758 console_provide_logctx(logctx);
759 {
760 const char *error;
761 char *realhost;
762 /* nodelay is only useful if stdin is a terminal device */
763 int nodelay = cfg.tcp_nodelay && isatty(0);
764
765 error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
766 &realhost, nodelay, cfg.tcp_keepalives);
767 if (error) {
768 fprintf(stderr, "Unable to open connection:\n%s\n", error);
769 return 1;
770 }
771 back->provide_logctx(backhandle, logctx);
772 ldisc = ldisc_create(&cfg, NULL, back, backhandle, NULL);
773 sfree(realhost);
774 }
775 connopen = 1;
776
777 /*
778 * Set up the initial console mode. We don't care if this call
779 * fails, because we know we aren't necessarily running in a
780 * console.
781 */
782 local_tty = (tcgetattr(0, &orig_termios) == 0);
783 atexit(cleanup_termios);
784 ldisc_update(NULL, 1, 1);
785 sending = FALSE;
786 now = GETTICKCOUNT();
787
788 while (1) {
789 fd_set rset, wset, xset;
790 int maxfd;
791 int rwx;
792 int ret;
793
794 FD_ZERO(&rset);
795 FD_ZERO(&wset);
796 FD_ZERO(&xset);
797 maxfd = 0;
798
799 FD_SET_MAX(signalpipe[0], maxfd, rset);
800
801 if (connopen && !sending &&
802 back->socket(backhandle) != NULL &&
803 back->sendok(backhandle) &&
804 back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
805 /* If we're OK to send, then try to read from stdin. */
806 FD_SET_MAX(0, maxfd, rset);
807 }
808
809 if (bufchain_size(&stdout_data) > 0) {
810 /* If we have data for stdout, try to write to stdout. */
811 FD_SET_MAX(1, maxfd, wset);
812 }
813
814 if (bufchain_size(&stderr_data) > 0) {
815 /* If we have data for stderr, try to write to stderr. */
816 FD_SET_MAX(2, maxfd, wset);
817 }
818
819 /* Count the currently active fds. */
820 i = 0;
821 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
822 fd = next_fd(&fdstate, &rwx)) i++;
823
824 /* Expand the fdlist buffer if necessary. */
825 if (i > fdsize) {
826 fdsize = i + 16;
827 fdlist = sresize(fdlist, fdsize, int);
828 }
829
830 /*
831 * Add all currently open fds to the select sets, and store
832 * them in fdlist as well.
833 */
834 fdcount = 0;
835 for (fd = first_fd(&fdstate, &rwx); fd >= 0;
836 fd = next_fd(&fdstate, &rwx)) {
837 fdlist[fdcount++] = fd;
838 if (rwx & 1)
839 FD_SET_MAX(fd, maxfd, rset);
840 if (rwx & 2)
841 FD_SET_MAX(fd, maxfd, wset);
842 if (rwx & 4)
843 FD_SET_MAX(fd, maxfd, xset);
844 }
845
846 do {
847 long next, ticks;
848 struct timeval tv, *ptv;
849
850 if (run_timers(now, &next)) {
851 ticks = next - GETTICKCOUNT();
852 if (ticks < 0) ticks = 0; /* just in case */
853 tv.tv_sec = ticks / 1000;
854 tv.tv_usec = ticks % 1000 * 1000;
855 ptv = &tv;
856 } else {
857 ptv = NULL;
858 }
859 ret = select(maxfd, &rset, &wset, &xset, ptv);
860 if (ret == 0)
861 now = next;
862 else {
863 long newnow = GETTICKCOUNT();
864 /*
865 * Check to see whether the system clock has
866 * changed massively during the select.
867 */
868 if (newnow - now < 0 || newnow - now > next - now) {
869 /*
870 * If so, look at the elapsed time in the
871 * select and use it to compute a new
872 * tickcount_offset.
873 */
874 long othernow = now + tv.tv_sec * 1000 + tv.tv_usec / 1000;
875 /* So we'd like GETTICKCOUNT to have returned othernow,
876 * but instead it return newnow. Hence ... */
877 tickcount_offset += othernow - newnow;
878 now = othernow;
879 } else {
880 now = newnow;
881 }
882 }
883 } while (ret < 0 && errno == EINTR);
884
885 if (ret < 0) {
886 perror("select");
887 exit(1);
888 }
889
890 for (i = 0; i < fdcount; i++) {
891 fd = fdlist[i];
892 /*
893 * We must process exceptional notifications before
894 * ordinary readability ones, or we may go straight
895 * past the urgent marker.
896 */
897 if (FD_ISSET(fd, &xset))
898 select_result(fd, 4);
899 if (FD_ISSET(fd, &rset))
900 select_result(fd, 1);
901 if (FD_ISSET(fd, &wset))
902 select_result(fd, 2);
903 }
904
905 if (FD_ISSET(signalpipe[0], &rset)) {
906 char c[1];
907 struct winsize size;
908 read(signalpipe[0], c, 1); /* ignore its value; it'll be `x' */
909 if (ioctl(0, TIOCGWINSZ, (void *)&size) >= 0)
910 back->size(backhandle, size.ws_col, size.ws_row);
911 }
912
913 if (FD_ISSET(0, &rset)) {
914 char buf[4096];
915 int ret;
916
917 if (connopen && back->socket(backhandle) != NULL) {
918 ret = read(0, buf, sizeof(buf));
919 if (ret < 0) {
920 perror("stdin: read");
921 exit(1);
922 } else if (ret == 0) {
923 back->special(backhandle, TS_EOF);
924 sending = FALSE; /* send nothing further after this */
925 } else {
926 back->send(backhandle, buf, ret);
927 }
928 }
929 }
930
931 if (FD_ISSET(1, &wset)) {
932 try_output(0);
933 }
934
935 if (FD_ISSET(2, &wset)) {
936 try_output(1);
937 }
938
939 if ((!connopen || back->socket(backhandle) == NULL) &&
940 bufchain_size(&stdout_data) == 0 &&
941 bufchain_size(&stderr_data) == 0)
942 break; /* we closed the connection */
943 }
944 exitcode = back->exitcode(backhandle);
945 if (exitcode < 0) {
946 fprintf(stderr, "Remote process exit code unavailable\n");
947 exitcode = 1; /* this is an error condition */
948 }
949 cleanup_exit(exitcode);
950 return exitcode; /* shouldn't happen, but placates gcc */
951 }