]> asedeno.scripts.mit.edu Git - PuTTY_svn.git/blob - windows/winplink.c
Implement connection sharing between instances of PuTTY.
[PuTTY_svn.git] / windows / winplink.c
1 /*
2  * PLink - a Windows command-line (stdin/stdout) variant of PuTTY.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <assert.h>
8 #include <stdarg.h>
9
10 #define PUTTY_DO_GLOBALS               /* actually _define_ globals */
11 #include "putty.h"
12 #include "storage.h"
13 #include "tree234.h"
14
15 #define WM_AGENT_CALLBACK (WM_APP + 4)
16
17 struct agent_callback {
18     void (*callback)(void *, void *, int);
19     void *callback_ctx;
20     void *data;
21     int len;
22 };
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     if (logctx) {
33         log_free(logctx);
34         logctx = NULL;
35     }
36     cleanup_exit(1);
37 }
38 void modalfatalbox(char *p, ...)
39 {
40     va_list ap;
41     fprintf(stderr, "FATAL ERROR: ");
42     va_start(ap, p);
43     vfprintf(stderr, p, ap);
44     va_end(ap);
45     fputc('\n', stderr);
46     if (logctx) {
47         log_free(logctx);
48         logctx = NULL;
49     }
50     cleanup_exit(1);
51 }
52 void nonfatal(char *p, ...)
53 {
54     va_list ap;
55     fprintf(stderr, "ERROR: ");
56     va_start(ap, p);
57     vfprintf(stderr, p, ap);
58     va_end(ap);
59     fputc('\n', stderr);
60 }
61 void connection_fatal(void *frontend, char *p, ...)
62 {
63     va_list ap;
64     fprintf(stderr, "FATAL ERROR: ");
65     va_start(ap, p);
66     vfprintf(stderr, p, ap);
67     va_end(ap);
68     fputc('\n', stderr);
69     if (logctx) {
70         log_free(logctx);
71         logctx = NULL;
72     }
73     cleanup_exit(1);
74 }
75 void cmdline_error(char *p, ...)
76 {
77     va_list ap;
78     fprintf(stderr, "plink: ");
79     va_start(ap, p);
80     vfprintf(stderr, p, ap);
81     va_end(ap);
82     fputc('\n', stderr);
83     exit(1);
84 }
85
86 HANDLE inhandle, outhandle, errhandle;
87 struct handle *stdin_handle, *stdout_handle, *stderr_handle;
88 DWORD orig_console_mode;
89 int connopen;
90
91 WSAEVENT netevent;
92
93 static Backend *back;
94 static void *backhandle;
95 static Conf *conf;
96
97 int term_ldisc(Terminal *term, int mode)
98 {
99     return FALSE;
100 }
101 void ldisc_update(void *frontend, int echo, int edit)
102 {
103     /* Update stdin read mode to reflect changes in line discipline. */
104     DWORD mode;
105
106     mode = ENABLE_PROCESSED_INPUT;
107     if (echo)
108         mode = mode | ENABLE_ECHO_INPUT;
109     else
110         mode = mode & ~ENABLE_ECHO_INPUT;
111     if (edit)
112         mode = mode | ENABLE_LINE_INPUT;
113     else
114         mode = mode & ~ENABLE_LINE_INPUT;
115     SetConsoleMode(inhandle, mode);
116 }
117
118 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
119
120 int from_backend(void *frontend_handle, int is_stderr,
121                  const char *data, int len)
122 {
123     if (is_stderr) {
124         handle_write(stderr_handle, data, len);
125     } else {
126         handle_write(stdout_handle, data, len);
127     }
128
129     return handle_backlog(stdout_handle) + handle_backlog(stderr_handle);
130 }
131
132 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
133 {
134     /*
135      * No "untrusted" output should get here (the way the code is
136      * currently, it's all diverted by FLAG_STDERR).
137      */
138     assert(!"Unexpected call to from_backend_untrusted()");
139     return 0; /* not reached */
140 }
141
142 int from_backend_eof(void *frontend_handle)
143 {
144     handle_write_eof(stdout_handle);
145     return FALSE;   /* do not respond to incoming EOF with outgoing */
146 }
147
148 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
149 {
150     int ret;
151     ret = cmdline_get_passwd_input(p, in, inlen);
152     if (ret == -1)
153         ret = console_get_userpass_input(p, in, inlen);
154     return ret;
155 }
156
157 static DWORD main_thread_id;
158
159 void agent_schedule_callback(void (*callback)(void *, void *, int),
160                              void *callback_ctx, void *data, int len)
161 {
162     struct agent_callback *c = snew(struct agent_callback);
163     c->callback = callback;
164     c->callback_ctx = callback_ctx;
165     c->data = data;
166     c->len = len;
167     PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
168 }
169
170 /*
171  *  Short description of parameters.
172  */
173 static void usage(void)
174 {
175     printf("PuTTY Link: command-line connection utility\n");
176     printf("%s\n", ver);
177     printf("Usage: plink [options] [user@]host [command]\n");
178     printf("       (\"host\" can also be a PuTTY saved session name)\n");
179     printf("Options:\n");
180     printf("  -V        print version information and exit\n");
181     printf("  -pgpfp    print PGP key fingerprints and exit\n");
182     printf("  -v        show verbose messages\n");
183     printf("  -load sessname  Load settings from saved session\n");
184     printf("  -ssh -telnet -rlogin -raw -serial\n");
185     printf("            force use of a particular protocol\n");
186     printf("  -P port   connect to specified port\n");
187     printf("  -l user   connect with specified username\n");
188     printf("  -batch    disable all interactive prompts\n");
189     printf("The following options only apply to SSH connections:\n");
190     printf("  -pw passw login with specified password\n");
191     printf("  -D [listen-IP:]listen-port\n");
192     printf("            Dynamic SOCKS-based port forwarding\n");
193     printf("  -L [listen-IP:]listen-port:host:port\n");
194     printf("            Forward local port to remote address\n");
195     printf("  -R [listen-IP:]listen-port:host:port\n");
196     printf("            Forward remote port to local address\n");
197     printf("  -X -x     enable / disable X11 forwarding\n");
198     printf("  -A -a     enable / disable agent forwarding\n");
199     printf("  -t -T     enable / disable pty allocation\n");
200     printf("  -1 -2     force use of particular protocol version\n");
201     printf("  -4 -6     force use of IPv4 or IPv6\n");
202     printf("  -C        enable compression\n");
203     printf("  -i key    private key file for authentication\n");
204     printf("  -noagent  disable use of Pageant\n");
205     printf("  -agent    enable use of Pageant\n");
206     printf("  -m file   read remote command(s) from file\n");
207     printf("  -s        remote command is an SSH subsystem (SSH-2 only)\n");
208     printf("  -N        don't start a shell/command (SSH-2 only)\n");
209     printf("  -nc host:port\n");
210     printf("            open tunnel in place of session (SSH-2 only)\n");
211     printf("  -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
212     printf("            Specify the serial configuration (serial only)\n");
213     exit(1);
214 }
215
216 static void version(void)
217 {
218     printf("plink: %s\n", ver);
219     exit(1);
220 }
221
222 char *do_select(SOCKET skt, int startup)
223 {
224     int events;
225     if (startup) {
226         events = (FD_CONNECT | FD_READ | FD_WRITE |
227                   FD_OOB | FD_CLOSE | FD_ACCEPT);
228     } else {
229         events = 0;
230     }
231     if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
232         switch (p_WSAGetLastError()) {
233           case WSAENETDOWN:
234             return "Network is down";
235           default:
236             return "WSAEventSelect(): unknown error";
237         }
238     }
239     return NULL;
240 }
241
242 int stdin_gotdata(struct handle *h, void *data, int len)
243 {
244     if (len < 0) {
245         /*
246          * Special case: report read error.
247          */
248         char buf[4096];
249         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -len, 0,
250                       buf, lenof(buf), NULL);
251         buf[lenof(buf)-1] = '\0';
252         if (buf[strlen(buf)-1] == '\n')
253             buf[strlen(buf)-1] = '\0';
254         fprintf(stderr, "Unable to read from standard input: %s\n", buf);
255         cleanup_exit(0);
256     }
257     noise_ultralight(len);
258     if (connopen && back->connected(backhandle)) {
259         if (len > 0) {
260             return back->send(backhandle, data, len);
261         } else {
262             back->special(backhandle, TS_EOF);
263             return 0;
264         }
265     } else
266         return 0;
267 }
268
269 void stdouterr_sent(struct handle *h, int new_backlog)
270 {
271     if (new_backlog < 0) {
272         /*
273          * Special case: report write error.
274          */
275         char buf[4096];
276         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -new_backlog, 0,
277                       buf, lenof(buf), NULL);
278         buf[lenof(buf)-1] = '\0';
279         if (buf[strlen(buf)-1] == '\n')
280             buf[strlen(buf)-1] = '\0';
281         fprintf(stderr, "Unable to write to standard %s: %s\n",
282                 (h == stdout_handle ? "output" : "error"), buf);
283         cleanup_exit(0);
284     }
285     if (connopen && back->connected(backhandle)) {
286         back->unthrottle(backhandle, (handle_backlog(stdout_handle) +
287                                       handle_backlog(stderr_handle)));
288     }
289 }
290
291 const int share_can_be_downstream = TRUE;
292 const int share_can_be_upstream = TRUE;
293
294 int main(int argc, char **argv)
295 {
296     int sending;
297     int portnumber = -1;
298     SOCKET *sklist;
299     int skcount, sksize;
300     int exitcode;
301     int errors;
302     int got_host = FALSE;
303     int use_subsystem = 0;
304     unsigned long now, next, then;
305
306     sklist = NULL;
307     skcount = sksize = 0;
308     /*
309      * Initialise port and protocol to sensible defaults. (These
310      * will be overridden by more or less anything.)
311      */
312     default_protocol = PROT_SSH;
313     default_port = 22;
314
315     flags = FLAG_STDERR;
316     /*
317      * Process the command line.
318      */
319     conf = conf_new();
320     do_defaults(NULL, conf);
321     loaded_session = FALSE;
322     default_protocol = conf_get_int(conf, CONF_protocol);
323     default_port = conf_get_int(conf, CONF_port);
324     errors = 0;
325     {
326         /*
327          * Override the default protocol if PLINK_PROTOCOL is set.
328          */
329         char *p = getenv("PLINK_PROTOCOL");
330         if (p) {
331             const Backend *b = backend_from_name(p);
332             if (b) {
333                 default_protocol = b->protocol;
334                 default_port = b->default_port;
335                 conf_set_int(conf, CONF_protocol, default_protocol);
336                 conf_set_int(conf, CONF_port, default_port);
337             }
338         }
339     }
340     while (--argc) {
341         char *p = *++argv;
342         if (*p == '-') {
343             int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
344                                             1, conf);
345             if (ret == -2) {
346                 fprintf(stderr,
347                         "plink: option \"%s\" requires an argument\n", p);
348                 errors = 1;
349             } else if (ret == 2) {
350                 --argc, ++argv;
351             } else if (ret == 1) {
352                 continue;
353             } else if (!strcmp(p, "-batch")) {
354                 console_batch_mode = 1;
355             } else if (!strcmp(p, "-s")) {
356                 /* Save status to write to conf later. */
357                 use_subsystem = 1;
358             } else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
359                 version();
360             } else if (!strcmp(p, "--help")) {
361                 usage();
362             } else if (!strcmp(p, "-pgpfp")) {
363                 pgp_fingerprints();
364                 exit(1);
365             } else {
366                 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
367                 errors = 1;
368             }
369         } else if (*p) {
370             if (!conf_launchable(conf) || !(got_host || loaded_session)) {
371                 char *q = p;
372                 /*
373                  * If the hostname starts with "telnet:", set the
374                  * protocol to Telnet and process the string as a
375                  * Telnet URL.
376                  */
377                 if (!strncmp(q, "telnet:", 7)) {
378                     char c;
379
380                     q += 7;
381                     if (q[0] == '/' && q[1] == '/')
382                         q += 2;
383                     conf_set_int(conf, CONF_protocol, PROT_TELNET);
384                     p = q;
385                     while (*p && *p != ':' && *p != '/')
386                         p++;
387                     c = *p;
388                     if (*p)
389                         *p++ = '\0';
390                     if (c == ':')
391                         conf_set_int(conf, CONF_port, atoi(p));
392                     else
393                         conf_set_int(conf, CONF_port, -1);
394                     conf_set_str(conf, CONF_host, q);
395                     got_host = TRUE;
396                 } else {
397                     char *r, *user, *host;
398                     /*
399                      * Before we process the [user@]host string, we
400                      * first check for the presence of a protocol
401                      * prefix (a protocol name followed by ",").
402                      */
403                     r = strchr(p, ',');
404                     if (r) {
405                         const Backend *b;
406                         *r = '\0';
407                         b = backend_from_name(p);
408                         if (b) {
409                             default_protocol = b->protocol;
410                             conf_set_int(conf, CONF_protocol,
411                                          default_protocol);
412                             portnumber = b->default_port;
413                         }
414                         p = r + 1;
415                     }
416
417                     /*
418                      * A nonzero length string followed by an @ is treated
419                      * as a username. (We discount an _initial_ @.) The
420                      * rest of the string (or the whole string if no @)
421                      * is treated as a session name and/or hostname.
422                      */
423                     r = strrchr(p, '@');
424                     if (r == p)
425                         p++, r = NULL; /* discount initial @ */
426                     if (r) {
427                         *r++ = '\0';
428                         user = p, host = r;
429                     } else {
430                         user = NULL, host = p;
431                     }
432
433                     /*
434                      * Now attempt to load a saved session with the
435                      * same name as the hostname.
436                      */
437                     {
438                         Conf *conf2 = conf_new();
439                         do_defaults(host, conf2);
440                         if (loaded_session || !conf_launchable(conf2)) {
441                             /* No settings for this host; use defaults */
442                             /* (or session was already loaded with -load) */
443                             conf_set_str(conf, CONF_host, host);
444                             conf_set_int(conf, CONF_port, default_port);
445                             got_host = TRUE;
446                         } else {
447                             conf_copy_into(conf, conf2);
448                             loaded_session = TRUE;
449                         }
450                         conf_free(conf2);
451                     }
452
453                     if (user) {
454                         /* Patch in specified username. */
455                         conf_set_str(conf, CONF_username, user);
456                     }
457
458                 }
459             } else {
460                 char *command;
461                 int cmdlen, cmdsize;
462                 cmdlen = cmdsize = 0;
463                 command = NULL;
464
465                 while (argc) {
466                     while (*p) {
467                         if (cmdlen >= cmdsize) {
468                             cmdsize = cmdlen + 512;
469                             command = sresize(command, cmdsize, char);
470                         }
471                         command[cmdlen++]=*p++;
472                     }
473                     if (cmdlen >= cmdsize) {
474                         cmdsize = cmdlen + 512;
475                         command = sresize(command, cmdsize, char);
476                     }
477                     command[cmdlen++]=' '; /* always add trailing space */
478                     if (--argc) p = *++argv;
479                 }
480                 if (cmdlen) command[--cmdlen]='\0';
481                                        /* change trailing blank to NUL */
482                 conf_set_str(conf, CONF_remote_cmd, command);
483                 conf_set_str(conf, CONF_remote_cmd2, "");
484                 conf_set_int(conf, CONF_nopty, TRUE);  /* command => no tty */
485
486                 break;                 /* done with cmdline */
487             }
488         }
489     }
490
491     if (errors)
492         return 1;
493
494     if (!conf_launchable(conf) || !(got_host || loaded_session)) {
495         usage();
496     }
497
498     /*
499      * Muck about with the hostname in various ways.
500      */
501     {
502         char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
503         char *host = hostbuf;
504         char *p, *q;
505
506         /*
507          * Trim leading whitespace.
508          */
509         host += strspn(host, " \t");
510
511         /*
512          * See if host is of the form user@host, and separate out
513          * the username if so.
514          */
515         if (host[0] != '\0') {
516             char *atsign = strrchr(host, '@');
517             if (atsign) {
518                 *atsign = '\0';
519                 conf_set_str(conf, CONF_username, host);
520                 host = atsign + 1;
521             }
522         }
523
524         /*
525          * Trim off a colon suffix if it's there.
526          */
527         host[strcspn(host, ":")] = '\0';
528
529         /*
530          * Remove any remaining whitespace.
531          */
532         p = hostbuf;
533         q = host;
534         while (*q) {
535             if (*q != ' ' && *q != '\t')
536                 *p++ = *q;
537             q++;
538         }
539         *p = '\0';
540
541         conf_set_str(conf, CONF_host, hostbuf);
542         sfree(hostbuf);
543     }
544
545     /*
546      * Perform command-line overrides on session configuration.
547      */
548     cmdline_run_saved(conf);
549
550     /*
551      * Apply subsystem status.
552      */
553     if (use_subsystem)
554         conf_set_int(conf, CONF_ssh_subsys, TRUE);
555
556     if (!*conf_get_str(conf, CONF_remote_cmd) &&
557         !*conf_get_str(conf, CONF_remote_cmd2) &&
558         !*conf_get_str(conf, CONF_ssh_nc_host))
559         flags |= FLAG_INTERACTIVE;
560
561     /*
562      * Select protocol. This is farmed out into a table in a
563      * separate file to enable an ssh-free variant.
564      */
565     back = backend_from_proto(conf_get_int(conf, CONF_protocol));
566     if (back == NULL) {
567         fprintf(stderr,
568                 "Internal fault: Unsupported protocol found\n");
569         return 1;
570     }
571
572     /*
573      * Select port.
574      */
575     if (portnumber != -1)
576         conf_set_int(conf, CONF_port, portnumber);
577
578     sk_init();
579     if (p_WSAEventSelect == NULL) {
580         fprintf(stderr, "Plink requires WinSock 2\n");
581         return 1;
582     }
583
584     logctx = log_init(NULL, conf);
585     console_provide_logctx(logctx);
586
587     /*
588      * Start up the connection.
589      */
590     netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
591     {
592         const char *error;
593         char *realhost;
594         /* nodelay is only useful if stdin is a character device (console) */
595         int nodelay = conf_get_int(conf, CONF_tcp_nodelay) &&
596             (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
597
598         error = back->init(NULL, &backhandle, conf,
599                            conf_get_str(conf, CONF_host),
600                            conf_get_int(conf, CONF_port),
601                            &realhost, nodelay,
602                            conf_get_int(conf, CONF_tcp_keepalives));
603         if (error) {
604             fprintf(stderr, "Unable to open connection:\n%s", error);
605             return 1;
606         }
607         back->provide_logctx(backhandle, logctx);
608         sfree(realhost);
609     }
610     connopen = 1;
611
612     inhandle = GetStdHandle(STD_INPUT_HANDLE);
613     outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
614     errhandle = GetStdHandle(STD_ERROR_HANDLE);
615
616     /*
617      * Turn off ECHO and LINE input modes. We don't care if this
618      * call fails, because we know we aren't necessarily running in
619      * a console.
620      */
621     GetConsoleMode(inhandle, &orig_console_mode);
622     SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
623
624     /*
625      * Pass the output handles to the handle-handling subsystem.
626      * (The input one we leave until we're through the
627      * authentication process.)
628      */
629     stdout_handle = handle_output_new(outhandle, stdouterr_sent, NULL, 0);
630     stderr_handle = handle_output_new(errhandle, stdouterr_sent, NULL, 0);
631
632     main_thread_id = GetCurrentThreadId();
633
634     sending = FALSE;
635
636     now = GETTICKCOUNT();
637
638     while (1) {
639         int nhandles;
640         HANDLE *handles;        
641         int n;
642         DWORD ticks;
643
644         if (!sending && back->sendok(backhandle)) {
645             stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL,
646                                             0);
647             sending = TRUE;
648         }
649
650         if (toplevel_callback_pending()) {
651             ticks = 0;
652         } else if (run_timers(now, &next)) {
653             then = now;
654             now = GETTICKCOUNT();
655             if (now - then > next - then)
656                 ticks = 0;
657             else
658                 ticks = next - now;
659         } else {
660             ticks = INFINITE;
661         }
662
663         handles = handle_get_events(&nhandles);
664         handles = sresize(handles, nhandles+1, HANDLE);
665         handles[nhandles] = netevent;
666         n = MsgWaitForMultipleObjects(nhandles+1, handles, FALSE, ticks,
667                                       QS_POSTMESSAGE);
668         if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
669             handle_got_event(handles[n - WAIT_OBJECT_0]);
670         } else if (n == WAIT_OBJECT_0 + nhandles) {
671             WSANETWORKEVENTS things;
672             SOCKET socket;
673             extern SOCKET first_socket(int *), next_socket(int *);
674             extern int select_result(WPARAM, LPARAM);
675             int i, socketstate;
676
677             /*
678              * We must not call select_result() for any socket
679              * until we have finished enumerating within the tree.
680              * This is because select_result() may close the socket
681              * and modify the tree.
682              */
683             /* Count the active sockets. */
684             i = 0;
685             for (socket = first_socket(&socketstate);
686                  socket != INVALID_SOCKET;
687                  socket = next_socket(&socketstate)) i++;
688
689             /* Expand the buffer if necessary. */
690             if (i > sksize) {
691                 sksize = i + 16;
692                 sklist = sresize(sklist, sksize, SOCKET);
693             }
694
695             /* Retrieve the sockets into sklist. */
696             skcount = 0;
697             for (socket = first_socket(&socketstate);
698                  socket != INVALID_SOCKET;
699                  socket = next_socket(&socketstate)) {
700                 sklist[skcount++] = socket;
701             }
702
703             /* Now we're done enumerating; go through the list. */
704             for (i = 0; i < skcount; i++) {
705                 WPARAM wp;
706                 socket = sklist[i];
707                 wp = (WPARAM) socket;
708                 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
709                     static const struct { int bit, mask; } eventtypes[] = {
710                         {FD_CONNECT_BIT, FD_CONNECT},
711                         {FD_READ_BIT, FD_READ},
712                         {FD_CLOSE_BIT, FD_CLOSE},
713                         {FD_OOB_BIT, FD_OOB},
714                         {FD_WRITE_BIT, FD_WRITE},
715                         {FD_ACCEPT_BIT, FD_ACCEPT},
716                     };
717                     int e;
718
719                     noise_ultralight(socket);
720                     noise_ultralight(things.lNetworkEvents);
721
722                     for (e = 0; e < lenof(eventtypes); e++)
723                         if (things.lNetworkEvents & eventtypes[e].mask) {
724                             LPARAM lp;
725                             int err = things.iErrorCode[eventtypes[e].bit];
726                             lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
727                             connopen &= select_result(wp, lp);
728                         }
729                 }
730             }
731         } else if (n == WAIT_OBJECT_0 + nhandles + 1) {
732             MSG msg;
733             while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
734                                WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
735                                PM_REMOVE)) {
736                 struct agent_callback *c = (struct agent_callback *)msg.lParam;
737                 c->callback(c->callback_ctx, c->data, c->len);
738                 sfree(c);
739             }
740         }
741
742         run_toplevel_callbacks();
743
744         if (n == WAIT_TIMEOUT) {
745             now = next;
746         } else {
747             now = GETTICKCOUNT();
748         }
749
750         sfree(handles);
751
752         if (sending)
753             handle_unthrottle(stdin_handle, back->sendbuffer(backhandle));
754
755         if ((!connopen || !back->connected(backhandle)) &&
756             handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0)
757             break;                     /* we closed the connection */
758     }
759     exitcode = back->exitcode(backhandle);
760     if (exitcode < 0) {
761         fprintf(stderr, "Remote process exit code unavailable\n");
762         exitcode = 1;                  /* this is an error condition */
763     }
764     cleanup_exit(exitcode);
765     return 0;                          /* placate compiler warning */
766 }