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