]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - plink.c
PayPal is actually _much_ easier to work with than e-gold these
[PuTTY.git] / plink.c
1 /*
2  * PLink - a 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_XUSER + 4)
16
17 #define MAX_STDIN_BACKLOG 4096
18
19 struct agent_callback {
20     void (*callback)(void *, void *, int);
21     void *callback_ctx;
22     void *data;
23     int len;
24 };
25
26 void fatalbox(char *p, ...)
27 {
28     va_list ap;
29     fprintf(stderr, "FATAL ERROR: ");
30     va_start(ap, p);
31     vfprintf(stderr, p, ap);
32     va_end(ap);
33     fputc('\n', stderr);
34     cleanup_exit(1);
35 }
36 void modalfatalbox(char *p, ...)
37 {
38     va_list ap;
39     fprintf(stderr, "FATAL ERROR: ");
40     va_start(ap, p);
41     vfprintf(stderr, p, ap);
42     va_end(ap);
43     fputc('\n', stderr);
44     cleanup_exit(1);
45 }
46 void connection_fatal(void *frontend, char *p, ...)
47 {
48     va_list ap;
49     fprintf(stderr, "FATAL ERROR: ");
50     va_start(ap, p);
51     vfprintf(stderr, p, ap);
52     va_end(ap);
53     fputc('\n', stderr);
54     cleanup_exit(1);
55 }
56 void cmdline_error(char *p, ...)
57 {
58     va_list ap;
59     fprintf(stderr, "plink: ");
60     va_start(ap, p);
61     vfprintf(stderr, p, ap);
62     va_end(ap);
63     fputc('\n', stderr);
64     exit(1);
65 }
66
67 HANDLE inhandle, outhandle, errhandle;
68 DWORD orig_console_mode;
69
70 WSAEVENT netevent;
71
72 static Backend *back;
73 static void *backhandle;
74 static Config cfg;
75
76 int term_ldisc(Terminal *term, int mode)
77 {
78     return FALSE;
79 }
80 void ldisc_update(void *frontend, int echo, int edit)
81 {
82     /* Update stdin read mode to reflect changes in line discipline. */
83     DWORD mode;
84
85     mode = ENABLE_PROCESSED_INPUT;
86     if (echo)
87         mode = mode | ENABLE_ECHO_INPUT;
88     else
89         mode = mode & ~ENABLE_ECHO_INPUT;
90     if (edit)
91         mode = mode | ENABLE_LINE_INPUT;
92     else
93         mode = mode & ~ENABLE_LINE_INPUT;
94     SetConsoleMode(inhandle, mode);
95 }
96
97 struct input_data {
98     DWORD len;
99     char buffer[4096];
100     HANDLE event, eventback;
101 };
102
103 static DWORD WINAPI stdin_read_thread(void *param)
104 {
105     struct input_data *idata = (struct input_data *) param;
106     HANDLE inhandle;
107
108     inhandle = GetStdHandle(STD_INPUT_HANDLE);
109
110     while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
111                     &idata->len, NULL) && idata->len > 0) {
112         SetEvent(idata->event);
113         WaitForSingleObject(idata->eventback, INFINITE);
114     }
115
116     idata->len = 0;
117     SetEvent(idata->event);
118
119     return 0;
120 }
121
122 struct output_data {
123     DWORD len, lenwritten;
124     int writeret;
125     char *buffer;
126     int is_stderr, done;
127     HANDLE event, eventback;
128     int busy;
129 };
130
131 static DWORD WINAPI stdout_write_thread(void *param)
132 {
133     struct output_data *odata = (struct output_data *) param;
134     HANDLE outhandle, errhandle;
135
136     outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
137     errhandle = GetStdHandle(STD_ERROR_HANDLE);
138
139     while (1) {
140         WaitForSingleObject(odata->eventback, INFINITE);
141         if (odata->done)
142             break;
143         odata->writeret =
144             WriteFile(odata->is_stderr ? errhandle : outhandle,
145                       odata->buffer, odata->len, &odata->lenwritten, NULL);
146         SetEvent(odata->event);
147     }
148
149     return 0;
150 }
151
152 bufchain stdout_data, stderr_data;
153 struct output_data odata, edata;
154
155 void try_output(int is_stderr)
156 {
157     struct output_data *data = (is_stderr ? &edata : &odata);
158     void *senddata;
159     int sendlen;
160
161     if (!data->busy) {
162         bufchain_prefix(is_stderr ? &stderr_data : &stdout_data,
163                         &senddata, &sendlen);
164         data->buffer = senddata;
165         data->len = sendlen;
166         SetEvent(data->eventback);
167         data->busy = 1;
168     }
169 }
170
171 int from_backend(void *frontend_handle, int is_stderr,
172                  const char *data, int len)
173 {
174     int osize, esize;
175
176     if (is_stderr) {
177         bufchain_add(&stderr_data, data, len);
178         try_output(1);
179     } else {
180         bufchain_add(&stdout_data, data, len);
181         try_output(0);
182     }
183
184     osize = bufchain_size(&stdout_data);
185     esize = bufchain_size(&stderr_data);
186
187     return osize + esize;
188 }
189
190 static DWORD main_thread_id;
191
192 void agent_schedule_callback(void (*callback)(void *, void *, int),
193                              void *callback_ctx, void *data, int len)
194 {
195     struct agent_callback *c = snew(struct agent_callback);
196     c->callback = callback;
197     c->callback_ctx = callback_ctx;
198     c->data = data;
199     c->len = len;
200     PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
201 }
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        show verbose messages\n");
214     printf("  -load sessname  Load settings from saved session\n");
215     printf("  -ssh -telnet -rlogin -raw\n");
216     printf("            force use of a particular protocol (default SSH)\n");
217     printf("  -P port   connect to specified port\n");
218     printf("  -l user   connect with specified username\n");
219     printf("  -m file   read remote command(s) from file\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("  -C        enable compression\n");
234     printf("  -i key    private key file for authentication\n");
235     printf("  -s        remote command is an SSH subsystem (SSH-2 only)\n");
236     exit(1);
237 }
238
239 char *do_select(SOCKET skt, int startup)
240 {
241     int events;
242     if (startup) {
243         events = (FD_CONNECT | FD_READ | FD_WRITE |
244                   FD_OOB | FD_CLOSE | FD_ACCEPT);
245     } else {
246         events = 0;
247     }
248     if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
249         switch (p_WSAGetLastError()) {
250           case WSAENETDOWN:
251             return "Network is down";
252           default:
253             return "WSAEventSelect(): unknown error";
254         }
255     }
256     return NULL;
257 }
258
259 int main(int argc, char **argv)
260 {
261     WSAEVENT stdinevent, stdoutevent, stderrevent;
262     HANDLE handles[4];
263     DWORD in_threadid, out_threadid, err_threadid;
264     struct input_data idata;
265     int reading;
266     int sending;
267     int portnumber = -1;
268     SOCKET *sklist;
269     int skcount, sksize;
270     int connopen;
271     int exitcode;
272     int errors;
273     int use_subsystem = 0;
274
275     ssh_get_line = console_get_line;
276
277     sklist = NULL;
278     skcount = sksize = 0;
279     /*
280      * Initialise port and protocol to sensible defaults. (These
281      * will be overridden by more or less anything.)
282      */
283     default_protocol = PROT_SSH;
284     default_port = 22;
285
286     flags = FLAG_STDERR;
287     /*
288      * Process the command line.
289      */
290     do_defaults(NULL, &cfg);
291     default_protocol = cfg.protocol;
292     default_port = cfg.port;
293     errors = 0;
294     {
295         /*
296          * Override the default protocol if PLINK_PROTOCOL is set.
297          */
298         char *p = getenv("PLINK_PROTOCOL");
299         int i;
300         if (p) {
301             for (i = 0; backends[i].backend != NULL; i++) {
302                 if (!strcmp(backends[i].name, p)) {
303                     default_protocol = cfg.protocol = backends[i].protocol;
304                     default_port = cfg.port =
305                         backends[i].backend->default_port;
306                     break;
307                 }
308             }
309         }
310     }
311     while (--argc) {
312         char *p = *++argv;
313         if (*p == '-') {
314             int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
315                                             1, &cfg);
316             if (ret == -2) {
317                 fprintf(stderr,
318                         "plink: option \"%s\" requires an argument\n", p);
319                 errors = 1;
320             } else if (ret == 2) {
321                 --argc, ++argv;
322             } else if (ret == 1) {
323                 continue;
324             } else if (!strcmp(p, "-batch")) {
325                 console_batch_mode = 1;
326             } else if (!strcmp(p, "-s")) {
327                 /* Save status to write to cfg later. */
328                 use_subsystem = 1;
329             } else {
330                 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
331                 errors = 1;
332             }
333         } else if (*p) {
334             if (!*cfg.host) {
335                 char *q = p;
336                 /*
337                  * If the hostname starts with "telnet:", set the
338                  * protocol to Telnet and process the string as a
339                  * Telnet URL.
340                  */
341                 if (!strncmp(q, "telnet:", 7)) {
342                     char c;
343
344                     q += 7;
345                     if (q[0] == '/' && q[1] == '/')
346                         q += 2;
347                     cfg.protocol = PROT_TELNET;
348                     p = q;
349                     while (*p && *p != ':' && *p != '/')
350                         p++;
351                     c = *p;
352                     if (*p)
353                         *p++ = '\0';
354                     if (c == ':')
355                         cfg.port = atoi(p);
356                     else
357                         cfg.port = -1;
358                     strncpy(cfg.host, q, sizeof(cfg.host) - 1);
359                     cfg.host[sizeof(cfg.host) - 1] = '\0';
360                 } else {
361                     char *r;
362                     /*
363                      * Before we process the [user@]host string, we
364                      * first check for the presence of a protocol
365                      * prefix (a protocol name followed by ",").
366                      */
367                     r = strchr(p, ',');
368                     if (r) {
369                         int i, j;
370                         for (i = 0; backends[i].backend != NULL; i++) {
371                             j = strlen(backends[i].name);
372                             if (j == r - p &&
373                                 !memcmp(backends[i].name, p, j)) {
374                                 default_protocol = cfg.protocol =
375                                     backends[i].protocol;
376                                 portnumber =
377                                     backends[i].backend->default_port;
378                                 p = r + 1;
379                                 break;
380                             }
381                         }
382                     }
383
384                     /*
385                      * Three cases. Either (a) there's a nonzero
386                      * length string followed by an @, in which
387                      * case that's user and the remainder is host.
388                      * Or (b) there's only one string, not counting
389                      * a potential initial @, and it exists in the
390                      * saved-sessions database. Or (c) only one
391                      * string and it _doesn't_ exist in the
392                      * database.
393                      */
394                     r = strrchr(p, '@');
395                     if (r == p)
396                         p++, r = NULL; /* discount initial @ */
397                     if (r == NULL) {
398                         /*
399                          * One string.
400                          */
401                         Config cfg2;
402                         do_defaults(p, &cfg2);
403                         if (cfg2.host[0] == '\0') {
404                             /* No settings for this host; use defaults */
405                             strncpy(cfg.host, p, sizeof(cfg.host) - 1);
406                             cfg.host[sizeof(cfg.host) - 1] = '\0';
407                             cfg.port = default_port;
408                         } else {
409                             cfg = cfg2;
410                             cfg.remote_cmd_ptr = cfg.remote_cmd;
411                         }
412                     } else {
413                         *r++ = '\0';
414                         strncpy(cfg.username, p, sizeof(cfg.username) - 1);
415                         cfg.username[sizeof(cfg.username) - 1] = '\0';
416                         strncpy(cfg.host, r, sizeof(cfg.host) - 1);
417                         cfg.host[sizeof(cfg.host) - 1] = '\0';
418                         cfg.port = default_port;
419                     }
420                 }
421             } else {
422                 char *command;
423                 int cmdlen, cmdsize;
424                 cmdlen = cmdsize = 0;
425                 command = NULL;
426
427                 while (argc) {
428                     while (*p) {
429                         if (cmdlen >= cmdsize) {
430                             cmdsize = cmdlen + 512;
431                             command = sresize(command, cmdsize, char);
432                         }
433                         command[cmdlen++]=*p++;
434                     }
435                     if (cmdlen >= cmdsize) {
436                         cmdsize = cmdlen + 512;
437                         command = sresize(command, cmdsize, char);
438                     }
439                     command[cmdlen++]=' '; /* always add trailing space */
440                     if (--argc) p = *++argv;
441                 }
442                 if (cmdlen) command[--cmdlen]='\0';
443                                        /* change trailing blank to NUL */
444                 cfg.remote_cmd_ptr = command;
445                 cfg.remote_cmd_ptr2 = NULL;
446                 cfg.nopty = TRUE;      /* command => no terminal */
447
448                 break;                 /* done with cmdline */
449             }
450         }
451     }
452
453     if (errors)
454         return 1;
455
456     if (!*cfg.host) {
457         usage();
458     }
459
460     /*
461      * Trim leading whitespace off the hostname if it's there.
462      */
463     {
464         int space = strspn(cfg.host, " \t");
465         memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
466     }
467
468     /* See if host is of the form user@host */
469     if (cfg.host[0] != '\0') {
470         char *atsign = strchr(cfg.host, '@');
471         /* Make sure we're not overflowing the user field */
472         if (atsign) {
473             if (atsign - cfg.host < sizeof cfg.username) {
474                 strncpy(cfg.username, cfg.host, atsign - cfg.host);
475                 cfg.username[atsign - cfg.host] = '\0';
476             }
477             memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
478         }
479     }
480
481     /*
482      * Perform command-line overrides on session configuration.
483      */
484     cmdline_run_saved(&cfg);
485
486     /*
487      * Apply subsystem status.
488      */
489     if (use_subsystem)
490         cfg.ssh_subsys = TRUE;
491
492     /*
493      * Trim a colon suffix off the hostname if it's there.
494      */
495     cfg.host[strcspn(cfg.host, ":")] = '\0';
496
497     /*
498      * Remove any remaining whitespace from the hostname.
499      */
500     {
501         int p1 = 0, p2 = 0;
502         while (cfg.host[p2] != '\0') {
503             if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
504                 cfg.host[p1] = cfg.host[p2];
505                 p1++;
506             }
507             p2++;
508         }
509         cfg.host[p1] = '\0';
510     }
511
512     if (!*cfg.remote_cmd_ptr)
513         flags |= FLAG_INTERACTIVE;
514
515     /*
516      * Select protocol. This is farmed out into a table in a
517      * separate file to enable an ssh-free variant.
518      */
519     {
520         int i;
521         back = NULL;
522         for (i = 0; backends[i].backend != NULL; i++)
523             if (backends[i].protocol == cfg.protocol) {
524                 back = backends[i].backend;
525                 break;
526             }
527         if (back == NULL) {
528             fprintf(stderr,
529                     "Internal fault: Unsupported protocol found\n");
530             return 1;
531         }
532     }
533
534     /*
535      * Select port.
536      */
537     if (portnumber != -1)
538         cfg.port = portnumber;
539
540     sk_init();
541     if (p_WSAEventSelect == NULL) {
542         fprintf(stderr, "Plink requires WinSock 2\n");
543         return 1;
544     }
545
546     /*
547      * Start up the connection.
548      */
549     netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
550     {
551         const char *error;
552         char *realhost;
553         /* nodelay is only useful if stdin is a character device (console) */
554         int nodelay = cfg.tcp_nodelay &&
555             (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
556
557         error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
558                            &realhost, nodelay);
559         if (error) {
560             fprintf(stderr, "Unable to open connection:\n%s", error);
561             return 1;
562         }
563         logctx = log_init(NULL, &cfg);
564         back->provide_logctx(backhandle, logctx);
565         console_provide_logctx(logctx);
566         sfree(realhost);
567     }
568     connopen = 1;
569
570     stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
571     stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
572     stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
573
574     inhandle = GetStdHandle(STD_INPUT_HANDLE);
575     outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
576     errhandle = GetStdHandle(STD_ERROR_HANDLE);
577     GetConsoleMode(inhandle, &orig_console_mode);
578     SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
579
580     main_thread_id = GetCurrentThreadId();
581
582     /*
583      * Turn off ECHO and LINE input modes. We don't care if this
584      * call fails, because we know we aren't necessarily running in
585      * a console.
586      */
587     handles[0] = netevent;
588     handles[1] = stdinevent;
589     handles[2] = stdoutevent;
590     handles[3] = stderrevent;
591     sending = FALSE;
592
593     /*
594      * Create spare threads to write to stdout and stderr, so we
595      * can arrange asynchronous writes.
596      */
597     odata.event = stdoutevent;
598     odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
599     odata.is_stderr = 0;
600     odata.busy = odata.done = 0;
601     if (!CreateThread(NULL, 0, stdout_write_thread,
602                       &odata, 0, &out_threadid)) {
603         fprintf(stderr, "Unable to create output thread\n");
604         cleanup_exit(1);
605     }
606     edata.event = stderrevent;
607     edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
608     edata.is_stderr = 1;
609     edata.busy = edata.done = 0;
610     if (!CreateThread(NULL, 0, stdout_write_thread,
611                       &edata, 0, &err_threadid)) {
612         fprintf(stderr, "Unable to create error output thread\n");
613         cleanup_exit(1);
614     }
615
616     while (1) {
617         int n;
618
619         if (!sending && back->sendok(backhandle)) {
620             /*
621              * Create a separate thread to read from stdin. This is
622              * a total pain, but I can't find another way to do it:
623              *
624              *  - an overlapped ReadFile or ReadFileEx just doesn't
625              *    happen; we get failure from ReadFileEx, and
626              *    ReadFile blocks despite being given an OVERLAPPED
627              *    structure. Perhaps we can't do overlapped reads
628              *    on consoles. WHY THE HELL NOT?
629              * 
630              *  - WaitForMultipleObjects(netevent, console) doesn't
631              *    work, because it signals the console when
632              *    _anything_ happens, including mouse motions and
633              *    other things that don't cause data to be readable
634              *    - so we're back to ReadFile blocking.
635              */
636             idata.event = stdinevent;
637             idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
638             if (!CreateThread(NULL, 0, stdin_read_thread,
639                               &idata, 0, &in_threadid)) {
640                 fprintf(stderr, "Unable to create input thread\n");
641                 cleanup_exit(1);
642             }
643             sending = TRUE;
644         }
645
646         n = MsgWaitForMultipleObjects(4, handles, FALSE, INFINITE,
647                                       QS_POSTMESSAGE);
648         if (n == 0) {
649             WSANETWORKEVENTS things;
650             SOCKET socket;
651             extern SOCKET first_socket(int *), next_socket(int *);
652             extern int select_result(WPARAM, LPARAM);
653             int i, socketstate;
654
655             /*
656              * We must not call select_result() for any socket
657              * until we have finished enumerating within the tree.
658              * This is because select_result() may close the socket
659              * and modify the tree.
660              */
661             /* Count the active sockets. */
662             i = 0;
663             for (socket = first_socket(&socketstate);
664                  socket != INVALID_SOCKET;
665                  socket = next_socket(&socketstate)) i++;
666
667             /* Expand the buffer if necessary. */
668             if (i > sksize) {
669                 sksize = i + 16;
670                 sklist = sresize(sklist, sksize, SOCKET);
671             }
672
673             /* Retrieve the sockets into sklist. */
674             skcount = 0;
675             for (socket = first_socket(&socketstate);
676                  socket != INVALID_SOCKET;
677                  socket = next_socket(&socketstate)) {
678                 sklist[skcount++] = socket;
679             }
680
681             /* Now we're done enumerating; go through the list. */
682             for (i = 0; i < skcount; i++) {
683                 WPARAM wp;
684                 socket = sklist[i];
685                 wp = (WPARAM) socket;
686                 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
687                     static const struct { int bit, mask; } eventtypes[] = {
688                         {FD_CONNECT_BIT, FD_CONNECT},
689                         {FD_READ_BIT, FD_READ},
690                         {FD_CLOSE_BIT, FD_CLOSE},
691                         {FD_OOB_BIT, FD_OOB},
692                         {FD_WRITE_BIT, FD_WRITE},
693                         {FD_ACCEPT_BIT, FD_ACCEPT},
694                     };
695                     int e;
696
697                     noise_ultralight(socket);
698                     noise_ultralight(things.lNetworkEvents);
699
700                     for (e = 0; e < lenof(eventtypes); e++)
701                         if (things.lNetworkEvents & eventtypes[e].mask) {
702                             LPARAM lp;
703                             int err = things.iErrorCode[eventtypes[e].bit];
704                             lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
705                             connopen &= select_result(wp, lp);
706                         }
707                 }
708             }
709         } else if (n == 1) {
710             reading = 0;
711             noise_ultralight(idata.len);
712             if (connopen && back->socket(backhandle) != NULL) {
713                 if (idata.len > 0) {
714                     back->send(backhandle, idata.buffer, idata.len);
715                 } else {
716                     back->special(backhandle, TS_EOF);
717                 }
718             }
719         } else if (n == 2) {
720             odata.busy = 0;
721             if (!odata.writeret) {
722                 fprintf(stderr, "Unable to write to standard output\n");
723                 cleanup_exit(0);
724             }
725             bufchain_consume(&stdout_data, odata.lenwritten);
726             if (bufchain_size(&stdout_data) > 0)
727                 try_output(0);
728             if (connopen && back->socket(backhandle) != NULL) {
729                 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
730                                  bufchain_size(&stderr_data));
731             }
732         } else if (n == 3) {
733             edata.busy = 0;
734             if (!edata.writeret) {
735                 fprintf(stderr, "Unable to write to standard output\n");
736                 cleanup_exit(0);
737             }
738             bufchain_consume(&stderr_data, edata.lenwritten);
739             if (bufchain_size(&stderr_data) > 0)
740                 try_output(1);
741             if (connopen && back->socket(backhandle) != NULL) {
742                 back->unthrottle(backhandle, bufchain_size(&stdout_data) +
743                                  bufchain_size(&stderr_data));
744             }
745         } else if (n == 4) {
746             MSG msg;
747             while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
748                                WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
749                                PM_REMOVE)) {
750                 struct agent_callback *c = (struct agent_callback *)msg.lParam;
751                 c->callback(c->callback_ctx, c->data, c->len);
752                 sfree(c);
753             }
754         }
755         if (!reading && back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
756             SetEvent(idata.eventback);
757             reading = 1;
758         }
759         if ((!connopen || back->socket(backhandle) == NULL) &&
760             bufchain_size(&stdout_data) == 0 &&
761             bufchain_size(&stderr_data) == 0)
762             break;                     /* we closed the connection */
763     }
764     exitcode = back->exitcode(backhandle);
765     if (exitcode < 0) {
766         fprintf(stderr, "Remote process exit code unavailable\n");
767         exitcode = 1;                  /* this is an error condition */
768     }
769     cleanup_exit(exitcode);
770     return 0;                          /* placate compiler warning */
771 }