Upgrade tortoiseplink to putty 9002
[TortoiseGit.git] / src / TortoisePlink / Windows / WINHANDL.C
blobdbcab2b2a7e20ea7d504766a64be0b5c6dd3a313
1 /*\r
2  * winhandl.c: Module to give Windows front ends the general\r
3  * ability to deal with consoles, pipes, serial ports, or any other\r
4  * type of data stream accessed through a Windows API HANDLE rather\r
5  * than a WinSock SOCKET.\r
6  *\r
7  * We do this by spawning a subthread to continuously try to read\r
8  * from the handle. Every time a read successfully returns some\r
9  * data, the subthread sets an event object which is picked up by\r
10  * the main thread, and the main thread then sets an event in\r
11  * return to instruct the subthread to resume reading.\r
12  * \r
13  * Output works precisely the other way round, in a second\r
14  * subthread. The output subthread should not be attempting to\r
15  * write all the time, because it hasn't always got data _to_\r
16  * write; so the output thread waits for an event object notifying\r
17  * it to _attempt_ a write, and then it sets an event in return\r
18  * when one completes.\r
19  * \r
20  * (It's terribly annoying having to spawn a subthread for each\r
21  * direction of each handle. Technically it isn't necessary for\r
22  * serial ports, since we could use overlapped I/O within the main\r
23  * thread and wait directly on the event objects in the OVERLAPPED\r
24  * structures. However, we can't use this trick for some types of\r
25  * file handle at all - for some reason Windows restricts use of\r
26  * OVERLAPPED to files which were opened with the overlapped flag -\r
27  * and so we must use threads for those. This being the case, it's\r
28  * simplest just to use threads for everything rather than trying\r
29  * to keep track of multiple completely separate mechanisms.)\r
30  */\r
32 #include <assert.h>\r
34 #include "putty.h"\r
36 /* ----------------------------------------------------------------------\r
37  * Generic definitions.\r
38  */\r
40 /*\r
41  * Maximum amount of backlog we will allow to build up on an input\r
42  * handle before we stop reading from it.\r
43  */\r
44 #define MAX_BACKLOG 32768\r
46 struct handle_generic {\r
47     /*\r
48      * Initial fields common to both handle_input and handle_output\r
49      * structures.\r
50      * \r
51      * The three HANDLEs are set up at initialisation time and are\r
52      * thereafter read-only to both main thread and subthread.\r
53      * `moribund' is only used by the main thread; `done' is\r
54      * written by the main thread before signalling to the\r
55      * subthread. `defunct' and `busy' are used only by the main\r
56      * thread.\r
57      */\r
58     HANDLE h;                          /* the handle itself */\r
59     HANDLE ev_to_main;                 /* event used to signal main thread */\r
60     HANDLE ev_from_main;               /* event used to signal back to us */\r
61     int moribund;                      /* are we going to kill this soon? */\r
62     int done;                          /* request subthread to terminate */\r
63     int defunct;                       /* has the subthread already gone? */\r
64     int busy;                          /* operation currently in progress? */\r
65     void *privdata;                    /* for client to remember who they are */\r
66 };\r
68 /* ----------------------------------------------------------------------\r
69  * Input threads.\r
70  */\r
72 /*\r
73  * Data required by an input thread.\r
74  */\r
75 struct handle_input {\r
76     /*\r
77      * Copy of the handle_generic structure.\r
78      */\r
79     HANDLE h;                          /* the handle itself */\r
80     HANDLE ev_to_main;                 /* event used to signal main thread */\r
81     HANDLE ev_from_main;               /* event used to signal back to us */\r
82     int moribund;                      /* are we going to kill this soon? */\r
83     int done;                          /* request subthread to terminate */\r
84     int defunct;                       /* has the subthread already gone? */\r
85     int busy;                          /* operation currently in progress? */\r
86     void *privdata;                    /* for client to remember who they are */\r
88     /*\r
89      * Data set at initialisation and then read-only.\r
90      */\r
91     int flags;\r
93     /*\r
94      * Data set by the input thread before signalling ev_to_main,\r
95      * and read by the main thread after receiving that signal.\r
96      */\r
97     char buffer[4096];                 /* the data read from the handle */\r
98     DWORD len;                         /* how much data that was */\r
99     int readerr;                       /* lets us know about read errors */\r
101     /*\r
102      * Callback function called by this module when data arrives on\r
103      * an input handle.\r
104      */\r
105     handle_inputfn_t gotdata;\r
106 };\r
108 /*\r
109  * The actual thread procedure for an input thread.\r
110  */\r
111 static DWORD WINAPI handle_input_threadfunc(void *param)\r
113     struct handle_input *ctx = (struct handle_input *) param;\r
114     OVERLAPPED ovl, *povl;\r
115     HANDLE oev;\r
116     int readret, readlen;\r
118     if (ctx->flags & HANDLE_FLAG_OVERLAPPED) {\r
119         povl = &ovl;\r
120         oev = CreateEvent(NULL, TRUE, FALSE, NULL);\r
121     } else {\r
122         povl = NULL;\r
123     }\r
125     if (ctx->flags & HANDLE_FLAG_UNITBUFFER)\r
126         readlen = 1;\r
127     else\r
128         readlen = sizeof(ctx->buffer);\r
130     while (1) {\r
131         if (povl) {\r
132             memset(povl, 0, sizeof(OVERLAPPED));\r
133             povl->hEvent = oev;\r
134         }\r
135         readret = ReadFile(ctx->h, ctx->buffer,readlen, &ctx->len, povl);\r
136         if (!readret)\r
137             ctx->readerr = GetLastError();\r
138         else\r
139             ctx->readerr = 0;\r
140         if (povl && !readret && ctx->readerr == ERROR_IO_PENDING) {\r
141             WaitForSingleObject(povl->hEvent, INFINITE);\r
142             readret = GetOverlappedResult(ctx->h, povl, &ctx->len, FALSE);\r
143             if (!readret)\r
144                 ctx->readerr = GetLastError();\r
145             else\r
146                 ctx->readerr = 0;\r
147         }\r
149         if (!readret) {\r
150             /*\r
151              * Windows apparently sends ERROR_BROKEN_PIPE when a\r
152              * pipe we're reading from is closed normally from the\r
153              * writing end. This is ludicrous; if that situation\r
154              * isn't a natural EOF, _nothing_ is. So if we get that\r
155              * particular error, we pretend it's EOF.\r
156              */\r
157             if (ctx->readerr == ERROR_BROKEN_PIPE)\r
158                 ctx->readerr = 0;\r
159             ctx->len = 0;\r
160         }\r
162         if (readret && ctx->len == 0 &&\r
163             (ctx->flags & HANDLE_FLAG_IGNOREEOF))\r
164             continue;\r
166         SetEvent(ctx->ev_to_main);\r
168         if (!ctx->len)\r
169             break;\r
171         WaitForSingleObject(ctx->ev_from_main, INFINITE);\r
172         if (ctx->done)\r
173             break;                     /* main thread told us to shut down */\r
174     }\r
176     if (povl)\r
177         CloseHandle(oev);\r
179     return 0;\r
182 /*\r
183  * This is called after a succcessful read, or from the\r
184  * `unthrottle' function. It decides whether or not to begin a new\r
185  * read operation.\r
186  */\r
187 static void handle_throttle(struct handle_input *ctx, int backlog)\r
189     if (ctx->defunct)\r
190         return;\r
192     /*\r
193      * If there's a read operation already in progress, do nothing:\r
194      * when that completes, we'll come back here and be in a\r
195      * position to make a better decision.\r
196      */\r
197     if (ctx->busy)\r
198         return;\r
200     /*\r
201      * Otherwise, we must decide whether to start a new read based\r
202      * on the size of the backlog.\r
203      */\r
204     if (backlog < MAX_BACKLOG) {\r
205         SetEvent(ctx->ev_from_main);\r
206         ctx->busy = TRUE;\r
207     }\r
210 /* ----------------------------------------------------------------------\r
211  * Output threads.\r
212  */\r
214 /*\r
215  * Data required by an output thread.\r
216  */\r
217 struct handle_output {\r
218     /*\r
219      * Copy of the handle_generic structure.\r
220      */\r
221     HANDLE h;                          /* the handle itself */\r
222     HANDLE ev_to_main;                 /* event used to signal main thread */\r
223     HANDLE ev_from_main;               /* event used to signal back to us */\r
224     int moribund;                      /* are we going to kill this soon? */\r
225     int done;                          /* request subthread to terminate */\r
226     int defunct;                       /* has the subthread already gone? */\r
227     int busy;                          /* operation currently in progress? */\r
228     void *privdata;                    /* for client to remember who they are */\r
230     /*\r
231      * Data set at initialisation and then read-only.\r
232      */\r
233     int flags;\r
235     /*\r
236      * Data set by the main thread before signalling ev_from_main,\r
237      * and read by the input thread after receiving that signal.\r
238      */\r
239     char *buffer;                      /* the data to write */\r
240     DWORD len;                         /* how much data there is */\r
242     /*\r
243      * Data set by the input thread before signalling ev_to_main,\r
244      * and read by the main thread after receiving that signal.\r
245      */\r
246     DWORD lenwritten;                  /* how much data we actually wrote */\r
247     int writeerr;                      /* return value from WriteFile */\r
249     /*\r
250      * Data only ever read or written by the main thread.\r
251      */\r
252     bufchain queued_data;              /* data still waiting to be written */\r
254     /*\r
255      * Callback function called when the backlog in the bufchain\r
256      * drops.\r
257      */\r
258     handle_outputfn_t sentdata;\r
259 };\r
261 static DWORD WINAPI handle_output_threadfunc(void *param)\r
263     struct handle_output *ctx = (struct handle_output *) param;\r
264     OVERLAPPED ovl, *povl;\r
265     HANDLE oev;\r
266     int writeret;\r
268     if (ctx->flags & HANDLE_FLAG_OVERLAPPED) {\r
269         povl = &ovl;\r
270         oev = CreateEvent(NULL, TRUE, FALSE, NULL);\r
271     } else {\r
272         povl = NULL;\r
273     }\r
275     while (1) {\r
276         WaitForSingleObject(ctx->ev_from_main, INFINITE);\r
277         if (ctx->done) {\r
278             SetEvent(ctx->ev_to_main);\r
279             break;\r
280         }\r
281         if (povl) {\r
282             memset(povl, 0, sizeof(OVERLAPPED));\r
283             povl->hEvent = oev;\r
284         }\r
286         writeret = WriteFile(ctx->h, ctx->buffer, ctx->len,\r
287                              &ctx->lenwritten, povl);\r
288         if (!writeret)\r
289             ctx->writeerr = GetLastError();\r
290         else\r
291             ctx->writeerr = 0;\r
292         if (povl && !writeret && GetLastError() == ERROR_IO_PENDING) {\r
293             writeret = GetOverlappedResult(ctx->h, povl,\r
294                                            &ctx->lenwritten, TRUE);\r
295             if (!writeret)\r
296                 ctx->writeerr = GetLastError();\r
297             else\r
298                 ctx->writeerr = 0;\r
299         }\r
301         SetEvent(ctx->ev_to_main);\r
302         if (!writeret)\r
303             break;\r
304     }\r
306     if (povl)\r
307         CloseHandle(oev);\r
309     return 0;\r
312 static void handle_try_output(struct handle_output *ctx)\r
314     void *senddata;\r
315     int sendlen;\r
317     if (!ctx->busy && bufchain_size(&ctx->queued_data)) {\r
318         bufchain_prefix(&ctx->queued_data, &senddata, &sendlen);\r
319         ctx->buffer = senddata;\r
320         ctx->len = sendlen;\r
321         SetEvent(ctx->ev_from_main);\r
322         ctx->busy = TRUE;\r
323     }\r
326 /* ----------------------------------------------------------------------\r
327  * Unified code handling both input and output threads.\r
328  */\r
330 struct handle {\r
331     int output;\r
332     union {\r
333         struct handle_generic g;\r
334         struct handle_input i;\r
335         struct handle_output o;\r
336     } u;\r
337 };\r
339 static tree234 *handles_by_evtomain;\r
341 static int handle_cmp_evtomain(void *av, void *bv)\r
343     struct handle *a = (struct handle *)av;\r
344     struct handle *b = (struct handle *)bv;\r
346     if ((unsigned)a->u.g.ev_to_main < (unsigned)b->u.g.ev_to_main)\r
347         return -1;\r
348     else if ((unsigned)a->u.g.ev_to_main > (unsigned)b->u.g.ev_to_main)\r
349         return +1;\r
350     else\r
351         return 0;\r
354 static int handle_find_evtomain(void *av, void *bv)\r
356     HANDLE *a = (HANDLE *)av;\r
357     struct handle *b = (struct handle *)bv;\r
359     if ((unsigned)*a < (unsigned)b->u.g.ev_to_main)\r
360         return -1;\r
361     else if ((unsigned)*a > (unsigned)b->u.g.ev_to_main)\r
362         return +1;\r
363     else\r
364         return 0;\r
367 struct handle *handle_input_new(HANDLE handle, handle_inputfn_t gotdata,\r
368                                 void *privdata, int flags)\r
370     struct handle *h = snew(struct handle);\r
371     DWORD in_threadid; /* required for Win9x */\r
373     h->output = FALSE;\r
374     h->u.i.h = handle;\r
375     h->u.i.ev_to_main = CreateEvent(NULL, FALSE, FALSE, NULL);\r
376     h->u.i.ev_from_main = CreateEvent(NULL, FALSE, FALSE, NULL);\r
377     h->u.i.gotdata = gotdata;\r
378     h->u.i.defunct = FALSE;\r
379     h->u.i.moribund = FALSE;\r
380     h->u.i.done = FALSE;\r
381     h->u.i.privdata = privdata;\r
382     h->u.i.flags = flags;\r
384     if (!handles_by_evtomain)\r
385         handles_by_evtomain = newtree234(handle_cmp_evtomain);\r
386     add234(handles_by_evtomain, h);\r
388     CreateThread(NULL, 0, handle_input_threadfunc,\r
389                  &h->u.i, 0, &in_threadid);\r
390     h->u.i.busy = TRUE;\r
392     return h;\r
395 struct handle *handle_output_new(HANDLE handle, handle_outputfn_t sentdata,\r
396                                  void *privdata, int flags)\r
398     struct handle *h = snew(struct handle);\r
399     DWORD out_threadid; /* required for Win9x */\r
401     h->output = TRUE;\r
402     h->u.o.h = handle;\r
403     h->u.o.ev_to_main = CreateEvent(NULL, FALSE, FALSE, NULL);\r
404     h->u.o.ev_from_main = CreateEvent(NULL, FALSE, FALSE, NULL);\r
405     h->u.o.busy = FALSE;\r
406     h->u.o.defunct = FALSE;\r
407     h->u.o.moribund = FALSE;\r
408     h->u.o.done = FALSE;\r
409     h->u.o.privdata = privdata;\r
410     bufchain_init(&h->u.o.queued_data);\r
411     h->u.o.sentdata = sentdata;\r
412     h->u.o.flags = flags;\r
414     if (!handles_by_evtomain)\r
415         handles_by_evtomain = newtree234(handle_cmp_evtomain);\r
416     add234(handles_by_evtomain, h);\r
418     CreateThread(NULL, 0, handle_output_threadfunc,\r
419                  &h->u.o, 0, &out_threadid);\r
421     return h;\r
424 int handle_write(struct handle *h, const void *data, int len)\r
426     assert(h->output);\r
427     bufchain_add(&h->u.o.queued_data, data, len);\r
428     handle_try_output(&h->u.o);\r
429     return bufchain_size(&h->u.o.queued_data);\r
432 HANDLE *handle_get_events(int *nevents)\r
434     HANDLE *ret;\r
435     struct handle *h;\r
436     int i, n, size;\r
438     /*\r
439      * Go through our tree counting the handle objects currently\r
440      * engaged in useful activity.\r
441      */\r
442     ret = NULL;\r
443     n = size = 0;\r
444     if (handles_by_evtomain) {\r
445         for (i = 0; (h = index234(handles_by_evtomain, i)) != NULL; i++) {\r
446             if (h->u.g.busy) {\r
447                 if (n >= size) {\r
448                     size += 32;\r
449                     ret = sresize(ret, size, HANDLE);\r
450                 }\r
451                 ret[n++] = h->u.g.ev_to_main;\r
452             }\r
453         }\r
454     }\r
456     *nevents = n;\r
457     return ret;\r
460 static void handle_destroy(struct handle *h)\r
462     if (h->output)\r
463         bufchain_clear(&h->u.o.queued_data);\r
464     CloseHandle(h->u.g.ev_from_main);\r
465     CloseHandle(h->u.g.ev_to_main);\r
466     del234(handles_by_evtomain, h);\r
467     sfree(h);\r
470 void handle_free(struct handle *h)\r
472     /*\r
473      * If the handle is currently busy, we cannot immediately free\r
474      * it. Instead we must wait until it's finished its current\r
475      * operation, because otherwise the subthread will write to\r
476      * invalid memory after we free its context from under it.\r
477      */\r
478     assert(h && !h->u.g.moribund);\r
479     if (h->u.g.busy) {\r
480         /*\r
481          * Just set the moribund flag, which will be noticed next\r
482          * time an operation completes.\r
483          */\r
484         h->u.g.moribund = TRUE;\r
485     } else if (h->u.g.defunct) {\r
486         /*\r
487          * There isn't even a subthread; we can go straight to\r
488          * handle_destroy.\r
489          */\r
490         handle_destroy(h);\r
491     } else {\r
492         /*\r
493          * The subthread is alive but not busy, so we now signal it\r
494          * to die. Set the moribund flag to indicate that it will\r
495          * want destroying after that.\r
496          */\r
497         h->u.g.moribund = TRUE;\r
498         h->u.g.done = TRUE;\r
499         h->u.g.busy = TRUE;\r
500         SetEvent(h->u.g.ev_from_main);\r
501     }\r
504 void handle_got_event(HANDLE event)\r
506     struct handle *h;\r
508     assert(handles_by_evtomain);\r
509     h = find234(handles_by_evtomain, &event, handle_find_evtomain);\r
510     if (!h) {\r
511         /*\r
512          * This isn't an error condition. If two or more event\r
513          * objects were signalled during the same select operation,\r
514          * and processing of the first caused the second handle to\r
515          * be closed, then it will sometimes happen that we receive\r
516          * an event notification here for a handle which is already\r
517          * deceased. In that situation we simply do nothing.\r
518          */\r
519         return;\r
520     }\r
522     if (h->u.g.moribund) {\r
523         /*\r
524          * A moribund handle is already treated as dead from the\r
525          * external user's point of view, so do nothing with the\r
526          * actual event. Just signal the thread to die if\r
527          * necessary, or destroy the handle if not.\r
528          */\r
529         if (h->u.g.done) {\r
530             handle_destroy(h);\r
531         } else {\r
532             h->u.g.done = TRUE;\r
533             h->u.g.busy = TRUE;\r
534             SetEvent(h->u.g.ev_from_main);\r
535         }\r
536         return;\r
537     }\r
539     if (!h->output) {\r
540         int backlog;\r
542         h->u.i.busy = FALSE;\r
544         /*\r
545          * A signal on an input handle means data has arrived.\r
546          */\r
547         if (h->u.i.len == 0) {\r
548             /*\r
549              * EOF, or (nearly equivalently) read error.\r
550              */\r
551             h->u.i.gotdata(h, NULL, -h->u.i.readerr);\r
552             h->u.i.defunct = TRUE;\r
553         } else {\r
554             backlog = h->u.i.gotdata(h, h->u.i.buffer, h->u.i.len);\r
555             handle_throttle(&h->u.i, backlog);\r
556         }\r
557     } else {\r
558         h->u.o.busy = FALSE;\r
560         /*\r
561          * A signal on an output handle means we have completed a\r
562          * write. Call the callback to indicate that the output\r
563          * buffer size has decreased, or to indicate an error.\r
564          */\r
565         if (h->u.o.writeerr) {\r
566             /*\r
567              * Write error. Send a negative value to the callback,\r
568              * and mark the thread as defunct (because the output\r
569              * thread is terminating by now).\r
570              */\r
571             h->u.o.sentdata(h, -h->u.o.writeerr);\r
572             h->u.o.defunct = TRUE;\r
573         } else {\r
574             bufchain_consume(&h->u.o.queued_data, h->u.o.lenwritten);\r
575             h->u.o.sentdata(h, bufchain_size(&h->u.o.queued_data));\r
576             handle_try_output(&h->u.o);\r
577         }\r
578     }\r
581 void handle_unthrottle(struct handle *h, int backlog)\r
583     assert(!h->output);\r
584     handle_throttle(&h->u.i, backlog);\r
587 int handle_backlog(struct handle *h)\r
589     assert(h->output);\r
590     return bufchain_size(&h->u.o.queued_data);\r
593 void *handle_get_privdata(struct handle *h)\r
595     return h->u.g.privdata;\r