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