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