Debian Codegraph @

crt/aws-c-io/source/windows/iocp/pipe.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include <aws/io/pipe.h>
7
8 #include <aws/common/task_scheduler.h>
9 #include <aws/io/event_loop.h>
10 #include <aws/io/private/event_loop_impl.h>
11
12 #include <stdbool.h>
13 #include <stdio.h>
14
15 #include <windows.h>
16
17 enum read_end_state {
18 /* Pipe is open. */
19 READ_END_STATE_OPEN,
20
21 /* Pipe is open, user has subscribed, but async monitoring hasn't started yet.
22 * Pipe moves to SUBCSCRIBED state if async monitoring starts successfully
23 * or SUBSCRIBE_ERROR state if it doesn't start successfully.
24 * From any of the SUBSCRIBE* states, the pipe moves to OPEN state if the user unsubscribes. */
25 READ_END_STATE_SUBSCRIBING,
26
27 /* Pipe is open, user has subscribed, and user is receiving events delivered by async monitoring.
28 * Async monitoring is paused once the file is known to be readable.
29 * Async monitoring is resumed once the user reads all available bytes.
30 * Pipe moves to SUBSCRIBE_ERROR state if async monitoring reports an error, or fails to restart.
31 * Pipe move sto OPEN state if user unsubscribes. */
32 READ_END_STATE_SUBSCRIBED,
33
34 /* Pipe is open, use has subscribed, and an error event has been delivered to the user.
35 * No further error events are delivered to the user, and no more async monitoring occurs.*/
36 READ_END_STATE_SUBSCRIBE_ERROR,
37 };
38
39 /* Reasons to launch async monitoring of the read-end's handle */
40 enum monitoring_reason {
41 MONITORING_BECAUSE_SUBSCRIBING = 1,
42 MONITORING_BECAUSE_WAITING_FOR_DATA = 2,
43 MONITORING_BECAUSE_ERROR_SUSPECTED = 4,
44 };
45
46 /* Async operations live in their own allocations.
47 * This allows the pipe to be cleaned up without waiting for all outstanding operations to complete. */
48 struct async_operation {
49 union {
50 struct aws_overlapped overlapped;
51 struct aws_task task;
52 } op;
53
54 struct aws_allocator *alloc;
55 bool is_active;
56 bool is_read_end_cleaned_up;
57 };
58
59 struct read_end_impl {
60 struct aws_allocator *alloc;
61
62 enum read_end_state state;
63
64 struct aws_io_handle handle;
65
66 struct aws_event_loop *event_loop;
67
68 /* Async overlapped operation for monitoring pipe status.
69 * This operation is re-used each time monitoring resumes.
70 * Note that rapidly subscribing/unsubscribing could lead to the monitoring operation from a previous subscribe
71 * still pending while the user is re-subscribing. */
72 struct async_operation *async_monitoring;
73
74 /* Async task operation used to deliver error reports. */
75 struct async_operation *async_error_report;
76
77 aws_pipe_on_readable_fn *on_readable_user_callback;
78 void *on_readable_user_data;
79
80 /* Error code that the error-reporting task will report. */
81 int error_code_to_report;
82
83 /* Reasons to restart monitoring once current async operation completes.
84 * Contains read_end_monitoring_request_t flags.*/
85 uint8_t monitoring_request_reasons;
86 };
87
88 enum write_end_state {
89 WRITE_END_STATE_CLOSING,
90 WRITE_END_STATE_OPEN,
91 };
92
93 /* Data describing an async write request */
94 struct pipe_write_request {
95 struct aws_byte_cursor original_cursor;
96 aws_pipe_on_write_completed_fn *user_callback;
97 void *user_data;
98 struct aws_allocator *alloc;
99 struct aws_overlapped overlapped;
100 struct aws_linked_list_node list_node;
101 bool is_write_end_cleaned_up;
102 };
103
104 struct write_end_impl {
105 struct aws_allocator *alloc;
106 enum write_end_state state;
107 struct aws_io_handle handle;
108 struct aws_event_loop *event_loop;
109
110 /* List of currently active pipe_write_requests */
111 struct aws_linked_list write_list;
112
113 /* Future optimization idea: avoid an allocation on each write by keeping 1 pre-allocated pipe_write_request around
114 * and re-using it whenever possible */
115 };
116
117 enum {
118 PIPE_BUFFER_SIZE = 4096,
119 PIPE_UNIQUE_NAME_MAX_TRIES = 10,
120 };
121
122 static void s_read_end_on_zero_byte_read_completion(
123 struct aws_event_loop *event_loop,
124 struct aws_overlapped *overlapped,
125 int status_code,
126 size_t num_bytes_transferred);
127 static void s_read_end_report_error_task(struct aws_task *task, void *user_data, enum aws_task_status status);
128 static void s_write_end_on_write_completion(
129 struct aws_event_loop *event_loop,
130 struct aws_overlapped *overlapped,
131 int status_code,
132 size_t num_bytes_transferred);
133
134 /* Translate Windows errors into aws_pipe errors */
135 static int s_translate_windows_error(DWORD win_error) {
136 switch (win_error) {
137 case ERROR_BROKEN_PIPE:
138 return AWS_IO_BROKEN_PIPE;
139 case 0xC000014B: /* STATUS_PIPE_BROKEN */
140 return AWS_IO_BROKEN_PIPE;
141 case 0xC0000120: /* STATUS_CANCELLED */
142 return AWS_IO_BROKEN_PIPE;
143 default:
144 return AWS_ERROR_SYS_CALL_FAILURE;
145 }
146 }
147
148 static int s_raise_last_windows_error(void) {
149 DWORD win_error = GetLastError();
150 int aws_error = s_translate_windows_error(win_error);
151 return aws_raise_error(aws_error);
152 }
153
154 AWS_THREAD_LOCAL uint32_t tl_unique_name_counter = 0;
155
156 AWS_IO_API int aws_pipe_get_unique_name(char *dst, size_t dst_size) {
157 /* For local pipes, name should be unique per-machine.
158 * Mix together several sources that should should lead to something unique. */
159
160 DWORD process_id = GetCurrentProcessId();
161
162 DWORD thread_id = GetCurrentThreadId();
163
164 uint32_t counter = tl_unique_name_counter++;
165
166 LARGE_INTEGER timestamp;
167 bool success = QueryPerformanceCounter(&timestamp);
168 AWS_ASSERT(success);
169 (void)success; /* QueryPerformanceCounter() always succeeds on XP and later */
170
171 /* snprintf() returns number of characters (not including '\0') which would have written if dst_size was ignored */
172 int ideal_strlen = snprintf(
173 dst,
174 dst_size,
175 "\\\\.\\pipe\\aws_pipe_%08x_%08x_%08x_%08x%08x",
176 process_id,
177 thread_id,
178 counter,
179 timestamp.HighPart,
180 timestamp.LowPart);
181
182 AWS_ASSERT(ideal_strlen > 0);
183 if (dst_size < (size_t)(ideal_strlen + 1)) {
184 return aws_raise_error(AWS_ERROR_SHORT_BUFFER);
185 }
186
187 return AWS_OP_SUCCESS;
188 }
189
190 int aws_pipe_init(
191 struct aws_pipe_read_end *read_end,
192 struct aws_event_loop *read_end_event_loop,
193 struct aws_pipe_write_end *write_end,
194 struct aws_event_loop *write_end_event_loop,
195 struct aws_allocator *allocator) {
196
197 AWS_ASSERT(read_end);
198 AWS_ASSERT(read_end_event_loop);
199 AWS_ASSERT(write_end);
200 AWS_ASSERT(write_end_event_loop);
201 AWS_ASSERT(allocator);
202
203 AWS_ZERO_STRUCT(*write_end);
204 AWS_ZERO_STRUCT(*read_end);
205
206 struct write_end_impl *write_impl = NULL;
207 struct read_end_impl *read_impl = NULL;
208
209 /* Init write-end */
210 write_impl = aws_mem_calloc(allocator, 1, sizeof(struct write_end_impl));
211 if (!write_impl) {
212 goto clean_up;
213 }
214
215 write_impl->alloc = allocator;
216 write_impl->state = WRITE_END_STATE_OPEN;
217 write_impl->handle.data.handle = INVALID_HANDLE_VALUE;
218 aws_linked_list_init(&write_impl->write_list);
219
220 /* Anonymous pipes don't support overlapped I/O so named pipes are used. Names must be unique system-wide.
221 * We generate random names, but collisions are theoretically possible, so try several times before giving up. */
222 char pipe_name[256];
223 int tries = 0;
224 while (true) {
225 int err = aws_pipe_get_unique_name(pipe_name, sizeof(pipe_name));
226 if (err) {
227 goto clean_up;
228 }
229
230 const DWORD open_mode = PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE;
231
232 const DWORD pipe_mode = PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS;
233
234 write_impl->handle.data.handle = CreateNamedPipeA(
235 pipe_name,
236 open_mode,
237 pipe_mode,
238 1, /*nMaxInstances*/
239 PIPE_BUFFER_SIZE, /*nOutBufferSize*/
240 PIPE_BUFFER_SIZE, /*nInBufferSize*/
241 0, /*nDefaultTimeout: 0 means default*/
242 NULL); /*lpSecurityAttributes: NULL means default */
243
244 if (write_impl->handle.data.handle != INVALID_HANDLE_VALUE) {
245 /* Success, break out of loop */
246 break;
247 }
248
249 if (++tries >= PIPE_UNIQUE_NAME_MAX_TRIES) {
250 s_raise_last_windows_error();
251 goto clean_up;
252 }
253 }
254
255 int err = aws_event_loop_connect_handle_to_io_completion_port(write_end_event_loop, &write_impl->handle);
256 if (err) {
257 goto clean_up;
258 }
259
260 write_impl->event_loop = write_end_event_loop;
261
262 /* Init read-end */
263 read_impl = aws_mem_calloc(allocator, 1, sizeof(struct read_end_impl));
264 if (!read_impl) {
265 goto clean_up;
266 }
267
268 read_impl->alloc = allocator;
269 read_impl->state = READ_END_STATE_OPEN;
270 read_impl->handle.data.handle = INVALID_HANDLE_VALUE;
271
272 read_impl->handle.data.handle = CreateFileA(
273 pipe_name, /*lpFileName*/
274 GENERIC_READ, /*dwDesiredAccess*/
275 0, /*dwShareMode: 0 prevents acess by external processes*/
276 NULL, /*lpSecurityAttributes: NULL prevents inheritance by child processes*/
277 OPEN_EXISTING, /*dwCreationDisposition*/
278 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, /*dwFlagsAndAttributes*/
279 NULL); /*hTemplateFile: ignored when opening existing file*/
280
281 if (read_impl->handle.data.handle == INVALID_HANDLE_VALUE) {
282 s_raise_last_windows_error();
283 goto clean_up;
284 }
285
286 err = aws_event_loop_connect_handle_to_io_completion_port(read_end_event_loop, &read_impl->handle);
287 if (err) {
288 goto clean_up;
289 }
290
291 read_impl->event_loop = read_end_event_loop;
292
293 /* Init the read-end's async operations */
294 read_impl->async_monitoring = aws_mem_calloc(allocator, 1, sizeof(struct async_operation));
295 if (!read_impl->async_monitoring) {
296 goto clean_up;
297 }
298
299 read_impl->async_monitoring->alloc = allocator;
300 aws_overlapped_init(&read_impl->async_monitoring->op.overlapped, s_read_end_on_zero_byte_read_completion, read_end);
301
302 read_impl->async_error_report = aws_mem_calloc(allocator, 1, sizeof(struct async_operation));
303 if (!read_impl->async_error_report) {
304 goto clean_up;
305 }
306
307 read_impl->async_error_report->alloc = allocator;
308 aws_task_init(
309 &read_impl->async_error_report->op.task, s_read_end_report_error_task, read_end, "pipe_read_end_report_error");
310
311 /* Success */
312 write_end->impl_data = write_impl;
313 read_end->impl_data = read_impl;
314 return AWS_OP_SUCCESS;
315
316 clean_up:
317 if (write_impl) {
318 if (write_impl->handle.data.handle != INVALID_HANDLE_VALUE) {
319 CloseHandle(write_impl->handle.data.handle);
320 }
321
322 aws_mem_release(allocator, write_impl);
323 write_impl = NULL;
324 }
325
326 if (read_impl) {
327 if (read_impl->handle.data.handle != INVALID_HANDLE_VALUE) {
328 CloseHandle(read_impl->handle.data.handle);
329 }
330
331 if (read_impl->async_monitoring) {
332 aws_mem_release(allocator, read_impl->async_monitoring);
333 }
334
335 if (read_impl->async_error_report) {
336 aws_mem_release(allocator, read_impl->async_error_report);
337 }
338
339 aws_mem_release(allocator, read_impl);
340 read_impl = NULL;
341 }
342
343 return AWS_OP_ERR;
344 }
345
346 struct aws_event_loop *aws_pipe_get_read_end_event_loop(const struct aws_pipe_read_end *read_end) {
347 struct read_end_impl *read_impl = read_end->impl_data;
348 if (!read_impl) {
349 aws_raise_error(AWS_IO_BROKEN_PIPE);
350 return NULL;
351 }
352
353 return read_impl->event_loop;
354 }
355
356 struct aws_event_loop *aws_pipe_get_write_end_event_loop(const struct aws_pipe_write_end *write_end) {
357 struct write_end_impl *write_impl = write_end->impl_data;
358 if (!write_impl) {
359 aws_raise_error(AWS_IO_BROKEN_PIPE);
360 return NULL;
361 }
362
363 return write_impl->event_loop;
364 }
365
366 int aws_pipe_clean_up_read_end(struct aws_pipe_read_end *read_end) {
367
368 struct read_end_impl *read_impl = read_end->impl_data;
369 if (!read_impl) {
370 return aws_raise_error(AWS_IO_BROKEN_PIPE);
371 }
372
373 if (!aws_event_loop_thread_is_callers_thread(read_impl->event_loop)) {
374 return aws_raise_error(AWS_ERROR_IO_EVENT_LOOP_THREAD_ONLY);
375 }
376
377 CloseHandle(read_impl->handle.data.handle);
378
379 /* If the async operations are inactive they can be deleted now.
380 * Otherwise, inform the operations of the clean-up so they can delete themselves upon completion. */
381 if (!read_impl->async_monitoring->is_active) {
382 aws_mem_release(read_impl->alloc, read_impl->async_monitoring);
383 } else {
384 read_impl->async_monitoring->is_read_end_cleaned_up = true;
385 }
386
387 if (!read_impl->async_error_report->is_active) {
388 aws_mem_release(read_impl->alloc, read_impl->async_error_report);
389 } else {
390 read_impl->async_error_report->is_read_end_cleaned_up = true;
391 }
392
393 aws_mem_release(read_impl->alloc, read_impl);
394 AWS_ZERO_STRUCT(*read_end);
395
396 return AWS_OP_SUCCESS;
397 }
398
399 /* Return whether a user is subscribed to receive read events */
400 static bool s_read_end_is_subscribed(struct aws_pipe_read_end *read_end) {
401 struct read_end_impl *read_impl = read_end->impl_data;
402 switch (read_impl->state) {
403 case READ_END_STATE_SUBSCRIBING:
404 case READ_END_STATE_SUBSCRIBED:
405 case READ_END_STATE_SUBSCRIBE_ERROR:
406 return true;
407 default:
408 return false;
409 }
410 }
411
412 /* Detect events on the pipe by kicking off an async zero-byte-read.
413 * When the pipe becomes readable or an error occurs, the read will
414 * complete and we will report the event. */
415 static void s_read_end_request_async_monitoring(struct aws_pipe_read_end *read_end, int request_reason) {
416 struct read_end_impl *read_impl = read_end->impl_data;
417 AWS_ASSERT(read_impl);
418
419 /* We only do async monitoring while user is subscribed, but not if we've
420 * reported an error and moved into the SUBSCRIBE_ERROR state */
421 bool async_monitoring_allowed =
422 s_read_end_is_subscribed(read_end) && (read_impl->state != READ_END_STATE_SUBSCRIBE_ERROR);
423 if (!async_monitoring_allowed) {
424 return;
425 }
426
427 /* We can only have one monitoring operation active at a time. Save off
428 * the reason for the request. When the current operation completes,
429 * if this reason is still valid, we'll re-launch async monitoring */
430 if (read_impl->async_monitoring->is_active) {
431 read_impl->monitoring_request_reasons |= request_reason;
432 return;
433 }
434
435 AWS_ASSERT(read_impl->error_code_to_report == 0);
436
437 read_impl->monitoring_request_reasons = 0;
438 read_impl->state = READ_END_STATE_SUBSCRIBED;
439
440 /* aws_overlapped must be reset before each use */
441 aws_overlapped_reset(&read_impl->async_monitoring->op.overlapped);
442
443 int fake_buffer;
444 bool success = ReadFile(
445 read_impl->handle.data.handle,
446 &fake_buffer,
447 0, /*nNumberOfBytesToRead*/
448 NULL, /*lpNumberOfBytesRead: NULL for an overlapped operation*/
449 aws_overlapped_to_windows_overlapped(&read_impl->async_monitoring->op.overlapped));
450
451 if (success || (GetLastError() == ERROR_IO_PENDING)) {
452 /* Success launching zero-byte-read, aka async monitoring operation */
453 read_impl->async_monitoring->is_active = true;
454 return;
455 }
456
457 /* User is subscribed for IO events and expects to be notified of errors via the event callback.
458 * We schedule this as a task so the callback doesn't happen before the user expects it.
459 * We also set the state to SUBSCRIBE_ERROR so we don't keep trying to monitor the file. */
460 read_impl->state = READ_END_STATE_SUBSCRIBE_ERROR;
461 read_impl->error_code_to_report = s_translate_windows_error(GetLastError());
462 read_impl->async_error_report->is_active = true;
463 aws_event_loop_schedule_task_now(read_impl->event_loop, &read_impl->async_error_report->op.task);
464 }
465
466 static void s_read_end_report_error_task(struct aws_task *task, void *user_data, enum aws_task_status status) {
467 (void)status; /* Do same work whether or not this is a "cancelled" task */
468
469 struct async_operation *async_op = AWS_CONTAINER_OF(task, struct async_operation, op);
470 AWS_ASSERT(async_op->is_active);
471 async_op->is_active = false;
472
473 /* If the read end has been cleaned up, don't report the error, just free the task's memory. */
474 if (async_op->is_read_end_cleaned_up) {
475 aws_mem_release(async_op->alloc, async_op);
476 return;
477 }
478
479 struct aws_pipe_read_end *read_end = user_data;
480 struct read_end_impl *read_impl = read_end->impl_data;
481 AWS_ASSERT(read_impl);
482
483 /* Only report the error if we're still in the SUBSCRIBE_ERROR state.
484 * If the user unsubscribed since this task was queued, then we'd be in a different state. */
485 if (read_impl->state == READ_END_STATE_SUBSCRIBE_ERROR) {
486 AWS_ASSERT(read_impl->error_code_to_report != 0);
487
488 if (read_impl->on_readable_user_callback) {
489 read_impl->on_readable_user_callback(
490 read_end, read_impl->error_code_to_report, read_impl->on_readable_user_data);
491 }
492 }
493 }
494
495 static void s_read_end_on_zero_byte_read_completion(
496 struct aws_event_loop *event_loop,
497 struct aws_overlapped *overlapped,
498 int status_code,
499 size_t num_bytes_transferred) {
500
501 (void)event_loop;
502 (void)num_bytes_transferred;
503
504 struct async_operation *async_op = AWS_CONTAINER_OF(overlapped, struct async_operation, op);
505
506 /* If the read-end has been cleaned up, simply free the operation's memory and return. */
507 if (async_op->is_read_end_cleaned_up) {
508 aws_mem_release(async_op->alloc, async_op);
509 return;
510 }
511
512 struct aws_pipe_read_end *read_end = overlapped->user_data;
513 struct read_end_impl *read_impl = read_end->impl_data;
514 AWS_ASSERT(read_impl);
515
516 /* Only report events to user when in the SUBSCRIBED state.
517 * If in the SUBSCRIBING state, this completion is from an operation begun during a previous subscription. */
518 if (read_impl->state == READ_END_STATE_SUBSCRIBED) {
519 int readable_error_code;
520
521 if (status_code == 0) {
522 readable_error_code = AWS_ERROR_SUCCESS;
523
524 /* Clear out the "waiting for data" reason to restart zero-byte-read, since we're about to tell the user
525 * that the pipe is readable. If the user consumes all the data, the "waiting for data" reason will get set
526 * again and async-monitoring will be relaunched at the end of this function. */
527 read_impl->monitoring_request_reasons &= ~MONITORING_BECAUSE_WAITING_FOR_DATA;
528
529 } else {
530 readable_error_code = AWS_IO_BROKEN_PIPE;
531
532 /* Move pipe to SUBSCRIBE_ERROR state to prevent further monitoring */
533 read_impl->state = READ_END_STATE_SUBSCRIBE_ERROR;
534 }
535
536 if (read_impl->on_readable_user_callback) {
537 read_impl->on_readable_user_callback(read_end, readable_error_code, read_impl->on_readable_user_data);
538 }
539 }
540
541 /* Note that the user callback might have invoked aws_pipe_clean_up_read_end().
542 * If so, clean up the operation's memory.
543 * Otherwise, relaunch the monitoring operation if there's a reason to do so */
544 AWS_ASSERT(async_op->is_active);
545 async_op->is_active = false;
546
547 if (async_op->is_read_end_cleaned_up) {
548 aws_mem_release(async_op->alloc, async_op);
549 } else if (read_impl->monitoring_request_reasons != 0) {
550 s_read_end_request_async_monitoring(read_end, read_impl->monitoring_request_reasons);
551 }
552 }
553
554 int aws_pipe_subscribe_to_readable_events(
555 struct aws_pipe_read_end *read_end,
556 aws_pipe_on_readable_fn *on_readable,
557 void *user_data) {
558
559 struct read_end_impl *read_impl = read_end->impl_data;
560 if (!read_impl) {
561 return aws_raise_error(AWS_IO_BROKEN_PIPE);
562 }
563
564 if (read_impl->state != READ_END_STATE_OPEN) {
565 /* Return specific error about why user can't subscribe */
566 if (s_read_end_is_subscribed(read_end)) {
567 return aws_raise_error(AWS_ERROR_IO_ALREADY_SUBSCRIBED);
568 }
569
570 AWS_ASSERT(0); /* Unexpected state */
571 return aws_raise_error(AWS_ERROR_UNKNOWN);
572 }
573
574 if (!aws_event_loop_thread_is_callers_thread(read_impl->event_loop)) {
575 return aws_raise_error(AWS_ERROR_IO_EVENT_LOOP_THREAD_ONLY);
576 }
577
578 read_impl->state = READ_END_STATE_SUBSCRIBING;
579 read_impl->on_readable_user_callback = on_readable;
580 read_impl->on_readable_user_data = user_data;
581
582 s_read_end_request_async_monitoring(read_end, MONITORING_BECAUSE_SUBSCRIBING);
583
584 return AWS_OP_SUCCESS;
585 }
586
587 int aws_pipe_unsubscribe_from_readable_events(struct aws_pipe_read_end *read_end) {
588 struct read_end_impl *read_impl = read_end->impl_data;
589 if (!read_impl) {
590 return aws_raise_error(AWS_IO_BROKEN_PIPE);
591 }
592
593 if (!s_read_end_is_subscribed(read_end)) {
594 return aws_raise_error(AWS_ERROR_IO_NOT_SUBSCRIBED);
595 }
596
597 if (!aws_event_loop_thread_is_callers_thread(read_impl->event_loop)) {
598 return aws_raise_error(AWS_ERROR_IO_EVENT_LOOP_THREAD_ONLY);
599 }
600
601 read_impl->state = READ_END_STATE_OPEN;
602 read_impl->on_readable_user_callback = NULL;
603 read_impl->on_readable_user_data = NULL;
604 read_impl->monitoring_request_reasons = 0;
605 read_impl->error_code_to_report = 0;
606
607 /* If there's a chance the zero-byte-read is pending, cancel it.
608 * s_read_end_on_zero_byte_read_completion() will see status code
609 * ERROR_OPERATION_ABORTED, but won't pass the event to the user
610 * because we're not in the SUBSCRIBED state anymore. */
611 if (read_impl->async_monitoring->is_active) {
612 CancelIo(read_impl->handle.data.handle);
613 }
614
615 return AWS_OP_SUCCESS;
616 }
617
618 int aws_pipe_read(struct aws_pipe_read_end *read_end, struct aws_byte_buf *dst_buffer, size_t *amount_read) {
619 AWS_ASSERT(dst_buffer && dst_buffer->buffer);
620
621 struct read_end_impl *read_impl = read_end->impl_data;
622 if (!read_impl) {
623 return aws_raise_error(AWS_IO_BROKEN_PIPE);
624 }
625
626 if (amount_read) {
627 *amount_read = 0;
628 }
629
630 if (!aws_event_loop_thread_is_callers_thread(read_impl->event_loop)) {
631 return aws_raise_error(AWS_ERROR_IO_EVENT_LOOP_THREAD_ONLY);
632 }
633
634 /* Just return success if user requests 0 data */
635 if (dst_buffer->capacity <= dst_buffer->len) {
636 return AWS_OP_SUCCESS;
637 }
638
639 /* ReadFile() will be called in synchronous mode and would block indefinitely if it asked for more bytes than are
640 * currently available. Therefore, peek at the available bytes before performing the actual read. */
641 DWORD bytes_available = 0;
642 bool peek_success = PeekNamedPipe(
643 read_impl->handle.data.handle,
644 NULL, /*lpBuffer: NULL so peek doesn't actually copy data */
645 0, /*nBufferSize*/
646 NULL, /*lpBytesRead*/
647 &bytes_available, /*lpTotalBytesAvail*/
648 NULL); /*lpBytesLeftThisMessage: doesn't apply to byte-type pipes*/
649
650 /* If operation failed. Request async monitoring so user is informed via aws_pipe_on_readable_fn of handle error. */
651 if (!peek_success) {
652 s_read_end_request_async_monitoring(read_end, MONITORING_BECAUSE_ERROR_SUSPECTED);
653 return s_raise_last_windows_error();
654 }
655
656 /* If no data available. Request async monitoring so user is notified when data becomes available. */
657 if (bytes_available == 0) {
658 s_read_end_request_async_monitoring(read_end, MONITORING_BECAUSE_WAITING_FOR_DATA);
659 return aws_raise_error(AWS_IO_READ_WOULD_BLOCK);
660 }
661
662 size_t bytes_to_read = dst_buffer->capacity - dst_buffer->len;
663 if (bytes_to_read > bytes_available) {
664 bytes_to_read = bytes_available;
665 }
666
667 DWORD bytes_read = 0;
668 bool read_success = ReadFile(
669 read_impl->handle.data.handle,
670 dst_buffer->buffer + dst_buffer->len, /*lpBuffer*/
671 (DWORD)bytes_to_read, /*nNumberOfBytesToRead*/
672 &bytes_read, /*lpNumberOfBytesRead*/
673 NULL); /*lpOverlapped: NULL so read is synchronous*/
674
675 /* Operation failed. Request async monitoring so user is informed via aws_pipe_on_readable_fn of handle error. */
676 if (!read_success) {
677 s_read_end_request_async_monitoring(read_end, MONITORING_BECAUSE_ERROR_SUSPECTED);
678 return s_raise_last_windows_error();
679 }
680
681 /* Success */
682 dst_buffer->len += bytes_read;
683
684 if (amount_read) {
685 *amount_read = bytes_read;
686 }
687
688 if (bytes_read < bytes_to_read) {
689 /* If we weren't able to read as many bytes as the user requested, that's ok.
690 * Request async monitoring so we can alert the user when more data arrives */
691 s_read_end_request_async_monitoring(read_end, MONITORING_BECAUSE_WAITING_FOR_DATA);
692 }
693
694 return AWS_OP_SUCCESS;
695 }
696
697 int aws_pipe_clean_up_write_end(struct aws_pipe_write_end *write_end) {
698
699 struct write_end_impl *write_impl = write_end->impl_data;
700 if (!write_impl) {
701 return aws_raise_error(AWS_IO_BROKEN_PIPE);
702 }
703
704 if (!aws_event_loop_thread_is_callers_thread(write_impl->event_loop)) {
705 return aws_raise_error(AWS_ERROR_IO_EVENT_LOOP_THREAD_ONLY);
706 }
707
708 CloseHandle(write_impl->handle.data.handle);
709
710 /* Inform outstanding writes about the clean up. */
711 while (!aws_linked_list_empty(&write_impl->write_list)) {
712 struct aws_linked_list_node *node = aws_linked_list_pop_front(&write_impl->write_list);
713 struct pipe_write_request *write_req = AWS_CONTAINER_OF(node, struct pipe_write_request, list_node);
714 write_req->is_write_end_cleaned_up = true;
715 }
716
717 aws_mem_release(write_impl->alloc, write_impl);
718 AWS_ZERO_STRUCT(*write_end);
719
720 return AWS_OP_SUCCESS;
721 }
722
723 int aws_pipe_write(
724 struct aws_pipe_write_end *write_end,
725 struct aws_byte_cursor src_buffer,
726 aws_pipe_on_write_completed_fn *on_completed,
727 void *user_data) {
728
729 struct write_end_impl *write_impl = write_end->impl_data;
730 if (!write_impl) {
731 return aws_raise_error(AWS_IO_BROKEN_PIPE);
732 }
733
734 if (!aws_event_loop_thread_is_callers_thread(write_impl->event_loop)) {
735 return aws_raise_error(AWS_ERROR_IO_EVENT_LOOP_THREAD_ONLY);
736 }
737
738 if (src_buffer.len > MAXDWORD) {
739 return aws_raise_error(AWS_ERROR_INVALID_BUFFER_SIZE);
740 }
741 DWORD num_bytes_to_write = (DWORD)src_buffer.len;
742
743 struct pipe_write_request *write = aws_mem_acquire(write_impl->alloc, sizeof(struct pipe_write_request));
744 if (!write) {
745 return AWS_OP_ERR;
746 }
747
748 AWS_ZERO_STRUCT(*write);
749 write->original_cursor = src_buffer;
750 write->user_callback = on_completed;
751 write->user_data = user_data;
752 write->alloc = write_impl->alloc;
753 aws_overlapped_init(&write->overlapped, s_write_end_on_write_completion, write_end);
754
755 bool write_success = WriteFile(
756 write_impl->handle.data.handle, /*hFile*/
757 src_buffer.ptr, /*lpBuffer*/
758 num_bytes_to_write, /*nNumberOfBytesToWrite*/
759 NULL, /*lpNumberOfBytesWritten*/
760 aws_overlapped_to_windows_overlapped(&write->overlapped)); /*lpOverlapped*/
761
762 /* Overlapped WriteFile() calls may succeed immediately, or they may queue the work. In either of these cases, IOCP
763 * on the event-loop will alert us when the operation completes and we'll invoke user callbacks then. */
764 if (!write_success && GetLastError() != ERROR_IO_PENDING) {
765 aws_mem_release(write_impl->alloc, write);
766 return s_raise_last_windows_error();
767 }
768
769 aws_linked_list_push_back(&write_impl->write_list, &write->list_node);
770 return AWS_OP_SUCCESS;
771 }
772
773 void s_write_end_on_write_completion(
774 struct aws_event_loop *event_loop,
775 struct aws_overlapped *overlapped,
776 int status_code,
777 size_t num_bytes_transferred) {
778
779 (void)event_loop;
780 (void)num_bytes_transferred;
781
782 struct pipe_write_request *write_request = AWS_CONTAINER_OF(overlapped, struct pipe_write_request, overlapped);
783 struct aws_pipe_write_end *write_end = write_request->is_write_end_cleaned_up ? NULL : overlapped->user_data;
784
785 AWS_ASSERT((num_bytes_transferred == write_request->original_cursor.len) || status_code);
786
787 struct aws_byte_cursor original_cursor = write_request->original_cursor;
788 aws_pipe_on_write_completed_fn *user_callback = write_request->user_callback;
789 void *user_data = write_request->user_data;
790
791 /* Clean up write-request.
792 * Note that write-end might have been cleaned up before this executes. */
793 if (!write_request->is_write_end_cleaned_up) {
794 aws_linked_list_remove(&write_request->list_node);
795 }
796
797 aws_mem_release(write_request->alloc, write_request);
798
799 /* Report outcome to user */
800 if (user_callback) {
801
802 int error_code = AWS_ERROR_SUCCESS;
803 if (status_code != 0) {
804 error_code = s_translate_windows_error(status_code);
805 }
806
807 /* Note that user may choose to clean up write-end in this callback */
808 user_callback(write_end, error_code, original_cursor, user_data);
809 }
810 }