]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winhandl.c
Add support for Windows named pipes.
[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 typedef enum { INPUT, OUTPUT, FOREIGN } HandleType;
69
70 /* ----------------------------------------------------------------------
71  * Input threads.
72  */
73
74 /*
75  * Data required by an input thread.
76  */
77 struct handle_input {
78     /*
79      * Copy of the handle_generic structure.
80      */
81     HANDLE h;                          /* the handle itself */
82     HANDLE ev_to_main;                 /* event used to signal main thread */
83     HANDLE ev_from_main;               /* event used to signal back to us */
84     int moribund;                      /* are we going to kill this soon? */
85     int done;                          /* request subthread to terminate */
86     int defunct;                       /* has the subthread already gone? */
87     int busy;                          /* operation currently in progress? */
88     void *privdata;                    /* for client to remember who they are */
89
90     /*
91      * Data set at initialisation and then read-only.
92      */
93     int flags;
94
95     /*
96      * Data set by the input thread before signalling ev_to_main,
97      * and read by the main thread after receiving that signal.
98      */
99     char buffer[4096];                 /* the data read from the handle */
100     DWORD len;                         /* how much data that was */
101     int readerr;                       /* lets us know about read errors */
102
103     /*
104      * Callback function called by this module when data arrives on
105      * an input handle.
106      */
107     handle_inputfn_t gotdata;
108 };
109
110 /*
111  * The actual thread procedure for an input thread.
112  */
113 static DWORD WINAPI handle_input_threadfunc(void *param)
114 {
115     struct handle_input *ctx = (struct handle_input *) param;
116     OVERLAPPED ovl, *povl;
117     HANDLE oev;
118     int readret, readlen;
119
120     if (ctx->flags & HANDLE_FLAG_OVERLAPPED) {
121         povl = &ovl;
122         oev = CreateEvent(NULL, TRUE, FALSE, NULL);
123     } else {
124         povl = NULL;
125     }
126
127     if (ctx->flags & HANDLE_FLAG_UNITBUFFER)
128         readlen = 1;
129     else
130         readlen = sizeof(ctx->buffer);
131
132     while (1) {
133         if (povl) {
134             memset(povl, 0, sizeof(OVERLAPPED));
135             povl->hEvent = oev;
136         }
137         readret = ReadFile(ctx->h, ctx->buffer,readlen, &ctx->len, povl);
138         if (!readret)
139             ctx->readerr = GetLastError();
140         else
141             ctx->readerr = 0;
142         if (povl && !readret && ctx->readerr == ERROR_IO_PENDING) {
143             WaitForSingleObject(povl->hEvent, INFINITE);
144             readret = GetOverlappedResult(ctx->h, povl, &ctx->len, FALSE);
145             if (!readret)
146                 ctx->readerr = GetLastError();
147             else
148                 ctx->readerr = 0;
149         }
150
151         if (!readret) {
152             /*
153              * Windows apparently sends ERROR_BROKEN_PIPE when a
154              * pipe we're reading from is closed normally from the
155              * writing end. This is ludicrous; if that situation
156              * isn't a natural EOF, _nothing_ is. So if we get that
157              * particular error, we pretend it's EOF.
158              */
159             if (ctx->readerr == ERROR_BROKEN_PIPE)
160                 ctx->readerr = 0;
161             ctx->len = 0;
162         }
163
164         if (readret && ctx->len == 0 &&
165             (ctx->flags & HANDLE_FLAG_IGNOREEOF))
166             continue;
167
168         SetEvent(ctx->ev_to_main);
169
170         if (!ctx->len)
171             break;
172
173         WaitForSingleObject(ctx->ev_from_main, INFINITE);
174         if (ctx->done)
175             break;                     /* main thread told us to shut down */
176     }
177
178     if (povl)
179         CloseHandle(oev);
180
181     return 0;
182 }
183
184 /*
185  * This is called after a succcessful read, or from the
186  * `unthrottle' function. It decides whether or not to begin a new
187  * read operation.
188  */
189 static void handle_throttle(struct handle_input *ctx, int backlog)
190 {
191     if (ctx->defunct)
192         return;
193
194     /*
195      * If there's a read operation already in progress, do nothing:
196      * when that completes, we'll come back here and be in a
197      * position to make a better decision.
198      */
199     if (ctx->busy)
200         return;
201
202     /*
203      * Otherwise, we must decide whether to start a new read based
204      * on the size of the backlog.
205      */
206     if (backlog < MAX_BACKLOG) {
207         SetEvent(ctx->ev_from_main);
208         ctx->busy = TRUE;
209     }
210 }
211
212 /* ----------------------------------------------------------------------
213  * Output threads.
214  */
215
216 /*
217  * Data required by an output thread.
218  */
219 struct handle_output {
220     /*
221      * Copy of the handle_generic structure.
222      */
223     HANDLE h;                          /* the handle itself */
224     HANDLE ev_to_main;                 /* event used to signal main thread */
225     HANDLE ev_from_main;               /* event used to signal back to us */
226     int moribund;                      /* are we going to kill this soon? */
227     int done;                          /* request subthread to terminate */
228     int defunct;                       /* has the subthread already gone? */
229     int busy;                          /* operation currently in progress? */
230     void *privdata;                    /* for client to remember who they are */
231
232     /*
233      * Data set at initialisation and then read-only.
234      */
235     int flags;
236
237     /*
238      * Data set by the main thread before signalling ev_from_main,
239      * and read by the input thread after receiving that signal.
240      */
241     char *buffer;                      /* the data to write */
242     DWORD len;                         /* how much data there is */
243
244     /*
245      * Data set by the input thread before signalling ev_to_main,
246      * and read by the main thread after receiving that signal.
247      */
248     DWORD lenwritten;                  /* how much data we actually wrote */
249     int writeerr;                      /* return value from WriteFile */
250
251     /*
252      * Data only ever read or written by the main thread.
253      */
254     bufchain queued_data;              /* data still waiting to be written */
255     enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
256
257     /*
258      * Callback function called when the backlog in the bufchain
259      * drops.
260      */
261     handle_outputfn_t sentdata;
262 };
263
264 static DWORD WINAPI handle_output_threadfunc(void *param)
265 {
266     struct handle_output *ctx = (struct handle_output *) param;
267     OVERLAPPED ovl, *povl;
268     HANDLE oev;
269     int writeret;
270
271     if (ctx->flags & HANDLE_FLAG_OVERLAPPED) {
272         povl = &ovl;
273         oev = CreateEvent(NULL, TRUE, FALSE, NULL);
274     } else {
275         povl = NULL;
276     }
277
278     while (1) {
279         WaitForSingleObject(ctx->ev_from_main, INFINITE);
280         if (ctx->done) {
281             SetEvent(ctx->ev_to_main);
282             break;
283         }
284         if (povl) {
285             memset(povl, 0, sizeof(OVERLAPPED));
286             povl->hEvent = oev;
287         }
288
289         writeret = WriteFile(ctx->h, ctx->buffer, ctx->len,
290                              &ctx->lenwritten, povl);
291         if (!writeret)
292             ctx->writeerr = GetLastError();
293         else
294             ctx->writeerr = 0;
295         if (povl && !writeret && GetLastError() == ERROR_IO_PENDING) {
296             writeret = GetOverlappedResult(ctx->h, povl,
297                                            &ctx->lenwritten, TRUE);
298             if (!writeret)
299                 ctx->writeerr = GetLastError();
300             else
301                 ctx->writeerr = 0;
302         }
303
304         SetEvent(ctx->ev_to_main);
305         if (!writeret)
306             break;
307     }
308
309     if (povl)
310         CloseHandle(oev);
311
312     return 0;
313 }
314
315 static void handle_try_output(struct handle_output *ctx)
316 {
317     void *senddata;
318     int sendlen;
319
320     if (!ctx->busy && bufchain_size(&ctx->queued_data)) {
321         bufchain_prefix(&ctx->queued_data, &senddata, &sendlen);
322         ctx->buffer = senddata;
323         ctx->len = sendlen;
324         SetEvent(ctx->ev_from_main);
325         ctx->busy = TRUE;
326     } else if (!ctx->busy && bufchain_size(&ctx->queued_data) == 0 &&
327                ctx->outgoingeof == EOF_PENDING) {
328         CloseHandle(ctx->h);
329         ctx->h = INVALID_HANDLE_VALUE;
330         ctx->outgoingeof = EOF_SENT;
331     }
332 }
333
334 /* ----------------------------------------------------------------------
335  * 'Foreign events'. These are handle structures which just contain a
336  * single event object passed to us by another module such as
337  * winnps.c, so that they can make use of our handle_get_events /
338  * handle_got_event mechanism for communicating with application main
339  * loops.
340  */
341 struct handle_foreign {
342     /*
343      * Copy of the handle_generic structure.
344      */
345     HANDLE h;                          /* the handle itself */
346     HANDLE ev_to_main;                 /* event used to signal main thread */
347     HANDLE ev_from_main;               /* event used to signal back to us */
348     int moribund;                      /* are we going to kill this soon? */
349     int done;                          /* request subthread to terminate */
350     int defunct;                       /* has the subthread already gone? */
351     int busy;                          /* operation currently in progress? */
352     void *privdata;                    /* for client to remember who they are */
353
354     /*
355      * Our own data, just consisting of knowledge of who to call back.
356      */
357     void (*callback)(void *);
358     void *ctx;
359 };
360
361 /* ----------------------------------------------------------------------
362  * Unified code handling both input and output threads.
363  */
364
365 struct handle {
366     HandleType type;
367     union {
368         struct handle_generic g;
369         struct handle_input i;
370         struct handle_output o;
371         struct handle_foreign f;
372     } u;
373 };
374
375 static tree234 *handles_by_evtomain;
376
377 static int handle_cmp_evtomain(void *av, void *bv)
378 {
379     struct handle *a = (struct handle *)av;
380     struct handle *b = (struct handle *)bv;
381
382     if ((unsigned)a->u.g.ev_to_main < (unsigned)b->u.g.ev_to_main)
383         return -1;
384     else if ((unsigned)a->u.g.ev_to_main > (unsigned)b->u.g.ev_to_main)
385         return +1;
386     else
387         return 0;
388 }
389
390 static int handle_find_evtomain(void *av, void *bv)
391 {
392     HANDLE *a = (HANDLE *)av;
393     struct handle *b = (struct handle *)bv;
394
395     if ((unsigned)*a < (unsigned)b->u.g.ev_to_main)
396         return -1;
397     else if ((unsigned)*a > (unsigned)b->u.g.ev_to_main)
398         return +1;
399     else
400         return 0;
401 }
402
403 struct handle *handle_input_new(HANDLE handle, handle_inputfn_t gotdata,
404                                 void *privdata, int flags)
405 {
406     struct handle *h = snew(struct handle);
407     DWORD in_threadid; /* required for Win9x */
408
409     h->type = INPUT;
410     h->u.i.h = handle;
411     h->u.i.ev_to_main = CreateEvent(NULL, FALSE, FALSE, NULL);
412     h->u.i.ev_from_main = CreateEvent(NULL, FALSE, FALSE, NULL);
413     h->u.i.gotdata = gotdata;
414     h->u.i.defunct = FALSE;
415     h->u.i.moribund = FALSE;
416     h->u.i.done = FALSE;
417     h->u.i.privdata = privdata;
418     h->u.i.flags = flags;
419
420     if (!handles_by_evtomain)
421         handles_by_evtomain = newtree234(handle_cmp_evtomain);
422     add234(handles_by_evtomain, h);
423
424     CreateThread(NULL, 0, handle_input_threadfunc,
425                  &h->u.i, 0, &in_threadid);
426     h->u.i.busy = TRUE;
427
428     return h;
429 }
430
431 struct handle *handle_output_new(HANDLE handle, handle_outputfn_t sentdata,
432                                  void *privdata, int flags)
433 {
434     struct handle *h = snew(struct handle);
435     DWORD out_threadid; /* required for Win9x */
436
437     h->type = OUTPUT;
438     h->u.o.h = handle;
439     h->u.o.ev_to_main = CreateEvent(NULL, FALSE, FALSE, NULL);
440     h->u.o.ev_from_main = CreateEvent(NULL, FALSE, FALSE, NULL);
441     h->u.o.busy = FALSE;
442     h->u.o.defunct = FALSE;
443     h->u.o.moribund = FALSE;
444     h->u.o.done = FALSE;
445     h->u.o.privdata = privdata;
446     bufchain_init(&h->u.o.queued_data);
447     h->u.o.outgoingeof = EOF_NO;
448     h->u.o.sentdata = sentdata;
449     h->u.o.flags = flags;
450
451     if (!handles_by_evtomain)
452         handles_by_evtomain = newtree234(handle_cmp_evtomain);
453     add234(handles_by_evtomain, h);
454
455     CreateThread(NULL, 0, handle_output_threadfunc,
456                  &h->u.o, 0, &out_threadid);
457
458     return h;
459 }
460
461 struct handle *handle_add_foreign_event(HANDLE event,
462                                         void (*callback)(void *), void *ctx)
463 {
464     struct handle *h = snew(struct handle);
465
466     h->type = FOREIGN;
467     h->u.f.h = INVALID_HANDLE_VALUE;
468     h->u.f.ev_to_main = event;
469     h->u.f.ev_from_main = INVALID_HANDLE_VALUE;
470     h->u.f.defunct = TRUE;  /* we have no thread in the first place */
471     h->u.f.moribund = FALSE;
472     h->u.f.done = FALSE;
473     h->u.f.privdata = NULL;
474     h->u.f.callback = callback;
475     h->u.f.ctx = ctx;
476     h->u.f.busy = TRUE;
477
478     if (!handles_by_evtomain)
479         handles_by_evtomain = newtree234(handle_cmp_evtomain);
480     add234(handles_by_evtomain, h);
481
482     return h;
483 }
484
485 int handle_write(struct handle *h, const void *data, int len)
486 {
487     assert(h->type == OUTPUT);
488     assert(h->u.o.outgoingeof == EOF_NO);
489     bufchain_add(&h->u.o.queued_data, data, len);
490     handle_try_output(&h->u.o);
491     return bufchain_size(&h->u.o.queued_data);
492 }
493
494 void handle_write_eof(struct handle *h)
495 {
496     /*
497      * This function is called when we want to proactively send an
498      * end-of-file notification on the handle. We can only do this by
499      * actually closing the handle - so never call this on a
500      * bidirectional handle if we're still interested in its incoming
501      * direction!
502      */
503     assert(h->type == OUTPUT);
504     if (!h->u.o.outgoingeof == EOF_NO) {
505         h->u.o.outgoingeof = EOF_PENDING;
506         handle_try_output(&h->u.o);
507     }
508 }
509
510 HANDLE *handle_get_events(int *nevents)
511 {
512     HANDLE *ret;
513     struct handle *h;
514     int i, n, size;
515
516     /*
517      * Go through our tree counting the handle objects currently
518      * engaged in useful activity.
519      */
520     ret = NULL;
521     n = size = 0;
522     if (handles_by_evtomain) {
523         for (i = 0; (h = index234(handles_by_evtomain, i)) != NULL; i++) {
524             if (h->u.g.busy) {
525                 if (n >= size) {
526                     size += 32;
527                     ret = sresize(ret, size, HANDLE);
528                 }
529                 ret[n++] = h->u.g.ev_to_main;
530             }
531         }
532     }
533
534     *nevents = n;
535     return ret;
536 }
537
538 static void handle_destroy(struct handle *h)
539 {
540     if (h->type == OUTPUT)
541         bufchain_clear(&h->u.o.queued_data);
542     CloseHandle(h->u.g.ev_from_main);
543     CloseHandle(h->u.g.ev_to_main);
544     del234(handles_by_evtomain, h);
545     sfree(h);
546 }
547
548 void handle_free(struct handle *h)
549 {
550     /*
551      * If the handle is currently busy, we cannot immediately free
552      * it. Instead we must wait until it's finished its current
553      * operation, because otherwise the subthread will write to
554      * invalid memory after we free its context from under it.
555      */
556     assert(h && !h->u.g.moribund);
557     if (h->u.g.busy) {
558         /*
559          * Just set the moribund flag, which will be noticed next
560          * time an operation completes.
561          */
562         h->u.g.moribund = TRUE;
563     } else if (h->u.g.defunct) {
564         /*
565          * There isn't even a subthread; we can go straight to
566          * handle_destroy.
567          */
568         handle_destroy(h);
569     } else {
570         /*
571          * The subthread is alive but not busy, so we now signal it
572          * to die. Set the moribund flag to indicate that it will
573          * want destroying after that.
574          */
575         h->u.g.moribund = TRUE;
576         h->u.g.done = TRUE;
577         h->u.g.busy = TRUE;
578         SetEvent(h->u.g.ev_from_main);
579     }
580 }
581
582 void handle_got_event(HANDLE event)
583 {
584     struct handle *h;
585
586     assert(handles_by_evtomain);
587     h = find234(handles_by_evtomain, &event, handle_find_evtomain);
588     if (!h) {
589         /*
590          * This isn't an error condition. If two or more event
591          * objects were signalled during the same select operation,
592          * and processing of the first caused the second handle to
593          * be closed, then it will sometimes happen that we receive
594          * an event notification here for a handle which is already
595          * deceased. In that situation we simply do nothing.
596          */
597         return;
598     }
599
600     if (h->u.g.moribund) {
601         /*
602          * A moribund handle is already treated as dead from the
603          * external user's point of view, so do nothing with the
604          * actual event. Just signal the thread to die if
605          * necessary, or destroy the handle if not.
606          */
607         if (h->u.g.done) {
608             handle_destroy(h);
609         } else {
610             h->u.g.done = TRUE;
611             h->u.g.busy = TRUE;
612             SetEvent(h->u.g.ev_from_main);
613         }
614         return;
615     }
616
617     switch (h->type) {
618         int backlog;
619
620       case INPUT:
621         h->u.i.busy = FALSE;
622
623         /*
624          * A signal on an input handle means data has arrived.
625          */
626         if (h->u.i.len == 0) {
627             /*
628              * EOF, or (nearly equivalently) read error.
629              */
630             h->u.i.gotdata(h, NULL, -h->u.i.readerr);
631             h->u.i.defunct = TRUE;
632         } else {
633             backlog = h->u.i.gotdata(h, h->u.i.buffer, h->u.i.len);
634             handle_throttle(&h->u.i, backlog);
635         }
636         break;
637
638       case OUTPUT:
639         h->u.o.busy = FALSE;
640
641         /*
642          * A signal on an output handle means we have completed a
643          * write. Call the callback to indicate that the output
644          * buffer size has decreased, or to indicate an error.
645          */
646         if (h->u.o.writeerr) {
647             /*
648              * Write error. Send a negative value to the callback,
649              * and mark the thread as defunct (because the output
650              * thread is terminating by now).
651              */
652             h->u.o.sentdata(h, -h->u.o.writeerr);
653             h->u.o.defunct = TRUE;
654         } else {
655             bufchain_consume(&h->u.o.queued_data, h->u.o.lenwritten);
656             h->u.o.sentdata(h, bufchain_size(&h->u.o.queued_data));
657             handle_try_output(&h->u.o);
658         }
659         break;
660
661       case FOREIGN:
662         /* Just call the callback. */
663         h->u.f.callback(h->u.f.ctx);
664         break;
665     }
666 }
667
668 void handle_unthrottle(struct handle *h, int backlog)
669 {
670     assert(h->type == INPUT);
671     handle_throttle(&h->u.i, backlog);
672 }
673
674 int handle_backlog(struct handle *h)
675 {
676     assert(h->type == OUTPUT);
677     return bufchain_size(&h->u.o.queued_data);
678 }
679
680 void *handle_get_privdata(struct handle *h)
681 {
682     return h->u.g.privdata;
683 }