Debian Codegraph @

c/src/proactor/win_iocp.cpp

raw
1 /*
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20 */
21
22 #include <proton/condition.h>
23 #include <proton/connection_driver.h>
24 #include <proton/engine.h>
25 #include <proton/message.h>
26 #include <proton/netaddr.h>
27 #include <proton/object.h>
28 #include <proton/proactor.h>
29 #include <proton/transport.h>
30 #include <proton/listener.h>
31 #include <proton/proactor.h>
32 #include <proton/raw_connection.h>
33
34 #include <assert.h>
35 #include <stddef.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39
40 #include <iostream>
41 #include <list>
42 #include <queue>
43 #include <sstream>
44
45 #include <winsock2.h>
46 #include <mswsock.h>
47 #include <ws2tcpip.h>
48
49 #include "netaddr-internal.h" /* Include after socket/inet headers */
50 #include "core/logger_private.h"
51
52 /*
53 * Proactor for Windows using IO completion ports.
54 *
55 * There is no specific threading code other than locking and indirect (and
56 * brief) calls to the default threadpool via timerqueue timers.
57 *
58 * The IOCP system remembers what threads have called pn_proactor_wait and
59 * assumes they are doing proactor work until they call wait again. Using a
60 * dedicated threadpool to drive the proactor, as in the examples, is
61 * recommended. The use of other long-lived threads to occasionally drive the
62 * proactor will hurt the completion port scheduler and cause fewer threads to
63 * run.
64 *
65 * Each proactor connection maintains its own queue of pending completions and
66 * its work is serialized on that. The proactor listener runs parallel where
67 * possible, but its event batch is serialized.
68 */
69
70 // TODO: make all code C++ or all C90-ish
71 // change INACTIVE to be from begin_close instead of zombie reap, to be more like Posix
72 // make the global write lock window much smaller
73 // 2 exclusive write buffers per connection
74 // make the zombie processing thread safe
75 // configurable completion port concurrency
76 // proton objects and ref counting: just say no.
77
78
79
80 // From selector.h
81 #define PN_READABLE (1)
82 #define PN_WRITABLE (2)
83 #define PN_EXPIRED (4)
84 #define PN_ERROR (8)
85
86 typedef SOCKET pn_socket_t;
87
88
89 namespace pn_experimental {
90 // Code borrowed from old messenger/reactor io.c iocp.c write_pipeline.c select.c
91 // Mostly unchanged except fro some thread safety (i.e. dropping the old descriptor map)
92
93 typedef struct pni_acceptor_t pni_acceptor_t;
94 typedef struct write_result_t write_result_t;
95 typedef struct read_result_t read_result_t;
96 typedef struct write_pipeline_t write_pipeline_t;
97 typedef struct iocpdesc_t iocpdesc_t;
98 typedef struct iocp_t iocp_t;
99
100
101 // One per completion port.
102
103 struct iocp_t {
104 HANDLE completion_port;
105 pn_list_t *zombie_list;
106 unsigned shared_pool_size;
107 char *shared_pool_memory;
108 write_result_t **shared_results;
109 write_result_t **available_results;
110 size_t shared_available_count;
111 size_t writer_count;
112 int loopback_bufsize;
113 bool iocp_trace;
114 };
115
116 // One for each socket.
117 // It should remain ref counted in the
118 // zombie_list until ops_in_progress == 0 or the completion port is closed.
119
120 struct iocpdesc_t {
121 pn_socket_t socket;
122 iocp_t *iocp;
123 void *active_completer;
124 pni_acceptor_t *acceptor;
125 pn_error_t *error;
126 int ops_in_progress;
127 bool read_in_progress;
128 write_pipeline_t *pipeline;
129 read_result_t *read_result;
130 bool bound; // associated with the completion port
131 bool closing; // close called by application
132 bool read_closed; // EOF or read error
133 bool write_closed; // shutdown sent or write error
134 bool poll_error; // flag posix-like POLLERR/POLLHUP/POLLNVAL
135 bool is_mp; // Special multi thread care required
136 bool write_blocked;
137 int events;
138 pn_timestamp_t reap_time;
139 };
140
141
142 // Max number of overlapped accepts per listener. TODO: configurable.
143 #define IOCP_MAX_ACCEPTS 4
144
145 // AcceptEx squishes the local and remote addresses and optional data
146 // all together when accepting the connection. Reserve enough for
147 // IPv6 addresses, even if the socket is IPv4. The 16 bytes padding
148 // per address is required by AcceptEx.
149 #define IOCP_SOCKADDRMAXLEN (sizeof(sockaddr_in6) + 16)
150 #define IOCP_SOCKADDRBUFLEN (2 * IOCP_SOCKADDRMAXLEN)
151
152 typedef enum { IOCP_ACCEPT, IOCP_CONNECT, IOCP_READ, IOCP_WRITE } iocp_type_t;
153
154 typedef struct {
155 OVERLAPPED overlapped;
156 iocp_type_t type;
157 iocpdesc_t *iocpd;
158 HRESULT status;
159 DWORD num_transferred;
160 } iocp_result_t;
161
162 // Completion keys to distinguish IO from some other user port completions
163 enum {
164 proactor_io = 0,
165 proactor_wake_key,
166 psocket_wakeup_key,
167 recycle_accept_key,
168 };
169
170 struct read_result_t {
171 iocp_result_t base;
172 size_t drain_count;
173 char unused_buf[1];
174 };
175
176 struct write_result_t {
177 iocp_result_t base;
178 size_t requested;
179 bool in_use;
180 pn_bytes_t buffer;
181 };
182
183 typedef struct {
184 iocp_result_t base;
185 char address_buffer[IOCP_SOCKADDRBUFLEN];
186 struct addrinfo *addrinfo;
187 } connect_result_t;
188
189 typedef struct {
190 iocp_result_t base;
191 iocpdesc_t *new_sock;
192 char address_buffer[IOCP_SOCKADDRBUFLEN];
193 DWORD unused;
194 } accept_result_t;
195
196
197 void complete_connect(connect_result_t *result, HRESULT status);
198 void complete_write(write_result_t *result, DWORD xfer_count, HRESULT status);
199 void complete_read(read_result_t *result, DWORD xfer_count, HRESULT status);
200 void start_reading(iocpdesc_t *iocpd);
201 void begin_accept(pni_acceptor_t *acceptor, accept_result_t *result);
202 void reset_accept_result(accept_result_t *result);
203 iocpdesc_t *create_same_type_socket(iocpdesc_t *iocpd);
204 void pni_iocp_reap_check(iocpdesc_t *iocpd);
205 connect_result_t *connect_result(iocpdesc_t *iocpd, struct addrinfo *addr);
206 iocpdesc_t *pni_iocpdesc_create(iocp_t *, pn_socket_t s);
207 iocpdesc_t *pni_deadline_desc(iocp_t *);
208 void pni_iocpdesc_start(iocpdesc_t *iocpd);
209 void pni_iocp_drain_completions(iocp_t *);
210 int pni_iocp_wait_one(iocp_t *, int timeout, pn_error_t *);
211 void pni_iocp_start_accepting(iocpdesc_t *iocpd);
212 pn_socket_t pni_iocp_end_accept(iocpdesc_t *ld, sockaddr *addr, socklen_t *addrlen, bool *would_block, pn_error_t *error);
213 pn_socket_t pni_iocp_begin_connect(iocp_t *, pn_socket_t sock, struct addrinfo *addr, pn_error_t *error);
214 ssize_t pni_iocp_begin_write(iocpdesc_t *, const void *, size_t, bool *, pn_error_t *);
215 ssize_t pni_iocp_recv(iocpdesc_t *iocpd, void *buf, size_t size, bool *would_block, pn_error_t *error);
216 void pni_iocp_begin_close(iocpdesc_t *iocpd);
217 iocp_t *pni_iocp();
218
219 void pni_events_update(iocpdesc_t *iocpd, int events);
220 write_result_t *pni_write_result(iocpdesc_t *iocpd, const char *buf, size_t buflen);
221 void pni_zombie_check(iocp_t *, pn_timestamp_t);
222 pn_timestamp_t pni_zombie_deadline(iocp_t *);
223
224 int pni_win32_error(pn_error_t *error, const char *msg, HRESULT code);
225 }
226
227 // ======================================================================
228 // Write pipeline.
229 // ======================================================================
230
231 /*
232 * A simple write buffer pool. Each socket has a dedicated "primary"
233 * buffer and can borrow from a shared pool with limited size tuning.
234 * Could enhance e.g. with separate pools per network interface and fancier
235 * memory tuning based on interface speed, system resources, and
236 * number of connections, etc.
237 */
238
239 namespace pn_experimental {
240
241 // Max overlapped writes per socket
242 #define IOCP_MAX_OWRITES 16
243 // Write buffer size
244 #define IOCP_WBUFSIZE 16384
245
246 static void pipeline_log(const char *fmt, ...)
247 {
248 va_list ap;
249 va_start(ap, fmt);
250 vfprintf(stderr, fmt, ap);
251 va_end(ap);
252 fflush(stderr);
253 }
254
255 void pni_shared_pool_create(iocp_t *iocp)
256 {
257 // TODO: more pools (or larger one) when using multiple non-loopback interfaces
258 iocp->shared_pool_size = 16;
259 char *env = getenv("PNI_WRITE_BUFFERS"); // Internal: for debugging
260 if (env) {
261 int sz = atoi(env);
262 if (sz >= 0 && sz < 256) {
263 iocp->shared_pool_size = sz;
264 }
265 }
266 iocp->loopback_bufsize = 0;
267 env = getenv("PNI_LB_BUFSIZE"); // Internal: for debugging
268 if (env) {
269 int sz = atoi(env);
270 if (sz >= 0 && sz <= 128 * 1024) {
271 iocp->loopback_bufsize = sz;
272 }
273 }
274
275 if (iocp->shared_pool_size) {
276 iocp->shared_pool_memory = (char *) VirtualAlloc(NULL, IOCP_WBUFSIZE * iocp->shared_pool_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
277 HRESULT status = GetLastError();
278 if (!iocp->shared_pool_memory) {
279 perror("Proton write buffer pool allocation failure\n");
280 iocp->shared_pool_size = 0;
281 iocp->shared_available_count = 0;
282 return;
283 }
284
285 iocp->shared_results = (write_result_t **) malloc(iocp->shared_pool_size * sizeof(write_result_t *));
286 iocp->available_results = (write_result_t **) malloc(iocp->shared_pool_size * sizeof(write_result_t *));
287 iocp->shared_available_count = iocp->shared_pool_size;
288 char *mem = iocp->shared_pool_memory;
289 for (unsigned i = 0; i < iocp->shared_pool_size; i++) {
290 iocp->shared_results[i] = iocp->available_results[i] = pni_write_result(NULL, mem, IOCP_WBUFSIZE);
291 mem += IOCP_WBUFSIZE;
292 }
293 }
294 }
295
296 void pni_shared_pool_free(iocp_t *iocp)
297 {
298 for (unsigned i = 0; i < iocp->shared_pool_size; i++) {
299 write_result_t *result = iocp->shared_results[i];
300 if (result->in_use)
301 pipeline_log("Proton buffer pool leak\n");
302 else
303 free(result);
304 }
305 if (iocp->shared_pool_size) {
306 free(iocp->shared_results);
307 free(iocp->available_results);
308 if (iocp->shared_pool_memory) {
309 if (!VirtualFree(iocp->shared_pool_memory, 0, MEM_RELEASE)) {
310 perror("write buffers release failed");
311 }
312 iocp->shared_pool_memory = NULL;
313 }
314 }
315 }
316
317 static void shared_pool_push(write_result_t *result)
318 {
319 iocp_t *iocp = result->base.iocpd->iocp;
320 assert(iocp->shared_available_count < iocp->shared_pool_size);
321 iocp->available_results[iocp->shared_available_count++] = result;
322 }
323
324 static write_result_t *shared_pool_pop(iocp_t *iocp)
325 {
326 return iocp->shared_available_count ? iocp->available_results[--iocp->shared_available_count] : NULL;
327 }
328
329 struct write_pipeline_t {
330 iocpdesc_t *iocpd;
331 size_t pending_count;
332 write_result_t *primary;
333 size_t reserved_count;
334 size_t next_primary_index;
335 size_t depth;
336 bool is_writer;
337 };
338
339 #define write_pipeline_compare NULL
340 #define write_pipeline_inspect NULL
341 #define write_pipeline_hashcode NULL
342
343 static void write_pipeline_initialize(void *object)
344 {
345 write_pipeline_t *pl = (write_pipeline_t *) object;
346 pl->pending_count = 0;
347 const char *pribuf = (const char *) malloc(IOCP_WBUFSIZE);
348 pl->primary = pni_write_result(NULL, pribuf, IOCP_WBUFSIZE);
349 pl->depth = 0;
350 pl->is_writer = false;
351 }
352
353 static void write_pipeline_finalize(void *object)
354 {
355 write_pipeline_t *pl = (write_pipeline_t *) object;
356 free((void *)pl->primary->buffer.start);
357 free(pl->primary);
358 }
359
360 write_pipeline_t *pni_write_pipeline(iocpdesc_t *iocpd)
361 {
362 static const pn_cid_t CID_write_pipeline = CID_pn_void;
363 static const pn_class_t clazz = PN_CLASS(write_pipeline);
364 write_pipeline_t *pipeline = (write_pipeline_t *) pn_class_new(&clazz, sizeof(write_pipeline_t));
365 pipeline->iocpd = iocpd;
366 pipeline->primary->base.iocpd = iocpd;
367 return pipeline;
368 }
369
370 static void confirm_as_writer(write_pipeline_t *pl)
371 {
372 if (!pl->is_writer) {
373 iocp_t *iocp = pl->iocpd->iocp;
374 iocp->writer_count++;
375 pl->is_writer = true;
376 }
377 }
378
379 static void remove_as_writer(write_pipeline_t *pl)
380 {
381 if (!pl->is_writer)
382 return;
383 iocp_t *iocp = pl->iocpd->iocp;
384 assert(iocp->writer_count);
385 pl->is_writer = false;
386 iocp->writer_count--;
387 }
388
389 /*
390 * Optimal depth will depend on properties of the NIC, server, and driver. For now,
391 * just distinguish between loopback interfaces and the rest. Optimizations in the
392 * loopback stack allow decent performance with depth 1 and actually cause major
393 * performance hiccups if set to large values.
394 */
395 static void set_depth(write_pipeline_t *pl)
396 {
397 pl->depth = 1;
398 sockaddr_storage sa;
399 socklen_t salen = sizeof(sa);
400 char buf[INET6_ADDRSTRLEN];
401 DWORD buflen = sizeof(buf);
402
403 if (getsockname(pl->iocpd->socket,(sockaddr*) &sa, &salen) == 0 &&
404 getnameinfo((sockaddr*) &sa, salen, buf, buflen, NULL, 0, NI_NUMERICHOST) == 0) {
405 if ((sa.ss_family == AF_INET6 && strcmp(buf, "::1")) ||
406 (sa.ss_family == AF_INET && strncmp(buf, "127.", 4))) {
407 // not loopback
408 pl->depth = IOCP_MAX_OWRITES;
409 } else {
410 iocp_t *iocp = pl->iocpd->iocp;
411 if (iocp->loopback_bufsize) {
412 const char *p = (const char *) realloc((void *) pl->primary->buffer.start, iocp->loopback_bufsize);
413 if (p) {
414 pl->primary->buffer.start = p;
415 pl->primary->buffer.size = iocp->loopback_bufsize;
416 }
417 }
418 }
419 }
420 }
421
422 static size_t pni_min(size_t a, size_t b) { return a < b ? a : b; }
423
424 // Reserve as many buffers as possible for count bytes.
425 size_t pni_write_pipeline_reserve(write_pipeline_t *pl, size_t count)
426 {
427 if (pl->primary->in_use)
428 return 0; // I.e. io->wouldblock
429 if (!pl->depth)
430 set_depth(pl);
431 if (pl->depth == 1) {
432 // always use the primary
433 pl->reserved_count = 1;
434 pl->next_primary_index = 0;
435 return 1;
436 }
437
438 iocp_t *iocp = pl->iocpd->iocp;
439 confirm_as_writer(pl);
440 size_t wanted = (count / IOCP_WBUFSIZE);
441 if (count % IOCP_WBUFSIZE)
442 wanted++;
443 size_t pending = pl->pending_count;
444 assert(pending < pl->depth);
445 size_t bufs = pni_min(wanted, pl->depth - pending);
446 // Can draw from shared pool or the primary... but share with others.
447 size_t writers = iocp->writer_count;
448 size_t shared_count = (iocp->shared_available_count + writers - 1) / writers;
449 bufs = pni_min(bufs, shared_count + 1);
450 pl->reserved_count = pending + bufs;
451
452 if (bufs == wanted &&
453 pl->reserved_count < (pl->depth / 2) &&
454 iocp->shared_available_count > (2 * writers + bufs)) {
455 // No shortage: keep the primary as spare for future use
456 pl->next_primary_index = pl->reserved_count;
457 } else if (bufs == 1) {
458 pl->next_primary_index = pending;
459 } else {
460 // let approx 1/3 drain before replenishing
461 pl->next_primary_index = ((pl->reserved_count + 2) / 3) - 1;
462 if (pl->next_primary_index < pending)
463 pl->next_primary_index = pending;
464 }
465 return bufs;
466 }
467
468 write_result_t *pni_write_pipeline_next(write_pipeline_t *pl)
469 {
470 size_t sz = pl->pending_count;
471 if (sz >= pl->reserved_count)
472 return NULL;
473 write_result_t *result;
474 if (sz == pl->next_primary_index) {
475 result = pl->primary;
476 } else {
477 assert(pl->iocpd->iocp->shared_available_count > 0);
478 result = shared_pool_pop(pl->iocpd->iocp);
479 }
480
481 result->in_use = true;
482 pl->pending_count++;
483 return result;
484 }
485
486 void pni_write_pipeline_return(write_pipeline_t *pl, write_result_t *result)
487 {
488 result->in_use = false;
489 pl->pending_count--;
490 pl->reserved_count = 0;
491 if (result != pl->primary)
492 shared_pool_push(result);
493 if (pl->pending_count == 0)
494 remove_as_writer(pl);
495 }
496
497 bool pni_write_pipeline_writable(write_pipeline_t *pl)
498 {
499 // Only writable if not full and we can guarantee a buffer:
500 return pl->pending_count < pl->depth && !pl->primary->in_use;
501 }
502
503 size_t pni_write_pipeline_size(write_pipeline_t *pl)
504 {
505 return pl->pending_count;
506 }
507
508 }
509
510
511 // ======================================================================
512 // IOCP infrastructure code
513 // ======================================================================
514
515 /*
516 * Socket IO including graceful or forced zombie teardown.
517 *
518 * Overlapped writes are used to avoid lengthy stalls between write
519 * completion and starting a new write. Non-overlapped reads are used
520 * since Windows accumulates inbound traffic without stalling and
521 * managing read buffers would not avoid a memory copy at the pn_read
522 * boundary.
523 *
524 * A socket must not get a Windows closesocket() unless the
525 * application has called pn_connection_close on the connection or a
526 * global single threaded shutdown is in progress. On error, the
527 * internal accounting for write_closed or read_closed may be updated
528 * along with the external event notification. A socket may be
529 * directly closed if it is never gets started (accept/listener_close
530 * collision) or otherwise turned into a zombie.
531 */
532
533 namespace pn_experimental {
534
535 static void iocp_log(const char *fmt, ...)
536 {
537 va_list ap;
538 va_start(ap, fmt);
539 vfprintf(stderr, fmt, ap);
540 va_end(ap);
541 fflush(stderr);
542 }
543
544 static void set_iocp_error_status(pn_error_t *error, int code, HRESULT status)
545 {
546 char buf[512];
547 if (FormatMessage(FORMAT_MESSAGE_MAX_WIDTH_MASK | FORMAT_MESSAGE_FROM_SYSTEM,
548 0, status, 0, buf, sizeof(buf), 0))
549 pn_error_set(error, code, buf);
550 else {
551 fprintf(stderr, "pn internal Windows error: %lu\n", GetLastError());
552 }
553 }
554
555 static void reap_check(iocpdesc_t *);
556 static void bind_to_completion_port(iocpdesc_t *iocpd);
557 static void iocp_shutdown(iocpdesc_t *iocpd);
558 static bool is_listener(iocpdesc_t *iocpd);
559 static void release_sys_sendbuf(SOCKET s);
560
561 int pni_win32_error(pn_error_t *error, const char *msg, HRESULT code)
562 {
563 // Error code can be from GetLastError or WSAGetLastError,
564 char err[1024] = {0};
565 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |
566 FORMAT_MESSAGE_MAX_WIDTH_MASK, NULL, code, 0, (LPSTR)&err, sizeof(err), NULL);
567 return pn_error_format(error, PN_ERR, "%s: %s", msg, err);
568 }
569
570 static void iocpdesc_fail(iocpdesc_t *iocpd, HRESULT status, const char* text)
571 {
572 pni_win32_error(iocpd->error, text, status);
573 if (iocpd->iocp->iocp_trace) {
574 iocp_log("connection terminated: %s\n", pn_error_text(iocpd->error));
575 }
576 iocpd->write_closed = true;
577 iocpd->read_closed = true;
578 iocpd->poll_error = true;
579 pni_events_update(iocpd, iocpd->events & ~(PN_READABLE | PN_WRITABLE));
580 }
581
582 static int pni_strcasecmp(const char *a, const char *b)
583 {
584 int diff;
585 while (*b) {
586 char aa = *a++, bb = *b++;
587 diff = tolower(aa)-tolower(bb);
588 if ( diff!=0 ) return diff;
589 }
590 return *a;
591 }
592
593 static void pni_events_update(iocpdesc_t *iocpd, int events)
594 {
595 // If set, a poll error is permanent
596 if (iocpd->poll_error)
597 events |= PN_ERROR;
598 if (iocpd->events == events)
599 return;
600 // ditch old code to update list of ready selectables
601 iocpd->events = events;
602 }
603
604 // Helper functions to use specialized IOCP AcceptEx() and ConnectEx()
605 static LPFN_ACCEPTEX lookup_accept_ex(SOCKET s)
606 {
607 GUID guid = WSAID_ACCEPTEX;
608 DWORD bytes = 0;
609 LPFN_ACCEPTEX fn;
610 WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid),
611 &fn, sizeof(fn), &bytes, NULL, NULL);
612 assert(fn);
613 return fn;
614 }
615
616 static LPFN_CONNECTEX lookup_connect_ex(SOCKET s)
617 {
618 GUID guid = WSAID_CONNECTEX;
619 DWORD bytes = 0;
620 LPFN_CONNECTEX fn;
621 WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid),
622 &fn, sizeof(fn), &bytes, NULL, NULL);
623 assert(fn);
624 return fn;
625 }
626
627 static LPFN_GETACCEPTEXSOCKADDRS lookup_get_accept_ex_sockaddrs(SOCKET s)
628 {
629 GUID guid = WSAID_GETACCEPTEXSOCKADDRS;
630 DWORD bytes = 0;
631 LPFN_GETACCEPTEXSOCKADDRS fn;
632 WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid),
633 &fn, sizeof(fn), &bytes, NULL, NULL);
634 assert(fn);
635 return fn;
636 }
637
638 // match accept socket to listener socket
639 iocpdesc_t *create_same_type_socket(iocpdesc_t *iocpd)
640 {
641 sockaddr_storage sa;
642 socklen_t salen = sizeof(sa);
643 if (getsockname(iocpd->socket, (sockaddr*)&sa, &salen) == -1)
644 return NULL;
645 SOCKET s = socket(sa.ss_family, SOCK_STREAM, 0); // Currently only work with SOCK_STREAM
646 if (s == INVALID_SOCKET)
647 return NULL;
648 return pni_iocpdesc_create(iocpd->iocp, s);
649 }
650
651 static bool is_listener(iocpdesc_t *iocpd)
652 {
653 return iocpd && iocpd->acceptor;
654 }
655
656 // === Async accept processing
657
658 static accept_result_t *accept_result(iocpdesc_t *listen_sock) {
659 accept_result_t *result = (accept_result_t *)calloc(1, sizeof(accept_result_t));
660 if (result) {
661 result->base.type = IOCP_ACCEPT;
662 result->base.iocpd = listen_sock;
663 }
664 return result;
665 }
666
667 void reset_accept_result(accept_result_t *result) {
668 memset(&result->base.overlapped, 0, sizeof (OVERLAPPED));
669 memset(&result->address_buffer, 0, IOCP_SOCKADDRBUFLEN);
670 result->new_sock = NULL;
671 }
672
673 struct pni_acceptor_t {
674 int accept_queue_size;
675 pn_list_t *accepts;
676 iocpdesc_t *listen_sock;
677 bool signalled;
678 LPFN_ACCEPTEX fn_accept_ex;
679 LPFN_GETACCEPTEXSOCKADDRS fn_get_accept_ex_sockaddrs;
680 };
681
682 #define pni_acceptor_compare NULL
683 #define pni_acceptor_inspect NULL
684 #define pni_acceptor_hashcode NULL
685
686 static void pni_acceptor_initialize(void *object)
687 {
688 pni_acceptor_t *acceptor = (pni_acceptor_t *) object;
689 acceptor->accepts = pn_list(PN_VOID, IOCP_MAX_ACCEPTS);
690 }
691
692 static void pni_acceptor_finalize(void *object)
693 {
694 pni_acceptor_t *acceptor = (pni_acceptor_t *) object;
695 size_t len = pn_list_size(acceptor->accepts);
696 for (size_t i = 0; i < len; i++)
697 free(pn_list_get(acceptor->accepts, i));
698 pn_free(acceptor->accepts);
699 }
700
701 static pni_acceptor_t *pni_acceptor(iocpdesc_t *iocpd)
702 {
703 static const pn_cid_t CID_pni_acceptor = CID_pn_void;
704 static const pn_class_t clazz = PN_CLASS(pni_acceptor);
705 pni_acceptor_t *acceptor = (pni_acceptor_t *) pn_class_new(&clazz, sizeof(pni_acceptor_t));
706 acceptor->listen_sock = iocpd;
707 acceptor->accept_queue_size = 0;
708 acceptor->signalled = false;
709 pn_socket_t sock = acceptor->listen_sock->socket;
710 acceptor->fn_accept_ex = lookup_accept_ex(sock);
711 acceptor->fn_get_accept_ex_sockaddrs = lookup_get_accept_ex_sockaddrs(sock);
712 return acceptor;
713 }
714
715 void begin_accept(pni_acceptor_t *acceptor, accept_result_t *result)
716 {
717 // flag to divide this routine's logic into locked/unlocked mp portions
718 bool mp = acceptor->listen_sock->is_mp;
719 bool created = false;
720
721 if (acceptor->listen_sock->closing) {
722 if (result) {
723 if (mp && result->new_sock && result->new_sock->socket != INVALID_SOCKET)
724 closesocket(result->new_sock->socket);
725 free(result);
726 acceptor->accept_queue_size--;
727 }
728 if (acceptor->accept_queue_size == 0)
729 acceptor->signalled = true;
730 return;
731 }
732
733 if (result) {
734 if (!mp)
735 reset_accept_result(result);
736 } else {
737 if (acceptor->accept_queue_size < IOCP_MAX_ACCEPTS && (mp ||
738 pn_list_size(acceptor->accepts) == acceptor->accept_queue_size )) {
739 result = accept_result(acceptor->listen_sock);
740 acceptor->accept_queue_size++;
741 created = true;
742 } else {
743 // an async accept is still pending or max concurrent accepts already hit
744 return;
745 }
746 }
747
748 if (created || !mp)
749 result->new_sock = create_same_type_socket(acceptor->listen_sock);
750 if (result->new_sock) {
751 // Not yet connected.
752 result->new_sock->read_closed = true;
753 result->new_sock->write_closed = true;
754
755 bool success = acceptor->fn_accept_ex(acceptor->listen_sock->socket, result->new_sock->socket,
756 result->address_buffer, 0, IOCP_SOCKADDRMAXLEN, IOCP_SOCKADDRMAXLEN,
757 &result->unused, (LPOVERLAPPED) result);
758 if (!success) {
759 DWORD err = WSAGetLastError();
760 if (err != ERROR_IO_PENDING) {
761 if (err == WSAECONNRESET) {
762 // other side gave up. Ignore and try again.
763 begin_accept(acceptor, result);
764 return;
765 }
766 else {
767 iocpdesc_fail(acceptor->listen_sock, err, "AcceptEX call failure");
768 return;
769 }
770 }
771 acceptor->listen_sock->ops_in_progress++;
772 // This socket is equally involved in the async operation.
773 result->new_sock->ops_in_progress++;
774 }
775 } else {
776 iocpdesc_fail(acceptor->listen_sock, WSAGetLastError(), "create accept socket");
777 }
778 }
779
780 static void complete_accept(accept_result_t *result, HRESULT status)
781 {
782 result->new_sock->ops_in_progress--;
783 iocpdesc_t *ld = result->base.iocpd;
784 if (ld->read_closed) {
785 if (!result->new_sock->closing)
786 pni_iocp_begin_close(result->new_sock);
787 pn_decref(result->new_sock);
788 free(result); // discard
789 reap_check(ld);
790 } else {
791 assert(!ld->is_mp); // Non mp only
792 result->base.status = status;
793 pn_list_add(ld->acceptor->accepts, result);
794 pni_events_update(ld, ld->events | PN_READABLE);
795 }
796 }
797
798
799 // === Async connect processing
800
801
802 #define connect_result_initialize NULL
803 #define connect_result_compare NULL
804 #define connect_result_inspect NULL
805 #define connect_result_hashcode NULL
806
807 static void connect_result_finalize(void *object)
808 {
809 connect_result_t *result = (connect_result_t *) object;
810 // Do not release addrinfo until ConnectEx completes
811 if (result->addrinfo)
812 freeaddrinfo(result->addrinfo);
813 }
814
815 connect_result_t *connect_result(iocpdesc_t *iocpd, struct addrinfo *addr) {
816 static const pn_cid_t CID_connect_result = CID_pn_void;
817 static const pn_class_t clazz = PN_CLASS(connect_result);
818 connect_result_t *result = (connect_result_t *) pn_class_new(&clazz, sizeof(connect_result_t));
819 if (result) {
820 memset(result, 0, sizeof(connect_result_t));
821 result->base.type = IOCP_CONNECT;
822 result->base.iocpd = iocpd;
823 result->addrinfo = addr;
824 }
825 return result;
826 }
827
828 pn_socket_t pni_iocp_begin_connect(iocp_t *iocp, pn_socket_t sock, struct addrinfo *addr, pn_error_t *error)
829 {
830 // addr lives for the duration of the async connect. Caller has passed ownership here.
831 // See connect_result_finalize().
832 // Use of Windows-specific ConnectEx() requires our socket to be "loosely" pre-bound:
833 sockaddr_storage sa;
834 memset(&sa, 0, sizeof(sa));
835 sa.ss_family = addr->ai_family;
836 if (bind(sock, (SOCKADDR *) &sa, addr->ai_addrlen)) {
837 pni_win32_error(error, "begin async connection", WSAGetLastError());
838 if (iocp->iocp_trace)
839 iocp_log("%s\n", pn_error_text(error));
840 closesocket(sock);
841 freeaddrinfo(addr);
842 return INVALID_SOCKET;
843 }
844
845 iocpdesc_t *iocpd = pni_iocpdesc_create(iocp, sock);
846 bind_to_completion_port(iocpd);
847 LPFN_CONNECTEX fn_connect_ex = lookup_connect_ex(iocpd->socket);
848 connect_result_t *result = connect_result(iocpd, addr);
849 DWORD unused;
850 bool success = fn_connect_ex(iocpd->socket, result->addrinfo->ai_addr, result->addrinfo->ai_addrlen,
851 NULL, 0, &unused, (LPOVERLAPPED) result);
852 if (!success && WSAGetLastError() != ERROR_IO_PENDING) {
853 pni_win32_error(error, "ConnectEx failure", WSAGetLastError());
854 pn_free(result);
855 iocpd->write_closed = true;
856 iocpd->read_closed = true;
857 if (iocp->iocp_trace)
858 iocp_log("%s\n", pn_error_text(error));
859 } else {
860 iocpd->ops_in_progress++;
861 }
862 return sock;
863 }
864
865 void complete_connect(connect_result_t *result, HRESULT status)
866 {
867 iocpdesc_t *iocpd = result->base.iocpd;
868 if (iocpd->closing) {
869 pn_free(result);
870 reap_check(iocpd);
871 return;
872 }
873
874 if (status) {
875 iocpdesc_fail(iocpd, status, "Connect failure");
876 // Posix sets selectable events as follows:
877 pni_events_update(iocpd, PN_READABLE | PN_EXPIRED);
878 } else {
879 release_sys_sendbuf(iocpd->socket);
880 if (setsockopt(iocpd->socket, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0)) {
881 iocpdesc_fail(iocpd, WSAGetLastError(), "Internal connect failure (update context)");
882 } else {
883 pni_events_update(iocpd, PN_WRITABLE);
884 start_reading(iocpd);
885 }
886 }
887 pn_free(result);
888 return;
889 }
890
891
892 // === Async writes
893
894 static bool write_in_progress(iocpdesc_t *iocpd)
895 {
896 return pni_write_pipeline_size(iocpd->pipeline) != 0;
897 }
898
899 write_result_t *pni_write_result(iocpdesc_t *iocpd, const char *buf, size_t buflen)
900 {
901 write_result_t *result = (write_result_t *) calloc(sizeof(write_result_t), 1);
902 if (result) {
903 result->base.type = IOCP_WRITE;
904 result->base.iocpd = iocpd;
905 result->buffer.start = buf;
906 result->buffer.size = buflen;
907 }
908 return result;
909 }
910
911 static int submit_write(write_result_t *result, const void *buf, size_t len)
912 {
913 WSABUF wsabuf;
914 wsabuf.buf = (char *) buf;
915 wsabuf.len = len;
916 memset(&result->base.overlapped, 0, sizeof (OVERLAPPED));
917 return WSASend(result->base.iocpd->socket, &wsabuf, 1, NULL, 0,
918 (LPOVERLAPPED) result, 0);
919 }
920
921 ssize_t pni_iocp_begin_write(iocpdesc_t *iocpd, const void *buf, size_t len, bool *would_block, pn_error_t *error)
922 {
923 if (len == 0) return 0;
924 *would_block = false;
925 if (is_listener(iocpd)) {
926 set_iocp_error_status(error, PN_ERR, WSAEOPNOTSUPP);
927 return INVALID_SOCKET;
928 }
929 if (iocpd->closing) {
930 set_iocp_error_status(error, PN_ERR, WSAESHUTDOWN);
931 return SOCKET_ERROR;
932 }
933 if (iocpd->write_closed) {
934 assert(pn_error_code(iocpd->error));
935 pn_error_copy(error, iocpd->error);
936 if (iocpd->iocp->iocp_trace)
937 iocp_log("write error: %s\n", pn_error_text(error));
938 return SOCKET_ERROR;
939 }
940 if (len == 0) return 0;
941 if (!(iocpd->events & PN_WRITABLE)) {
942 *would_block = true;
943 return SOCKET_ERROR;
944 }
945
946 size_t written = 0;
947 size_t requested = len;
948 const char *outgoing = (const char *) buf;
949 size_t available = pni_write_pipeline_reserve(iocpd->pipeline, len);
950 if (!available) {
951 *would_block = true;
952 return SOCKET_ERROR;
953 }
954
955 for (size_t wr_count = 0; wr_count < available; wr_count++) {
956 write_result_t *result = pni_write_pipeline_next(iocpd->pipeline);
957 assert(result);
958 result->base.iocpd = iocpd;
959 ssize_t actual_len = len;
960 if (len > result->buffer.size) actual_len = result->buffer.size;
961 result->requested = actual_len;
962 memmove((void *)result->buffer.start, outgoing, actual_len);
963 outgoing += actual_len;
964 written += actual_len;
965 len -= actual_len;
966
967 int werror = submit_write(result, result->buffer.start, actual_len);
968 if (werror && WSAGetLastError() != ERROR_IO_PENDING) {
969 pni_write_pipeline_return(iocpd->pipeline, result);
970 iocpdesc_fail(iocpd, WSAGetLastError(), "overlapped send");
971 return SOCKET_ERROR;
972 }
973 iocpd->ops_in_progress++;
974 }
975
976 if (!pni_write_pipeline_writable(iocpd->pipeline))
977 pni_events_update(iocpd, iocpd->events & ~PN_WRITABLE);
978 return written;
979 }
980
981 /*
982 * Note: iocp write completion is not "bytes on the wire", it is "peer
983 * acked the sent bytes". Completion can be seconds on a slow
984 * consuming peer.
985 */
986 void complete_write(write_result_t *result, DWORD xfer_count, HRESULT status)
987 {
988 iocpdesc_t *iocpd = result->base.iocpd;
989 if (iocpd->closing) {
990 pni_write_pipeline_return(iocpd->pipeline, result);
991 if (!iocpd->write_closed && !write_in_progress(iocpd))
992 iocp_shutdown(iocpd);
993 reap_check(iocpd);
994 return;
995 }
996 if (status == 0 && xfer_count > 0) {
997 if (xfer_count != result->requested) {
998 // Is this recoverable? How to preserve order if multiple overlapped writes?
999 pni_write_pipeline_return(iocpd->pipeline, result);
1000 iocpdesc_fail(iocpd, WSA_OPERATION_ABORTED, "Partial overlapped write on socket");
1001 return;
1002 } else {
1003 // Success.
1004 pni_write_pipeline_return(iocpd->pipeline, result);
1005 if (pni_write_pipeline_writable(iocpd->pipeline))
1006 pni_events_update(iocpd, iocpd->events | PN_WRITABLE);
1007 return;
1008 }
1009 }
1010 // Other error
1011 pni_write_pipeline_return(iocpd->pipeline, result);
1012 if (status == WSAECONNABORTED || status == WSAECONNRESET || status == WSAENOTCONN
1013 || status == ERROR_NETNAME_DELETED) {
1014 iocpd->write_closed = true;
1015 iocpd->poll_error = true;
1016 pni_events_update(iocpd, iocpd->events & ~PN_WRITABLE);
1017 pni_win32_error(iocpd->error, "Remote close or timeout", status);
1018 } else {
1019 iocpdesc_fail(iocpd, status, "IOCP async write error");
1020 }
1021 }
1022
1023
1024 // === Async reads
1025
1026
1027 static read_result_t *read_result(iocpdesc_t *iocpd)
1028 {
1029 read_result_t *result = (read_result_t *) calloc(sizeof(read_result_t), 1);
1030 if (result) {
1031 result->base.type = IOCP_READ;
1032 result->base.iocpd = iocpd;
1033 }
1034 return result;
1035 }
1036
1037 static void begin_zero_byte_read(iocpdesc_t *iocpd)
1038 {
1039 if (iocpd->read_in_progress) return;
1040 if (iocpd->read_closed) {
1041 pni_events_update(iocpd, iocpd->events | PN_READABLE);
1042 return;
1043 }
1044
1045 read_result_t *result = iocpd->read_result;
1046 memset(&result->base.overlapped, 0, sizeof (OVERLAPPED));
1047 DWORD flags = 0;
1048 WSABUF wsabuf;
1049 wsabuf.buf = result->unused_buf;
1050 wsabuf.len = 0;
1051 int rc = WSARecv(iocpd->socket, &wsabuf, 1, NULL, &flags,
1052 &result->base.overlapped, 0);
1053 if (rc && WSAGetLastError() != ERROR_IO_PENDING) {
1054 iocpdesc_fail(iocpd, WSAGetLastError(), "IOCP read error");
1055 return;
1056 }
1057 iocpd->ops_in_progress++;
1058 iocpd->read_in_progress = true;
1059 }
1060
1061 static void drain_until_closed(iocpdesc_t *iocpd) {
1062 size_t max_drain = 16 * 1024;
1063 char buf[512];
1064 read_result_t *result = iocpd->read_result;
1065 while (result->drain_count < max_drain) {
1066 int rv = recv(iocpd->socket, buf, 512, 0);
1067 if (rv > 0)
1068 result->drain_count += rv;
1069 else if (rv == 0) {
1070 iocpd->read_closed = true;
1071 return;
1072 } else if (WSAGetLastError() == WSAEWOULDBLOCK) {
1073 // wait a little longer
1074 start_reading(iocpd);
1075 return;
1076 }
1077 else
1078 break;
1079 }
1080 // Graceful close indication unlikely, force the issue
1081 if (iocpd->iocp->iocp_trace)
1082 if (result->drain_count >= max_drain)
1083 iocp_log("graceful close on reader abandoned (too many chars)\n");
1084 else
1085 iocp_log("graceful close on reader abandoned: %d\n", WSAGetLastError());
1086 iocpd->read_closed = true;
1087 }
1088
1089
1090 void complete_read(read_result_t *result, DWORD xfer_count, HRESULT status)
1091 {
1092 iocpdesc_t *iocpd = result->base.iocpd;
1093 iocpd->read_in_progress = false;
1094
1095 if (iocpd->closing) {
1096 // Application no longer reading, but we are looking for a zero length read
1097 if (!iocpd->read_closed)
1098 drain_until_closed(iocpd);
1099 reap_check(iocpd);
1100 return;
1101 }
1102
1103 if (status == 0 && xfer_count == 0) {
1104 // Success.
1105 pni_events_update(iocpd, iocpd->events | PN_READABLE);
1106 } else {
1107 iocpdesc_fail(iocpd, status, "IOCP read complete error");
1108 }
1109 }
1110
1111 ssize_t pni_iocp_recv(iocpdesc_t *iocpd, void *buf, size_t size, bool *would_block, pn_error_t *error)
1112 {
1113 if (size == 0) return 0;
1114 *would_block = false;
1115 if (is_listener(iocpd)) {
1116 set_iocp_error_status(error, PN_ERR, WSAEOPNOTSUPP);
1117 return SOCKET_ERROR;
1118 }
1119 if (iocpd->closing) {
1120 // Previous call to pn_close()
1121 set_iocp_error_status(error, PN_ERR, WSAESHUTDOWN);
1122 return SOCKET_ERROR;
1123 }
1124 if (iocpd->read_closed) {
1125 if (pn_error_code(iocpd->error))
1126 pn_error_copy(error, iocpd->error);
1127 else
1128 set_iocp_error_status(error, PN_ERR, WSAENOTCONN);
1129 return SOCKET_ERROR;
1130 }
1131
1132 int count = recv(iocpd->socket, (char *) buf, size, 0);
1133 if (count > 0) {
1134 pni_events_update(iocpd, iocpd->events & ~PN_READABLE);
1135 // caller must initiate begin_zero_byte_read(iocpd);
1136 return (ssize_t) count;
1137 } else if (count == 0) {
1138 iocpd->read_closed = true;
1139 return 0;
1140 }
1141 if (WSAGetLastError() == WSAEWOULDBLOCK)
1142 *would_block = true;
1143 else {
1144 set_iocp_error_status(error, PN_ERR, WSAGetLastError());
1145 iocpd->read_closed = true;
1146 }
1147 return SOCKET_ERROR;
1148 }
1149
1150 void start_reading(iocpdesc_t *iocpd)
1151 {
1152 begin_zero_byte_read(iocpd);
1153 }
1154
1155
1156 // === The iocp descriptor
1157
1158 static void pni_iocpdesc_initialize(void *object)
1159 {
1160 iocpdesc_t *iocpd = (iocpdesc_t *) object;
1161 memset(iocpd, 0, sizeof(iocpdesc_t));
1162 iocpd->socket = INVALID_SOCKET;
1163 }
1164
1165 static void pni_iocpdesc_finalize(void *object)
1166 {
1167 iocpdesc_t *iocpd = (iocpdesc_t *) object;
1168 pn_free(iocpd->acceptor);
1169 pn_error_free(iocpd->error);
1170 if (iocpd->pipeline)
1171 if (write_in_progress(iocpd))
1172 iocp_log("iocp descriptor write leak\n");
1173 else
1174 pn_free(iocpd->pipeline);
1175 if (iocpd->read_in_progress)
1176 iocp_log("iocp descriptor read leak\n");
1177 else
1178 free(iocpd->read_result);
1179 }
1180
1181 static uintptr_t pni_iocpdesc_hashcode(void *object)
1182 {
1183 iocpdesc_t *iocpd = (iocpdesc_t *) object;
1184 return iocpd->socket;
1185 }
1186
1187 #define pni_iocpdesc_compare NULL
1188 #define pni_iocpdesc_inspect NULL
1189
1190 // Reference counted in the iocpdesc map, zombie_list, selector.
1191 static iocpdesc_t *pni_iocpdesc(pn_socket_t s)
1192 {
1193 static const pn_cid_t CID_pni_iocpdesc = CID_pn_void;
1194 static pn_class_t clazz = PN_CLASS(pni_iocpdesc);
1195 iocpdesc_t *iocpd = (iocpdesc_t *) pn_class_new(&clazz, sizeof(iocpdesc_t));
1196 assert(iocpd);
1197 iocpd->socket = s;
1198 return iocpd;
1199 }
1200
1201 static bool is_listener_socket(pn_socket_t s)
1202 {
1203 BOOL tval = false;
1204 int tvalsz = sizeof(tval);
1205 int code = getsockopt(s, SOL_SOCKET, SO_ACCEPTCONN, (char *)&tval, &tvalsz);
1206 return code == 0 && tval;
1207 }
1208
1209 iocpdesc_t *pni_iocpdesc_create(iocp_t *iocp, pn_socket_t s) {
1210 assert (s != INVALID_SOCKET);
1211 bool listening = is_listener_socket(s);
1212 iocpdesc_t *iocpd = pni_iocpdesc(s);
1213 iocpd->iocp = iocp;
1214 if (iocpd) {
1215 iocpd->error = pn_error();
1216 if (listening) {
1217 iocpd->acceptor = pni_acceptor(iocpd);
1218 } else {
1219 iocpd->pipeline = pni_write_pipeline(iocpd);
1220 iocpd->read_result = read_result(iocpd);
1221 }
1222 }
1223 return iocpd;
1224 }
1225
1226
1227 static void bind_to_completion_port(iocpdesc_t *iocpd)
1228 {
1229 if (iocpd->bound) return;
1230 if (!iocpd->iocp->completion_port) {
1231 iocpdesc_fail(iocpd, WSAEINVAL, "Incomplete setup, no completion port.");
1232 return;
1233 }
1234
1235 if (CreateIoCompletionPort ((HANDLE) iocpd->socket, iocpd->iocp->completion_port, proactor_io, 0))
1236 iocpd->bound = true;
1237 else {
1238 iocpdesc_fail(iocpd, GetLastError(), "IOCP socket setup.");
1239 }
1240 }
1241
1242 static void release_sys_sendbuf(SOCKET s)
1243 {
1244 // Set the socket's send buffer size to zero.
1245 int sz = 0;
1246 int status = setsockopt(s, SOL_SOCKET, SO_SNDBUF, (const char *)&sz, sizeof(int));
1247 assert(status == 0);
1248 }
1249
1250 void pni_iocpdesc_start(iocpdesc_t *iocpd)
1251 {
1252 if (iocpd->bound) return;
1253 bind_to_completion_port(iocpd);
1254 if (is_listener(iocpd)) {
1255 begin_accept(iocpd->acceptor, NULL);
1256 }
1257 else {
1258 release_sys_sendbuf(iocpd->socket);
1259 pni_events_update(iocpd, PN_WRITABLE);
1260 start_reading(iocpd);
1261 }
1262 }
1263
1264 static void complete(iocp_result_t *result, bool success, DWORD num_transferred) {
1265 result->iocpd->ops_in_progress--;
1266 DWORD status = success ? 0 : GetLastError();
1267
1268 switch (result->type) {
1269 case IOCP_ACCEPT:
1270 complete_accept((accept_result_t *) result, status);
1271 break;
1272 case IOCP_CONNECT:
1273 complete_connect((connect_result_t *) result, status);
1274 break;
1275 case IOCP_WRITE:
1276 complete_write((write_result_t *) result, num_transferred, status);
1277 break;
1278 case IOCP_READ:
1279 complete_read((read_result_t *) result, num_transferred, status);
1280 break;
1281 default:
1282 assert(false);
1283 }
1284 }
1285
1286 void pni_iocp_drain_completions(iocp_t *iocp)
1287 {
1288 while (true) {
1289 DWORD timeout_ms = 0;
1290 DWORD num_transferred = 0;
1291 ULONG_PTR completion_key = 0;
1292 OVERLAPPED *overlapped = 0;
1293
1294 bool good_op = GetQueuedCompletionStatus (iocp->completion_port, &num_transferred,
1295 &completion_key, &overlapped, timeout_ms);
1296 if (!overlapped)
1297 return; // timed out
1298 iocp_result_t *result = (iocp_result_t *) overlapped;
1299 if (!completion_key)
1300 complete(result, good_op, num_transferred);
1301 }
1302 }
1303
1304 // returns: -1 on error, 0 on timeout, 1 successful completion
1305 // proactor layer uses completion_key, but we don't, so ignore those (shutdown in progress)
1306 int pni_iocp_wait_one(iocp_t *iocp, int timeout, pn_error_t *error) {
1307 DWORD win_timeout = (timeout < 0) ? INFINITE : (DWORD) timeout;
1308 DWORD num_transferred = 0;
1309 ULONG_PTR completion_key = 0;
1310 OVERLAPPED *overlapped = 0;
1311
1312 bool good_op = GetQueuedCompletionStatus (iocp->completion_port, &num_transferred,
1313 &completion_key, &overlapped, win_timeout);
1314 if (!overlapped)
1315 if (GetLastError() == WAIT_TIMEOUT)
1316 return 0;
1317 else {
1318 if (error)
1319 pni_win32_error(error, "GetQueuedCompletionStatus", GetLastError());
1320 return -1;
1321 }
1322
1323 if (completion_key)
1324 return pni_iocp_wait_one(iocp, timeout, error);
1325 iocp_result_t *result = (iocp_result_t *) overlapped;
1326 complete(result, good_op, num_transferred);
1327 return 1;
1328 }
1329
1330 // === Close (graceful and otherwise)
1331
1332 // zombie_list is for sockets transitioning out of iocp on their way to zero ops_in_progress
1333 // and fully closed.
1334
1335 static void zombie_list_add(iocpdesc_t *iocpd)
1336 {
1337 assert(iocpd->closing);
1338 if (!iocpd->ops_in_progress) {
1339 // No need to make a zombie.
1340 if (iocpd->socket != INVALID_SOCKET) {
1341 closesocket(iocpd->socket);
1342 iocpd->socket = INVALID_SOCKET;
1343 iocpd->read_closed = true;
1344 }
1345 return;
1346 }
1347 // Allow 2 seconds for graceful shutdown before releasing socket resource.
1348 iocpd->reap_time = pn_proactor_now_64() + 2000;
1349 pn_list_add(iocpd->iocp->zombie_list, iocpd);
1350 }
1351
1352 static void reap_check(iocpdesc_t *iocpd)
1353 {
1354 if (iocpd->closing && !iocpd->ops_in_progress) {
1355 if (iocpd->socket != INVALID_SOCKET) {
1356 closesocket(iocpd->socket);
1357 iocpd->socket = INVALID_SOCKET;
1358 }
1359 pn_list_remove(iocpd->iocp->zombie_list, iocpd);
1360 // iocpd is decref'ed and possibly released
1361 }
1362 }
1363
1364 void pni_iocp_reap_check(iocpdesc_t *iocpd) {
1365 reap_check(iocpd);
1366 }
1367
1368 pn_timestamp_t pni_zombie_deadline(iocp_t *iocp)
1369 {
1370 if (pn_list_size(iocp->zombie_list)) {
1371 iocpdesc_t *iocpd = (iocpdesc_t *) pn_list_get(iocp->zombie_list, 0);
1372 return iocpd->reap_time;
1373 }
1374 return 0;
1375 }
1376
1377 void pni_zombie_check(iocp_t *iocp, pn_timestamp_t now)
1378 {
1379 pn_list_t *zl = iocp->zombie_list;
1380 // Look for stale zombies that should have been reaped by "now"
1381 for (size_t idx = 0; idx < pn_list_size(zl); idx++) {
1382 iocpdesc_t *iocpd = (iocpdesc_t *) pn_list_get(zl, idx);
1383 if (iocpd->reap_time > now)
1384 return;
1385 if (iocpd->socket == INVALID_SOCKET)
1386 continue;
1387 if (iocp->iocp_trace)
1388 iocp_log("async close: graceful close timeout exceeded\n");
1389 closesocket(iocpd->socket);
1390 iocpd->socket = INVALID_SOCKET;
1391 iocpd->read_closed = true;
1392 // outstanding ops should complete immediately now
1393 }
1394 }
1395
1396 static void drain_zombie_completions(iocp_t *iocp)
1397 {
1398 // No more pn_selector_select() from App, but zombies still need care and feeding
1399 // until their outstanding async actions complete.
1400 pni_iocp_drain_completions(iocp);
1401
1402 // Discard any that have no pending async IO
1403 size_t sz = pn_list_size(iocp->zombie_list);
1404 for (size_t idx = 0; idx < sz;) {
1405 iocpdesc_t *iocpd = (iocpdesc_t *) pn_list_get(iocp->zombie_list, idx);
1406 if (!iocpd->ops_in_progress) {
1407 pn_list_del(iocp->zombie_list, idx, 1);
1408 sz--;
1409 } else {
1410 idx++;
1411 }
1412 }
1413
1414 unsigned shutdown_grace = 2000;
1415 char *override = getenv("PN_SHUTDOWN_GRACE");
1416 if (override) {
1417 int grace = atoi(override);
1418 if (grace > 0 && grace < 60000)
1419 shutdown_grace = (unsigned) grace;
1420 }
1421 pn_timestamp_t now = pn_proactor_now_64();
1422 pn_timestamp_t deadline = now + shutdown_grace;
1423
1424 while (pn_list_size(iocp->zombie_list)) {
1425 if (now >= deadline)
1426 break;
1427 int rv = pni_iocp_wait_one(iocp, deadline - now, NULL);
1428 if (rv < 0) {
1429 iocp_log("unexpected IOCP failure on Proton IO shutdown %d\n", GetLastError());
1430 break;
1431 }
1432 now = pn_proactor_now_64();
1433 }
1434 if (now >= deadline && pn_list_size(iocp->zombie_list) && iocp->iocp_trace)
1435 // Should only happen if really slow TCP handshakes, i.e. total network failure
1436 iocp_log("network failure on Proton shutdown\n");
1437 }
1438
1439 static void zombie_list_hard_close_all(iocp_t *iocp)
1440 {
1441 pni_iocp_drain_completions(iocp);
1442 size_t zs = pn_list_size(iocp->zombie_list);
1443 for (size_t i = 0; i < zs; i++) {
1444 iocpdesc_t *iocpd = (iocpdesc_t *) pn_list_get(iocp->zombie_list, i);
1445 if (iocpd->socket != INVALID_SOCKET) {
1446 closesocket(iocpd->socket);
1447 iocpd->socket = INVALID_SOCKET;
1448 iocpd->read_closed = true;
1449 iocpd->write_closed = true;
1450 }
1451 }
1452 pni_iocp_drain_completions(iocp);
1453
1454 // Zombies should be all gone. Do a sanity check.
1455 zs = pn_list_size(iocp->zombie_list);
1456 int remaining = 0;
1457 int ops = 0;
1458 for (size_t i = 0; i < zs; i++) {
1459 iocpdesc_t *iocpd = (iocpdesc_t *) pn_list_get(iocp->zombie_list, i);
1460 remaining++;
1461 ops += iocpd->ops_in_progress;
1462 }
1463 if (remaining)
1464 iocp_log("Proton: %d unfinished close operations (ops count = %d)\n", remaining, ops);
1465 }
1466
1467 static void iocp_shutdown(iocpdesc_t *iocpd)
1468 {
1469 if (iocpd->socket == INVALID_SOCKET)
1470 return; // Hard close in progress
1471 if (shutdown(iocpd->socket, SD_SEND)) {
1472 int err = WSAGetLastError();
1473 if (err != WSAECONNABORTED && err != WSAECONNRESET && err != WSAENOTCONN)
1474 if (iocpd->iocp->iocp_trace)
1475 iocp_log("socket shutdown failed %d\n", err);
1476 }
1477 iocpd->write_closed = true;
1478 }
1479
1480 void pni_iocp_begin_close(iocpdesc_t *iocpd)
1481 {
1482 assert (!iocpd->closing);
1483 if (is_listener(iocpd)) {
1484 // Listening socket is easy. Close the socket which will cancel async ops.
1485 pn_socket_t old_sock = iocpd->socket;
1486 iocpd->socket = INVALID_SOCKET;
1487 iocpd->closing = true;
1488 iocpd->read_closed = true;
1489 iocpd->write_closed = true;
1490 closesocket(old_sock);
1491 // Pending accepts will now complete. Zombie can die when all consumed.
1492 zombie_list_add(iocpd);
1493 } else {
1494 // Continue async operation looking for graceful close confirmation or timeout.
1495 pn_socket_t old_sock = iocpd->socket;
1496 iocpd->closing = true;
1497 if (!iocpd->write_closed && !write_in_progress(iocpd))
1498 iocp_shutdown(iocpd);
1499 zombie_list_add(iocpd);
1500 }
1501 }
1502
1503
1504 // === iocp_t
1505
1506 #define pni_iocp_hashcode NULL
1507 #define pni_iocp_compare NULL
1508 #define pni_iocp_inspect NULL
1509
1510 void pni_iocp_initialize(void *obj)
1511 {
1512 iocp_t *iocp = (iocp_t *) obj;
1513 memset(iocp, 0, sizeof(iocp_t));
1514 pni_shared_pool_create(iocp);
1515 iocp->completion_port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
1516 assert(iocp->completion_port != NULL);
1517 iocp->zombie_list = pn_list(PN_OBJECT, 0);
1518 iocp->iocp_trace = false;
1519 }
1520
1521 void pni_iocp_finalize(void *obj)
1522 {
1523 iocp_t *iocp = (iocp_t *) obj;
1524 // Move sockets to closed state
1525 drain_zombie_completions(iocp); // Last chance for graceful close
1526 zombie_list_hard_close_all(iocp);
1527 CloseHandle(iocp->completion_port); // This cancels all our async ops
1528 iocp->completion_port = NULL;
1529 // Now safe to free everything that might be touched by a former async operation.
1530 pn_free(iocp->zombie_list);
1531 pni_shared_pool_free(iocp);
1532 }
1533
1534 iocp_t *pni_iocp()
1535 {
1536 static const pn_cid_t CID_pni_iocp = CID_pn_void;
1537 static const pn_class_t clazz = PN_CLASS(pni_iocp);
1538 iocp_t *iocp = (iocp_t *) pn_class_new(&clazz, sizeof(iocp_t));
1539 return iocp;
1540 }
1541
1542 }
1543
1544
1545 // ======================================================================
1546 // Proton Proactor support
1547 // ======================================================================
1548
1549 #include "core/logger_private.h"
1550 #include "proactor-internal.h"
1551
1552 class csguard {
1553 public:
1554 csguard(CRITICAL_SECTION *cs) : cs_(cs), set_(true) { EnterCriticalSection(cs_); }
1555 ~csguard() { if (set_) LeaveCriticalSection(cs_); }
1556 void release() {
1557 if (set_) {
1558 set_ = false;
1559 LeaveCriticalSection(cs_);
1560 }
1561 }
1562 private:
1563 LPCRITICAL_SECTION cs_;
1564 bool set_;
1565 };
1566
1567
1568 // Get string from error status
1569 std::string errno_str2(DWORD status) {
1570 char buf[512];
1571 if (FormatMessage(FORMAT_MESSAGE_MAX_WIDTH_MASK | FORMAT_MESSAGE_FROM_SYSTEM,
1572 0, status, 0, buf, sizeof(buf), 0))
1573 return std::string(buf);
1574 return std::string("internal proactor error");
1575 }
1576
1577
1578 std::string errno_str(const std::string& msg, bool is_wsa) {
1579 DWORD e = is_wsa ? WSAGetLastError() : GetLastError();
1580 return msg + ": " + errno_str2(e);
1581 }
1582
1583
1584
1585 using namespace pn_experimental;
1586
1587 static int pgetaddrinfo(const char *host, const char *port, int flags, struct addrinfo **res)
1588 {
1589 struct addrinfo hints = { 0 };
1590 hints.ai_family = AF_UNSPEC;
1591 hints.ai_socktype = SOCK_STREAM;
1592 hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG | flags;
1593 return getaddrinfo(host, port, &hints, res) ? WSAGetLastError() : 0;
1594 }
1595
1596 const char *COND_NAME = "proactor";
1597 PN_HANDLE(PN_PROACTOR)
1598
1599 // The number of times a connection event batch may be replenished for
1600 // a thread between calls to wait().
1601 // TODO: consider some instrumentation to determine an optimal number
1602 // or switch to cpu time based limit.
1603 #define HOG_MAX 3
1604
1605 /* pn_proactor_t and pn_listener_t are plain C structs with normal memory management.
1606 Class definitions are for identification as pn_event_t context only.
1607 */
1608 PN_STRUCT_CLASSDEF(pn_proactor)
1609 PN_STRUCT_CLASSDEF(pn_listener)
1610
1611 /* Completion serialization context common to connection and listener. */
1612 /* And also the reaper singleton (which has no socket */
1613
1614 typedef enum {
1615 PROACTOR,
1616 PCONNECTION,
1617 LISTENER,
1618 WAKEABLE } pcontext_type_t;
1619
1620 typedef struct pcontext_t {
1621 CRITICAL_SECTION cslock;
1622 pn_proactor_t *proactor; /* Immutable */
1623 void *owner; /* Instance governed by the context */
1624 pcontext_type_t type;
1625 bool working;
1626 bool wake_pending;
1627 int completion_ops; // uncompleted ops that are not socket IO related
1628 struct pcontext_t *wake_next; // wake list, guarded by proactor eventfd_mutex
1629 bool closing;
1630 // Next 4 are protected by the proactor mutex
1631 struct pcontext_t* next; /* Protected by proactor.mutex */
1632 struct pcontext_t* prev; /* Protected by proactor.mutex */
1633 int disconnect_ops; /* ops remaining before disconnect complete */
1634 bool disconnecting; /* pn_proactor_disconnect */
1635 } pcontext_t;
1636
1637 static void pcontext_init(pcontext_t *ctx, pcontext_type_t t, pn_proactor_t *p, void *o) {
1638 memset(ctx, 0, sizeof(*ctx));
1639 InitializeCriticalSectionAndSpinCount(&ctx->cslock, 4000);
1640 ctx->proactor = p;
1641 ctx->owner = o;
1642 ctx->type = t;
1643 }
1644
1645 static void pcontext_finalize(pcontext_t* ctx) {
1646 DeleteCriticalSection(&ctx->cslock);
1647 }
1648
1649 typedef struct psocket_t {
1650 iocpdesc_t *iocpd; /* NULL if reaper, or socket open failure. */
1651 pn_listener_t *listener; /* NULL for a connection socket */
1652 pn_netaddr_t listen_addr; /* Not filled in for connection sockets */
1653 char addr_buf[PN_MAX_ADDR];
1654 const char *host, *port;
1655 bool is_reaper;
1656 } psocket_t;
1657
1658 static void psocket_init(psocket_t* ps, pn_listener_t *listener, bool is_reaper, const char *addr) {
1659 ps->is_reaper = is_reaper;
1660 if (is_reaper) return;
1661 ps->listener = listener;
1662 pni_parse_addr(addr, ps->addr_buf, sizeof(ps->addr_buf), &ps->host, &ps->port);
1663 }
1664
1665 struct pn_proactor_t {
1666 pcontext_t context;
1667 CRITICAL_SECTION write_lock;
1668 CRITICAL_SECTION timer_lock;
1669 CRITICAL_SECTION bind_lock;
1670 HANDLE timer_queue;
1671 HANDLE timeout_timer;
1672 iocp_t *iocp;
1673 class reaper *reaper;
1674 pn_collector_t *collector;
1675 pcontext_t *contexts; /* in-use contexts for PN_PROACTOR_INACTIVE and cleanup */
1676 pn_event_batch_t batch;
1677 size_t disconnects_pending; /* unfinished proactor disconnects*/
1678
1679 // need_xxx flags indicate we should generate PN_PROACTOR_XXX on the next update_batch()
1680 bool need_interrupt;
1681 bool need_inactive;
1682 bool need_timeout;
1683 bool timeout_set; /* timeout has been set by user and not yet cancelled or generated event */
1684 bool timeout_processed; /* timout event dispatched in the most recent event batch */
1685 bool delayed_interrupt;
1686 bool shutting_down;
1687 };
1688
1689 typedef struct pconnection_t {
1690 psocket_t psocket;
1691 pcontext_t context;
1692 pn_connection_driver_t driver;
1693 std::queue<iocp_result_t *> *completion_queue;
1694 std::queue<iocp_result_t *> *work_queue;
1695 pn_condition_t *disconnect_condition;
1696 pn_event_batch_t batch;
1697 int wake_count;
1698 int hog_count; // thread hogging limiter
1699 bool server; /* accept, not connect */
1700 bool started;
1701 bool connecting;
1702 bool tick_pending;
1703 bool queued_disconnect; /* deferred from pn_proactor_disconnect() */
1704 bool bound;
1705 bool stop_timer_required;
1706 bool can_wake;
1707 HANDLE tick_timer;
1708 struct pn_netaddr_t local, remote; /* Actual addresses */
1709 struct addrinfo *addrinfo; /* Resolved address list */
1710 struct addrinfo *ai; /* Current connect address */
1711 } pconnection_t;
1712
1713 struct pn_listener_t {
1714 psocket_t *psockets; /* Array of listening sockets */
1715 size_t psockets_size;
1716 pcontext_t context;
1717 std::queue<accept_result_t *> *pending_accepts; // sockets awaiting a pn_listener_accept
1718 int pending_events; // number of PN_LISTENER_ACCEPT events to be delivered
1719 pn_condition_t *condition;
1720 pn_collector_t *collector;
1721 pn_event_batch_t batch;
1722 pn_record_t *attachments;
1723 void *listener_context;
1724 size_t backlog;
1725 bool close_dispatched;
1726 };
1727
1728
1729 static bool proactor_remove(pcontext_t *ctx);
1730 static void listener_done(pn_listener_t *l);
1731 static bool proactor_update_batch(pn_proactor_t *p);
1732 static pn_event_batch_t *listener_process(pn_listener_t *l, iocp_result_t *result);
1733 static void recycle_result(accept_result_t *accept_result);
1734 static void proactor_add(pcontext_t *p);
1735 static void release_pending_accepts(pn_listener_t *l);
1736 static void proactor_shutdown(pn_proactor_t *p);
1737
1738 static void post_completion(iocp_t *iocp, ULONG_PTR arg1, void *arg2) {
1739 // Despite the vagueness of the official documentation, the
1740 // following args to Post are passed undisturbed and unvalidated
1741 // to GetQueuedCompletionStatus(). In particular, arg2 does not
1742 // have to be an OVERLAPPED struct and may be NULL.
1743
1744 DWORD nxfer = 0; // We could pass this through too if needed.
1745 PostQueuedCompletionStatus(iocp->completion_port, nxfer, arg1, (LPOVERLAPPED) arg2);
1746 }
1747
1748 static inline bool is_write_result(iocp_result_t *r) {
1749 return r && r->type == IOCP_WRITE;
1750 }
1751
1752 static inline bool is_read_result(iocp_result_t *r) {
1753 return r && r->type == IOCP_READ;
1754 }
1755
1756 static inline bool is_connect_result(iocp_result_t *r) {
1757 return r && r->type == IOCP_CONNECT;
1758 }
1759
1760 // From old io.c
1761 static void pni_configure_sock_2(pn_socket_t sock) {
1762 //
1763 // Disable the Nagle algorithm on TCP connections.
1764 //
1765
1766 int flag = 1;
1767 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(flag)) != 0) {
1768 //TODO: log/err
1769 }
1770
1771 u_long nonblock = 1;
1772 if (ioctlsocket(sock, FIONBIO, &nonblock)) {
1773 // TODO: log/err
1774 }
1775 }
1776
1777 static LPFN_CONNECTEX lookup_connect_ex2(SOCKET s)
1778 {
1779 GUID guid = WSAID_CONNECTEX;
1780 DWORD bytes = 0;
1781 LPFN_CONNECTEX fn;
1782 WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid),
1783 &fn, sizeof(fn), &bytes, NULL, NULL);
1784 assert(fn);
1785 return fn;
1786 }
1787
1788
1789 // File descriptor wrapper that calls ::close in destructor.
1790 class unique_socket {
1791 public:
1792 unique_socket(pn_socket_t socket) : socket_(socket) {}
1793 ~unique_socket() { if (socket_ != INVALID_SOCKET) ::closesocket(socket_); }
1794 operator pn_socket_t() const { return socket_; }
1795 pn_socket_t release() { pn_socket_t ret = socket_; socket_ = INVALID_SOCKET; return ret; }
1796
1797 protected:
1798 pn_socket_t socket_;
1799 };
1800
1801 void do_complete(iocp_result_t *result) {
1802 iocpdesc_t *iocpd = result->iocpd; // connect result gets deleted
1803 switch (result->type) {
1804
1805 case IOCP_ACCEPT:
1806 /* accept is now processed inline to do in parallel, except on teardown */
1807 assert(iocpd->closing);
1808 complete_accept((accept_result_t *) result, result->status); // free's result and retires new_sock
1809 break;
1810 case IOCP_CONNECT:
1811 complete_connect((connect_result_t *) result, result->status);
1812 break;
1813 case IOCP_WRITE:
1814 complete_write((write_result_t *) result, result->num_transferred, result->status);
1815 break;
1816 case IOCP_READ:
1817 complete_read((read_result_t *) result, result->num_transferred, result->status);
1818 break;
1819 default:
1820 assert(false);
1821 }
1822
1823 iocpd->ops_in_progress--; // Set in each begin_xxx call
1824 }
1825
1826
1827 static inline pconnection_t *as_pconnection_t(psocket_t* ps) {
1828 return !(ps->is_reaper || ps->listener) ? (pconnection_t*)ps : NULL;
1829 }
1830
1831 static inline pn_listener_t *as_listener(psocket_t* ps) {
1832 return ps->listener;
1833 }
1834
1835 static inline pconnection_t *pcontext_pconnection(pcontext_t *c) {
1836 return c->type == PCONNECTION ?
1837 containerof(c, pconnection_t, context) : NULL;
1838 }
1839 static inline pn_listener_t *pcontext_listener(pcontext_t *c) {
1840 return c->type == LISTENER ?
1841 containerof(c, pn_listener_t, context) : NULL;
1842 }
1843
1844 static pcontext_t *psocket_context(psocket_t *ps) {
1845 if (ps->listener)
1846 return &ps->listener->context;
1847 pconnection_t *pc = as_pconnection_t(ps);
1848 return &pc->context;
1849 }
1850
1851
1852 // Call wih lock held
1853 static inline void wake_complete(pcontext_t *ctx) {
1854 ctx->wake_pending = false;
1855 ctx->completion_ops--;
1856 }
1857
1858 // Call wih lock held
1859 static void wakeup(psocket_t *ps) {
1860 pcontext_t *ctx = psocket_context(ps);
1861 if (!ctx->working && !ctx->wake_pending) {
1862 ctx->wake_pending = true;
1863 ctx->completion_ops++;
1864 post_completion(ctx->proactor->iocp, psocket_wakeup_key, ps);
1865 }
1866 }
1867
1868 // Call wih lock held
1869 static inline void proactor_wake_complete(pn_proactor_t *p) {
1870 wake_complete(&p->context);
1871 }
1872
1873 // Call wih lock held
1874 static void proactor_wake(pn_proactor_t *p) {
1875 if (!p->context.working && !p->context.wake_pending) {
1876 p->context.wake_pending = true;
1877 p->context.completion_ops++;
1878 post_completion(p->iocp, proactor_wake_key, p);
1879 }
1880 }
1881
1882 VOID CALLBACK reap_check_cb(PVOID arg, BOOLEAN /* ignored*/ );
1883
1884 // Serialize handling listener and connection closing IO completions
1885 // after the engine has lost interest. A temporary convenience while
1886 // using the old single threaded iocp/io/select driver code.
1887 class reaper {
1888 public:
1889 reaper(pn_proactor_t *p, CRITICAL_SECTION *wlock, iocp_t *iocp)
1890 : iocp_(iocp), global_wlock_(wlock), timer_(NULL), running(true) {
1891 InitializeCriticalSectionAndSpinCount(&lock_, 4000);
1892 timer_queue_ = CreateTimerQueue();
1893 if (!timer_queue_) {
1894 perror("CreateTimerQueue");
1895 abort();
1896 }
1897 }
1898
1899 // Connection or listener lock must also be held by caller.
1900 bool add(iocpdesc_t *iocpd) {
1901 if (!iocpd) return false;
1902 csguard g(&lock_);
1903 if (iocpd->closing) return false;
1904 bool rval = !iocpd->ops_in_progress;
1905 pni_iocp_begin_close(iocpd); // sets iocpd->closing
1906 pn_decref(iocpd); // may still be ref counted on zombie list
1907 reap_timer();
1908 return rval;
1909 }
1910
1911 // For cases where the close will be immediate. I.E. after a failed
1912 // connection attempt where there is no follow-on IO.
1913 void fast_reap(iocpdesc_t *iocpd) {
1914 assert(iocpd && iocpd->ops_in_progress == 0 && !iocpd->closing);
1915 csguard g(&lock_);
1916 pni_iocp_begin_close(iocpd);
1917 pn_decref(iocpd);
1918 }
1919
1920 bool process(iocp_result_t *result) {
1921 // No queue of completions for the reaper. Just process
1922 // serialized by the lock assuming all actions are "short".
1923 // That may be wrong, and if so the real fix is not a
1924 // consumer/producer setup but just replace the reaper with a
1925 // multi threaded alternative.
1926 csguard g(&lock_);
1927 iocpdesc_t *iocpd = result->iocpd;
1928 if (is_write_result(result)) {
1929 csguard wg(global_wlock_);
1930 do_complete(result);
1931 }
1932 else do_complete(result);
1933 // result may now be NULL
1934 bool rval = (iocpd->ops_in_progress == 0);
1935 pni_iocp_reap_check(iocpd);
1936 return rval;
1937 }
1938
1939 // Called when all competing threads have terminated except our own reap_check timer.
1940 void final_shutdown() {
1941 running = false;
1942 DeleteTimerQueueEx(timer_queue_, INVALID_HANDLE_VALUE);
1943 // No pending or active timers from thread pool remain. Truly single threaded now.
1944 pn_free((void *) iocp_); // calls pni_iocp_finalize(); cleans up all sockets, completions, completion port.
1945 DeleteCriticalSection(&lock_);
1946 }
1947
1948 void reap_check() {
1949 csguard g(&lock_);
1950 DeleteTimerQueueTimer(timer_queue_, timer_, NULL);
1951 timer_ = NULL;
1952 reap_timer();
1953 }
1954
1955
1956 private:
1957 void reap_timer() {
1958 // Call with lock
1959 if (timer_ || !running)
1960 return;
1961 int64_t now = pn_proactor_now_64();
1962 pni_zombie_check(iocp_, now);
1963 int64_t zd = pni_zombie_deadline(iocp_);
1964 if (zd) {
1965 DWORD tm = (zd > now) ? zd - now : 1;
1966 if (!CreateTimerQueueTimer(&timer_, timer_queue_, reap_check_cb, this, tm,
1967 0, WT_EXECUTEONLYONCE)) {
1968 perror("CreateTimerQueueTimer");
1969 abort();
1970 }
1971 }
1972 }
1973
1974 iocp_t *iocp_;
1975 CRITICAL_SECTION lock_;
1976 CRITICAL_SECTION *global_wlock_;
1977 HANDLE timer_queue_;
1978 HANDLE timer_;
1979 bool running;
1980 };
1981
1982 VOID CALLBACK reap_check_cb(PVOID arg, BOOLEAN /* ignored*/ ) {
1983 // queue timer callback
1984 reaper *r = static_cast<reaper *>(arg);
1985 r->reap_check();
1986 }
1987
1988 static void listener_begin_close(pn_listener_t* l);
1989 static void connect_step_done(pconnection_t *pc, connect_result_t *result);
1990 static pn_event_t *listener_batch_next(pn_event_batch_t *batch);
1991 static pn_event_t *proactor_batch_next(pn_event_batch_t *batch);
1992 static pn_event_t *pconnection_batch_next(pn_event_batch_t *batch);
1993
1994
1995 static inline pn_proactor_t *batch_proactor(pn_event_batch_t *batch) {
1996 return (batch->next_event == proactor_batch_next) ?
1997 containerof(batch, pn_proactor_t, batch) : NULL;
1998 }
1999
2000 static inline pn_listener_t *batch_listener(pn_event_batch_t *batch) {
2001 return (batch->next_event == listener_batch_next) ?
2002 containerof(batch, pn_listener_t, batch) : NULL;
2003 }
2004
2005 static inline pconnection_t *batch_pconnection(pn_event_batch_t *batch) {
2006 return (batch->next_event == pconnection_batch_next) ?
2007 containerof(batch, pconnection_t, batch) : NULL;
2008 }
2009
2010 static inline bool pconnection_has_event(pconnection_t *pc) {
2011 return pn_connection_driver_has_event(&pc->driver);
2012 }
2013
2014 static inline bool listener_has_event(pn_listener_t *l) {
2015 return pn_collector_peek(l->collector);
2016 }
2017
2018 static inline bool proactor_has_event(pn_proactor_t *p) {
2019 return pn_collector_peek(p->collector);
2020 }
2021
2022 static void psocket_error_str(psocket_t *ps, const char *msg, const char* what) {
2023 if (ps->is_reaper)
2024 return;
2025 if (!ps->listener) {
2026 pn_connection_driver_t *driver = &as_pconnection_t(ps)->driver;
2027 pn_connection_driver_bind(driver); /* Bind so errors will be reported */
2028 pni_proactor_set_cond(pn_transport_condition(driver->transport), what, ps->host, ps->port, msg);
2029 pn_connection_driver_close(driver);
2030 } else {
2031 pn_listener_t *l = as_listener(ps);
2032 pni_proactor_set_cond(l->condition, what, ps->host, ps->port, msg);
2033 listener_begin_close(l);
2034 }
2035 }
2036
2037 static void psocket_error(psocket_t *ps, int err, const char* what) {
2038 psocket_error_str(ps, errno_str2(err).c_str(), what);
2039 }
2040
2041
2042
2043 // ========================================================================
2044 // pconnection
2045 // ========================================================================
2046
2047 /* Make a pn_class for pconnection_t since it is attached to a pn_connection_t record */
2048 #define CID_pconnection CID_pn_object
2049 #define pconnection_inspect NULL
2050 #define pconnection_initialize NULL
2051 #define pconnection_hashcode NULL
2052 #define pconnection_compare NULL
2053
2054 static void pconnection_finalize(void *vp_pconnection) {
2055 pconnection_t *pc = (pconnection_t*)vp_pconnection;
2056 pcontext_finalize(&pc->context);
2057 }
2058
2059 static const pn_class_t pconnection_class = PN_CLASS(pconnection);
2060
2061 static const char *pconnection_setup(pconnection_t *pc, pn_proactor_t *p, pn_connection_t *c, pn_transport_t *t, bool server, const char *addr)
2062 {
2063 if (pn_connection_driver_init(&pc->driver, c, t) != 0) {
2064 free(pc);
2065 return "pn_connection_driver_init failure";
2066 }
2067 {
2068 csguard g(&p->bind_lock);
2069 pn_record_t *r = pn_connection_attachments(pc->driver.connection);
2070 if (pn_record_get(r, PN_PROACTOR)) {
2071 pn_connection_driver_destroy(&pc->driver);
2072 free(pc);
2073 return "pn_connection_t already in use";
2074 }
2075 pn_record_def(r, PN_PROACTOR, &pconnection_class);
2076 pn_record_set(r, PN_PROACTOR, pc);
2077 pc->bound = true;
2078 pc->can_wake = true;
2079 }
2080
2081 pc->completion_queue = new std::queue<iocp_result_t *>();
2082 pc->work_queue = new std::queue<iocp_result_t *>();
2083 pcontext_init(&pc->context, PCONNECTION, p, pc);
2084
2085 psocket_init(&pc->psocket, NULL, false, addr);
2086 pc->batch.next_event = pconnection_batch_next;
2087 if (server) {
2088 pn_transport_set_server(pc->driver.transport);
2089 }
2090
2091 pn_decref(pc); /* Will be deleted when the connection is */
2092 return NULL;
2093 }
2094
2095 // Either stops a timer before firing or returns after the callback has
2096 // completed (in the threadpool thread). Never "in doubt".
2097 static bool stop_timer(HANDLE tqueue, HANDLE *timer) {
2098 if (!*timer) return true;
2099 if (DeleteTimerQueueTimer(tqueue, *timer, INVALID_HANDLE_VALUE)) {
2100 *timer = NULL;
2101 return true;
2102 }
2103 return false; // error
2104 }
2105
2106 static bool start_timer(HANDLE tqueue, HANDLE *timer, WAITORTIMERCALLBACK cb, void *cb_arg, DWORD time) {
2107 if (*timer) {
2108 // TODO: log err
2109 return false;
2110 }
2111 return CreateTimerQueueTimer(timer, tqueue, cb, cb_arg, time, 0, WT_EXECUTEONLYONCE);
2112 }
2113
2114 VOID CALLBACK tick_timer_cb(PVOID arg, BOOLEAN /* ignored*/ ) {
2115 pconnection_t *pc = (pconnection_t *) arg;
2116 csguard g(&pc->context.cslock);
2117 if (pc->psocket.iocpd && !pc->psocket.iocpd->closing) {
2118 pc->tick_pending = true;
2119 wakeup(&pc->psocket);
2120 }
2121 }
2122
2123
2124 // Call with no lock held or stop_timer and callback may deadlock
2125 static void pconnection_tick(pconnection_t *pc) {
2126 pn_transport_t *t = pc->driver.transport;
2127 if (pn_transport_get_idle_timeout(t) || pn_transport_get_remote_idle_timeout(t)) {
2128 if(!stop_timer(pc->context.proactor->timer_queue, &pc->tick_timer)) {
2129 // TODO: handle error
2130 }
2131 uint64_t now = pn_proactor_now_64();
2132 uint64_t next = pn_transport_tick(t, now);
2133 if (next) {
2134 if (!start_timer(pc->context.proactor->timer_queue, &pc->tick_timer, tick_timer_cb, pc, next - now)) {
2135 // TODO: handle error
2136 }
2137 }
2138 }
2139 }
2140
2141 static pconnection_t *get_pconnection(pn_connection_t* c) {
2142 if (!c) return NULL;
2143 pn_record_t *r = pn_connection_attachments(c);
2144 return (pconnection_t*) pn_record_get(r, PN_PROACTOR);
2145 }
2146
2147
2148 pn_listener_t *pn_event_listener(pn_event_t *e) {
2149 return (pn_event_class(e) == PN_CLASSCLASS(pn_listener)) ? (pn_listener_t*)pn_event_context(e) : NULL;
2150 }
2151
2152 pn_proactor_t *pn_event_proactor(pn_event_t *e) {
2153 if (pn_event_class(e) == PN_CLASSCLASS(pn_proactor)) return (pn_proactor_t*)pn_event_context(e);
2154 pn_listener_t *l = pn_event_listener(e);
2155 if (l) return l->context.proactor;
2156 pn_connection_t *c = pn_event_connection(e);
2157 if (c) return pn_connection_proactor(pn_event_connection(e));
2158 return NULL;
2159 }
2160
2161 // Call after successful accept
2162 static void set_sock_names(pconnection_t *pc) {
2163 // This works. Note possible use of GetAcceptExSockaddrs()
2164 pn_socket_t sock = pc->psocket.iocpd->socket;
2165 socklen_t len = sizeof(pc->local.ss);
2166 getsockname(sock, (struct sockaddr*)&pc->local.ss, &len);
2167 len = sizeof(pc->remote.ss);
2168 getpeername(sock, (struct sockaddr*)&pc->remote.ss, &len);
2169 }
2170
2171
2172 // Call with lock held when closing and transitioning away from working context
2173 static inline bool pconnection_can_free(pconnection_t *pc) {
2174 return pc->psocket.iocpd == NULL && pc->context.completion_ops == 0
2175 && !pc->stop_timer_required && !pconnection_has_event(pc) && !pc->queued_disconnect;
2176 }
2177
2178 static void pconnection_final_free(pconnection_t *pc) {
2179 if (pc->addrinfo) {
2180 freeaddrinfo(pc->addrinfo);
2181 }
2182 pn_condition_free(pc->disconnect_condition);
2183 pn_incref(pc); /* Make sure we don't do a circular free */
2184 pn_connection_driver_destroy(&pc->driver);
2185 pn_decref(pc);
2186 /* Now pc is freed iff the connection is, otherwise remains till the pn_connection_t is freed. */
2187 }
2188
2189 // Call with lock held or from forced shutdown
2190 static void pconnection_begin_close(pconnection_t *pc) {
2191 if (!pc->context.closing) {
2192 pc->context.closing = true;
2193 pn_connection_driver_close(&pc->driver);
2194 pc->stop_timer_required = true;
2195 if (pc->context.proactor->reaper->add(pc->psocket.iocpd))
2196 pc->psocket.iocpd = NULL;
2197 wakeup(&pc->psocket);
2198 }
2199 }
2200
2201 // call with lock held. return true if caller must call pconnection_final_free()
2202 static bool pconnection_cleanup(pconnection_t *pc) {
2203 delete pc->completion_queue;
2204 delete pc->work_queue;
2205 return proactor_remove(&pc->context);
2206 }
2207
2208 static inline bool pconnection_work_pending(pconnection_t *pc) {
2209 if (pc->completion_queue->size() || pc->wake_count || pc->tick_pending || pc->queued_disconnect)
2210 return true;
2211 if (!pc->started)
2212 return false;
2213 pn_bytes_t wbuf = pn_connection_driver_write_buffer(&pc->driver);
2214 return (wbuf.size > 0 && (pc->psocket.iocpd->events & PN_WRITABLE));
2215 }
2216
2217 // Return true unless reaped
2218 static bool pconnection_write(pconnection_t *pc, pn_bytes_t wbuf) {
2219 ssize_t n;
2220 bool wouldblock;
2221 {
2222 csguard g(&pc->context.proactor->write_lock);
2223 n = pni_iocp_begin_write(pc->psocket.iocpd, wbuf.start, wbuf.size, &wouldblock, pc->psocket.iocpd->error);
2224 }
2225 if (n > 0) {
2226 pn_connection_driver_write_done(&pc->driver, n);
2227 } else if (n < 0 && !wouldblock) {
2228 psocket_error(&pc->psocket, WSAGetLastError(), "on write to");
2229 }
2230 else if (wbuf.size == 0 && pn_connection_driver_write_closed(&pc->driver)) {
2231 if (pc->context.proactor->reaper->add(pc->psocket.iocpd)) {
2232 pc->psocket.iocpd = NULL;
2233 return false;
2234 }
2235 }
2236 return true;
2237 }
2238
2239 // Queue the result (if any) for the one worker thread. Become the worker if possible.
2240 // NULL result is a wakeup or a topup.
2241 // topup signifies that the working thread is the caller looking for additional events.
2242 static pn_event_batch_t *pconnection_process(pconnection_t *pc, iocp_result_t *result, bool topup) {
2243 bool first = true;
2244 bool waking = false;
2245 bool tick_required = false;
2246 bool open = false;
2247
2248 while (true) {
2249 {
2250 csguard g(&pc->context.cslock);
2251 if (first) {
2252 first = false;
2253 if (result)
2254 pc->completion_queue->push(result);
2255 else if (!topup)
2256 wake_complete(&pc->context);
2257 if (!topup) {
2258 if (pc->context.working)
2259 return NULL;
2260 pc->context.working = true;
2261 }
2262 open = pc->started && !pc->connecting && !pc->context.closing;
2263 }
2264 else {
2265 // Just re-acquired lock after processing IO and engine work
2266 if (pconnection_has_event(pc))
2267 return &pc->batch;
2268
2269 if (!pconnection_work_pending(pc)) {
2270 pc->context.working = false;
2271 if (pn_connection_driver_finished(&pc->driver)) {
2272 pconnection_begin_close(pc);
2273 }
2274 if (pc->context.closing && pconnection_can_free(pc)) {
2275 if (pconnection_cleanup(pc)) {
2276 g.release();
2277 pconnection_final_free(pc);
2278 return NULL;
2279 } // else disconnect logic has the free obligation
2280 }
2281 return NULL;
2282 }
2283 }
2284
2285 if (pc->queued_disconnect) { // From pn_proactor_disconnect()
2286 pc->queued_disconnect = false;
2287 if (!pc->context.closing) {
2288 if (pc->disconnect_condition) {
2289 pn_condition_copy(pn_transport_condition(pc->driver.transport), pc->disconnect_condition);
2290 }
2291 pn_connection_driver_close(&pc->driver);
2292 }
2293 }
2294
2295 assert(pc->work_queue->empty());
2296 if (pc->completion_queue->size())
2297 std::swap(pc->work_queue, pc->completion_queue);
2298
2299 if (pc->wake_count) {
2300 waking = open && pc->can_wake && !pn_connection_driver_finished(&pc->driver);
2301 pc->wake_count = 0;
2302 }
2303 if (pc->tick_pending) {
2304 pc->tick_pending = false;
2305 if (open)
2306 tick_required = true;
2307 }
2308 }
2309
2310 // No lock
2311
2312 // Drain completions prior to engine work
2313 while (pc->work_queue->size()) {
2314 result = (iocp_result_t *) pc->work_queue->front();
2315 pc->work_queue->pop();
2316 if (result->iocpd->closing) {
2317 if (pc->context.proactor->reaper->process(result)) {
2318 pc->psocket.iocpd = NULL; // reaped
2319 open = false;
2320 }
2321 }
2322 else {
2323 if (is_write_result(result)) {
2324 csguard g(&pc->context.proactor->write_lock);
2325 do_complete(result);
2326 }
2327 else if (is_connect_result(result)) {
2328 connect_step_done(pc, (connect_result_t *) result);
2329 if (pc->psocket.iocpd && (pc->psocket.iocpd->events & PN_WRITABLE)) {
2330 pc->connecting = false;
2331 if (pc->started)
2332 open = true;
2333 }
2334 }
2335 else do_complete(result);
2336 }
2337 }
2338
2339 if (!open) {
2340 if (pc->stop_timer_required) {
2341 pc->stop_timer_required = false;
2342 // Do without context lock to avoid possible deadlock
2343 stop_timer(pc->context.proactor->timer_queue, &pc->tick_timer);
2344 }
2345 } else {
2346
2347 pn_rwbytes_t rbuf = pn_connection_driver_read_buffer(&pc->driver);
2348 pn_bytes_t wbuf = pn_connection_driver_write_buffer(&pc->driver);
2349
2350 /* Ticks and checking buffers can generate events, process before proceeding */
2351 bool ready = pconnection_has_event(pc);
2352 if (waking) {
2353 pn_connection_t *c = pc->driver.connection;
2354 pn_collector_put(pn_connection_collector(c), PN_OBJECT, c, PN_CONNECTION_WAKE);
2355 waking = false;
2356 }
2357 if (ready) {
2358 continue;
2359 }
2360
2361 if (wbuf.size >= 16384 && (pc->psocket.iocpd->events & PN_WRITABLE)) {
2362 if (!pconnection_write(pc, wbuf))
2363 continue;
2364 }
2365 if (rbuf.size > 0 && !pc->psocket.iocpd->read_in_progress) {
2366 bool wouldblock;
2367 ssize_t n = pni_iocp_recv(pc->psocket.iocpd, rbuf.start, rbuf.size, &wouldblock, pc->psocket.iocpd->error);
2368
2369 if (n > 0) {
2370 pn_connection_driver_read_done(&pc->driver, n);
2371 pconnection_tick(pc); /* check for tick changes. */
2372 tick_required = false;
2373 }
2374 else if (n == 0)
2375 pn_connection_driver_read_close(&pc->driver);
2376 else if (!wouldblock)
2377 psocket_error(&pc->psocket, WSAGetLastError(), "on read from");
2378 }
2379 if (!pc->psocket.iocpd->read_in_progress)
2380 start_reading(pc->psocket.iocpd);
2381
2382
2383 if (tick_required) {
2384 pconnection_tick(pc); /* check for tick changes. */
2385 tick_required = false;
2386 }
2387 wbuf = pn_connection_driver_write_buffer(&pc->driver);
2388 if (wbuf.size > 0 && (pc->psocket.iocpd->events & PN_WRITABLE)) {
2389 if (!pconnection_write(pc, wbuf))
2390 open = false;
2391 }
2392 }
2393
2394 if (topup)
2395 return NULL; // regardless if new events made available
2396 }
2397 }
2398
2399
2400 static pn_event_t *pconnection_batch_next(pn_event_batch_t *batch) {
2401 pconnection_t *pc = batch_pconnection(batch);
2402 pn_event_t *e = pn_connection_driver_next_event(&pc->driver);
2403 if (!e && ++pc->hog_count < HOG_MAX) {
2404 pconnection_process(pc, NULL, true); // top up
2405 e = pn_connection_driver_next_event(&pc->driver);
2406 }
2407 if (e && !pc->started && pn_event_type(e) == PN_CONNECTION_BOUND)
2408 pc->started = true; // SSL will be set up on return and safe to do IO with correct transport layers
2409 return e;
2410 }
2411
2412 static void pconnection_done(pconnection_t *pc) {
2413 {
2414 csguard g(&pc->context.cslock);
2415 pc->context.working = false;
2416 pc->hog_count = 0;
2417 if (pconnection_has_event(pc) || pconnection_work_pending(pc)) {
2418 wakeup(&pc->psocket);
2419 } else if (pn_connection_driver_finished(&pc->driver)) {
2420 pconnection_begin_close(pc);
2421 wakeup(&pc->psocket);
2422 }
2423 }
2424 }
2425
2426 static inline bool is_inactive(pn_proactor_t *p) {
2427 return (!p->contexts && !p->disconnects_pending && !p->timeout_set && !p->need_timeout && !p->shutting_down);
2428 }
2429
2430 // Call whenever transitioning from "definitely active" to "maybe inactive"
2431 static void wake_if_inactive(pn_proactor_t *p) {
2432 if (is_inactive(p)) {
2433 p->need_inactive = true;
2434 proactor_wake(p);
2435 }
2436 }
2437
2438 void pn_proactor_done(pn_proactor_t *p, pn_event_batch_t *batch) {
2439 pconnection_t *pc = batch_pconnection(batch);
2440 if (pc) {
2441 pconnection_done(pc);
2442 return;
2443 }
2444 pn_listener_t *l = batch_listener(batch);
2445 if (l) {
2446 listener_done(l);
2447 return;
2448 }
2449 pn_proactor_t *bp = batch_proactor(batch);
2450 if (bp == p) {
2451 csguard g(&p->context.cslock);
2452 p->context.working = false;
2453 if (p->delayed_interrupt) {
2454 p->delayed_interrupt = false;
2455 p->need_interrupt = true;
2456 }
2457 if (p->timeout_processed) {
2458 p->timeout_processed = false;
2459 wake_if_inactive(p);
2460 }
2461 if (proactor_update_batch(p))
2462 proactor_wake(p);
2463 return;
2464 }
2465 }
2466
2467 static void proactor_add_event(pn_proactor_t *p, pn_event_type_t t) {
2468 pn_collector_put(p->collector, PN_CLASSCLASS(pn_proactor), p, t);
2469 }
2470
2471 static pn_event_batch_t *proactor_process(pn_proactor_t *p) {
2472 csguard g(&p->context.cslock);
2473 proactor_wake_complete(p);
2474 if (!p->context.working) { /* Can generate proactor events */
2475 if (proactor_update_batch(p)) {
2476 p->context.working = true;
2477 return &p->batch;
2478 }
2479 }
2480 return NULL;
2481 }
2482
2483 static pn_event_batch_t *psocket_process(psocket_t *ps, iocp_result_t *result, reaper *rpr) {
2484 if (ps) {
2485 pconnection_t *pc = as_pconnection_t(ps);
2486 if (pc) {
2487 return pconnection_process(pc, result, false);
2488 } else {
2489 pn_listener_t *l = as_listener(ps);
2490 if (l)
2491 return listener_process(l, result);
2492 }
2493 }
2494 rpr->process(result);
2495 return NULL;
2496 }
2497
2498 static pn_event_batch_t *proactor_completion_loop(struct pn_proactor_t* p, bool can_block) {
2499 // Proact! Process inbound completions of async activity until one
2500 // of them provides a batch of events.
2501 while(true) {
2502 pn_event_batch_t *batch = NULL;
2503
2504 DWORD win_timeout = can_block ? INFINITE : 0;
2505 DWORD num_xfer = 0;
2506 ULONG_PTR completion_key = 0;
2507 OVERLAPPED *overlapped = 0;
2508
2509 bool good_op = GetQueuedCompletionStatus (p->iocp->completion_port, &num_xfer,
2510 &completion_key, &overlapped, win_timeout);
2511 if (!overlapped && !can_block && GetLastError() == WAIT_TIMEOUT)
2512 return NULL; // valid timeout
2513
2514 if (!good_op && !overlapped) {
2515 // Should never happen. shutdown?
2516 // We aren't expecting a timeout, closed completion port, or other error here.
2517 PN_LOG_DEFAULT(PN_SUBSYSTEM_EVENT, PN_LEVEL_CRITICAL, "%s", errno_str("Windows Proton proactor internal failure\n", false).c_str());
2518 abort();
2519 }
2520
2521 switch (completion_key) {
2522 case proactor_io: {
2523 // Normal IO case for connections and listeners
2524 iocp_result_t *result = (iocp_result_t *) overlapped;
2525 result->status = good_op ? 0 : GetLastError();
2526 result->num_transferred = num_xfer;
2527 psocket_t *ps = (psocket_t *) result->iocpd->active_completer;
2528 batch = psocket_process(ps, result, p->reaper);
2529 break;
2530 }
2531 // completion_key on our completion port is always null unless set by us
2532 // in PostQueuedCompletionStatus. In which case, we hijack the overlapped
2533 // data structure for our own use.
2534 case psocket_wakeup_key:
2535 batch = psocket_process((psocket_t *) overlapped, NULL, p->reaper);
2536 break;
2537 case proactor_wake_key:
2538 batch = proactor_process((pn_proactor_t *) overlapped);
2539 break;
2540 case recycle_accept_key:
2541 recycle_result((accept_result_t *) overlapped);
2542 break;
2543 default:
2544 break;
2545 }
2546 if (batch) return batch;
2547 // No event generated. Try again with next completion.
2548 }
2549 }
2550
2551 pn_event_batch_t *pn_proactor_wait(struct pn_proactor_t* p) {
2552 return proactor_completion_loop(p, true);
2553 }
2554
2555 pn_event_batch_t *pn_proactor_get(struct pn_proactor_t* p) {
2556 return proactor_completion_loop(p, false);
2557 }
2558
2559 void pn_proactor_interrupt(pn_proactor_t *p) {
2560 csguard g(&p->context.cslock);
2561 if (p->context.working)
2562 p->delayed_interrupt = true;
2563 else
2564 p->need_interrupt = true;
2565 proactor_wake(p);
2566 }
2567
2568 // runs on a threadpool thread. Must not hold timer_lock.
2569 VOID CALLBACK timeout_cb(PVOID arg, BOOLEAN /* ignored*/ ) {
2570 pn_proactor_t *p = (pn_proactor_t *) arg;
2571 csguard gtimer(&p->timer_lock);
2572 csguard g(&p->context.cslock);
2573 if (p->timeout_set)
2574 p->need_timeout = true; // else cancelled
2575 p->timeout_set = false;
2576 if (p->need_timeout)
2577 proactor_wake(p);
2578 }
2579
2580 void pn_proactor_set_timeout(pn_proactor_t *p, pn_millis_t t) {
2581 bool ticking = false;
2582 csguard gtimer(&p->timer_lock);
2583 {
2584 csguard g(&p->context.cslock);
2585 ticking = (p->timeout_timer != NULL);
2586 if (t == 0) {
2587 p->need_timeout = true;
2588 p->timeout_set = false;
2589 proactor_wake(p);
2590 }
2591 else
2592 p->timeout_set = true;
2593 }
2594 // Just timer_lock held
2595 if (ticking) {
2596 stop_timer(p->timer_queue, &p->timeout_timer);
2597 }
2598 if (t) {
2599 start_timer(p->timer_queue, &p->timeout_timer, timeout_cb, p, t);
2600 }
2601 }
2602
2603 void pn_proactor_cancel_timeout(pn_proactor_t *p) {
2604 bool ticking = false;
2605 csguard gtimer(&p->timer_lock);
2606 {
2607 csguard g(&p->context.cslock);
2608 p->timeout_set = false;
2609 ticking = (p->timeout_timer != NULL);
2610 }
2611 if (ticking) {
2612 stop_timer(p->timer_queue, &p->timeout_timer);
2613 csguard g(&p->context.cslock);
2614 wake_if_inactive(p);
2615 }
2616 }
2617
2618 // Return true if connect_step_done()will handle connection status
2619 static bool connect_step(pconnection_t *pc) {
2620 pn_proactor_t *p = pc->context.proactor;
2621 while (pc->ai) { /* Have an address */
2622 struct addrinfo *ai = pc->ai;
2623 pc->ai = pc->ai->ai_next; /* Move to next address in case this fails */
2624 unique_socket fd(::socket(ai->ai_family, SOCK_STREAM, ai->ai_protocol));
2625 if (fd != INVALID_SOCKET) {
2626 // Windows ConnectEx requires loosely bound socket.
2627 sockaddr_storage sa;
2628 memset(&sa, 0, sizeof(sa));
2629 sa.ss_family = ai->ai_family;
2630 if (!bind(fd, (SOCKADDR *) &sa, ai->ai_addrlen)) {
2631 pni_configure_sock_2(fd);
2632 pc->psocket.iocpd = pni_iocpdesc_create(p->iocp, fd);
2633 assert(pc->psocket.iocpd);
2634 pc->psocket.iocpd->write_closed = true;
2635 pc->psocket.iocpd->read_closed = true;
2636 fd.release();
2637 iocpdesc_t *iocpd = pc->psocket.iocpd;
2638 if (CreateIoCompletionPort ((HANDLE) iocpd->socket, iocpd->iocp->completion_port, proactor_io, 0)) {
2639 LPFN_CONNECTEX fn_connect_ex = lookup_connect_ex2(iocpd->socket);
2640 // addrinfo is owned by the pconnection so pass NULL to the connect result
2641 connect_result_t *result = connect_result(iocpd, NULL);
2642 iocpd->ops_in_progress++;
2643 iocpd->active_completer = &pc->psocket;
2644 // getpeername unreliable for outgoing connections, but we know it at this point
2645 memcpy(&pc->remote.ss, ai->ai_addr, ai->ai_addrlen);
2646 DWORD unused;
2647 bool success = fn_connect_ex(iocpd->socket, ai->ai_addr, ai->ai_addrlen,
2648 NULL, 0, &unused, (LPOVERLAPPED) result);
2649 if (success || WSAGetLastError() == ERROR_IO_PENDING) {
2650 return true; // logic resumes at connect_step_done()
2651 } else {
2652 iocpd->ops_in_progress--;
2653 iocpd->active_completer = NULL;
2654 memset(&pc->remote.ss, 0, sizeof(pc->remote.ss));
2655 }
2656 pn_free(result);
2657 }
2658 }
2659 if (pc->psocket.iocpd) {
2660 pc->context.proactor->reaper->fast_reap(pc->psocket.iocpd);
2661 pc->psocket.iocpd = NULL;
2662 }
2663 }
2664 }
2665 pc->context.closing = true;
2666 return false;
2667 }
2668
2669 static void connect_step_done(pconnection_t *pc, connect_result_t *result) {
2670 csguard g(&pc->context.cslock);
2671 DWORD saved_status = result->base.status;
2672 iocpdesc_t *iocpd = result->base.iocpd;
2673 iocpd->ops_in_progress--;
2674 assert(pc->psocket.iocpd == iocpd);
2675 complete_connect(result, result->base.status); // frees result, starts regular IO if connected
2676
2677 if (!saved_status) {
2678 // Success
2679 pc->psocket.iocpd->write_closed = false;
2680 pc->psocket.iocpd->read_closed = false;
2681 if (pc->addrinfo) {
2682 socklen_t len = sizeof(pc->local.ss);
2683 getsockname(pc->psocket.iocpd->socket, (struct sockaddr*)&pc->local.ss, &len);
2684 freeaddrinfo(pc->addrinfo);
2685 pc->addrinfo = NULL;
2686 }
2687 pc->ai = NULL;
2688 return;
2689 }
2690 else {
2691 // Descriptor will never be used. Dispose.
2692 // Connect failed, no IO started, i.e. no pending iocpd based events
2693 pc->context.proactor->reaper->fast_reap(iocpd);
2694 pc->psocket.iocpd = NULL;
2695 memset(&pc->remote.ss, 0, sizeof(pc->remote.ss));
2696 // Is there a next connection target in the addrinfo to try?
2697 if (pc->ai && connect_step(pc)) {
2698 // Trying the next addrinfo possibility. Will return here.
2699 return;
2700 }
2701 // Give up
2702 psocket_error(&pc->psocket, saved_status, "connect to ");
2703 pc->context.closing = true;
2704 wakeup(&pc->psocket);
2705 }
2706 }
2707
2708 void pn_proactor_connect2(pn_proactor_t *p, pn_connection_t *c, pn_transport_t *t, const char *addr) {
2709 pconnection_t *pc = (pconnection_t*) pn_class_new(&pconnection_class, sizeof(pconnection_t));
2710 assert(pc); // TODO: memory safety
2711 const char *err = pconnection_setup(pc, p, c, t, false, addr);
2712 if (err) {
2713 PN_LOG_DEFAULT(PN_SUBSYSTEM_EVENT, PN_LEVEL_ERROR, "pn_proactor_connect failure: %s", err);
2714 return;
2715 }
2716 // TODO: check case of proactor shutting down
2717 csguard g(&pc->context.cslock);
2718 pc->connecting = true;
2719 proactor_add(&pc->context);
2720 pn_connection_open(pc->driver.connection); /* Auto-open */
2721
2722 if (!pgetaddrinfo(pc->psocket.host, pc->psocket.port, 0, &pc->addrinfo)) {
2723 pc->ai = pc->addrinfo;
2724 if (connect_step(pc)) {
2725 return;
2726 }
2727 }
2728 psocket_error(&pc->psocket, WSAGetLastError(), "connect to ");
2729 wakeup(&pc->psocket);
2730 if (p->reaper->add(pc->psocket.iocpd)) {
2731 pc->psocket.iocpd = NULL;
2732 }
2733 }
2734
2735 void pn_proactor_release_connection(pn_connection_t *c) {
2736 bool notify = false;
2737 pconnection_t *pc = get_pconnection(c);
2738 if (pc) {
2739 csguard g(&pc->context.cslock);
2740 // reverse lifecycle entanglement of pc and c from new_pconnection_t()
2741 pn_incref(pc);
2742 pn_proactor_t *p = pc->context.proactor;
2743 csguard g2(&p->bind_lock);
2744 pn_record_t *r = pn_connection_attachments(pc->driver.connection);
2745 pn_record_set(r, PN_PROACTOR, NULL);
2746 pn_connection_driver_release_connection(&pc->driver);
2747 pc->bound = false; // Transport unbound
2748 g2.release();
2749 pconnection_begin_close(pc);
2750 }
2751 }
2752
2753 void pn_proactor_listen(pn_proactor_t *p, pn_listener_t *l, const char *addr, int backlog)
2754 {
2755 csguard g(&l->context.cslock);
2756 l->context.proactor = p;;
2757 l->backlog = backlog;
2758 proactor_add(&l->context);
2759
2760 // l->overflow = NO_OVERFLOW; TODO, as for epoll
2761
2762 char addr_buf[PN_MAX_ADDR];
2763 const char *host, *port;
2764 pni_parse_addr(addr, addr_buf, PN_MAX_ADDR, &host, &port);
2765
2766 struct addrinfo *addrinfo = NULL;
2767 int gai_err = pgetaddrinfo(host, port, AI_PASSIVE | AI_ALL, &addrinfo);
2768 int wsa_err = 0;
2769 if (!gai_err) {
2770 /* Count addresses, allocate enough space for sockets */
2771 size_t len = 0;
2772 for (struct addrinfo *ai = addrinfo; ai; ai = ai->ai_next) {
2773 ++len;
2774 }
2775 assert(len > 0); /* guaranteed by getaddrinfo */
2776 l->psockets = (psocket_t*)calloc(len, sizeof(psocket_t));
2777 assert(l->psockets); /* TODO: memory safety */
2778 l->psockets_size = 0;
2779 uint16_t dynamic_port = 0; /* Record dynamic port from first bind(0) */
2780 /* Find working listen addresses */
2781 for (struct addrinfo *ai = addrinfo; ai; ai = ai->ai_next) {
2782 if (dynamic_port) set_port(ai->ai_addr, dynamic_port);
2783 // Note fd destructor can clear WSAGetLastError()
2784 unique_socket fd(::socket(ai->ai_family, SOCK_STREAM, ai->ai_protocol));
2785 if (fd != INVALID_SOCKET) {
2786 bool yes = 1;
2787 if (!::bind(fd, ai->ai_addr, ai->ai_addrlen))
2788 if (!::listen(fd, backlog)) {
2789 iocpdesc_t *iocpd = pni_iocpdesc_create(p->iocp, fd);
2790 if (iocpd) {
2791 pn_socket_t sock = fd.release();
2792 psocket_t *ps = &l->psockets[l->psockets_size++];
2793 psocket_init(ps, l, false, addr);
2794 ps->iocpd = iocpd;
2795 iocpd->is_mp = true;
2796 iocpd->active_completer = ps;
2797 pni_iocpdesc_start(ps->iocpd);
2798 /* Get actual address */
2799 socklen_t len = sizeof(ps->listen_addr.ss);
2800 (void)getsockname(sock, (struct sockaddr*)&ps->listen_addr.ss, &len);
2801 if (ps == l->psockets) { /* First socket, check for dynamic port */
2802 dynamic_port = check_dynamic_port(ai->ai_addr, pn_netaddr_sockaddr(&ps->listen_addr));
2803 } else {
2804 (ps-1)->listen_addr.next = &ps->listen_addr; /* Link into list */
2805 }
2806 }
2807 }
2808 }
2809 wsa_err = WSAGetLastError(); // save it
2810 }
2811 }
2812 if (addrinfo) {
2813 freeaddrinfo(addrinfo);
2814 }
2815 if (l->psockets_size == 0) { /* All failed, create dummy socket with an error */
2816 l->psockets = (psocket_t*)calloc(sizeof(psocket_t), 1);
2817 psocket_init(l->psockets, l, false, addr);
2818 if (gai_err) {
2819 psocket_error(l->psockets, gai_err, "listen on");
2820 } else {
2821 psocket_error(l->psockets, wsa_err, "listen on");
2822 }
2823 } else {
2824 pn_collector_put(l->collector, PN_CLASSCLASS(pn_listener), l, PN_LISTENER_OPEN);
2825 }
2826 wakeup(l->psockets);
2827 }
2828
2829 // Assumes listener lock is held
2830 static pn_event_batch_t *batch_owned(pn_listener_t *l) {
2831 if (l->close_dispatched) return NULL;
2832 if (!l->context.working) {
2833 if (listener_has_event(l)) {
2834 l->context.working = true;
2835 return &l->batch;
2836 }
2837 assert(!(l->context.closing && l->pending_events));
2838 if (l->pending_events) {
2839 pn_collector_put(l->collector, PN_CLASSCLASS(pn_listener), l, PN_LISTENER_ACCEPT);
2840 l->pending_events--;
2841 l->context.working = true;
2842 return &l->batch;
2843 }
2844 }
2845 return NULL;
2846 }
2847
2848 static void listener_close_all(pn_listener_t *l) {
2849 for (size_t i = 0; i < l->psockets_size; ++i) {
2850 psocket_t *ps = &l->psockets[i];
2851 if(ps->iocpd && !ps->iocpd->closing)
2852 if (l->context.proactor->reaper->add(ps->iocpd))
2853 ps->iocpd = NULL;
2854 }
2855 }
2856
2857 static bool listener_can_free(pn_listener_t *l) {
2858 if (!l->close_dispatched) return false;
2859 if (l->context.working || l->context.completion_ops) return false;
2860 for (size_t i = 0; i < l->psockets_size; ++i) {
2861 psocket_t *ps = &l->psockets[i];
2862 if (ps->iocpd)
2863 return false;
2864 }
2865 return true;
2866 }
2867
2868 /* Call with lock not held */
2869 static inline void listener_final_free(pn_listener_t *l) {
2870 pcontext_finalize(&l->context);
2871 free(l->psockets);
2872 if (l->collector) pn_collector_free(l->collector);
2873 if (l->condition) pn_condition_free(l->condition);
2874 if (l->attachments) pn_free(l->attachments);
2875 free(l);
2876 }
2877
2878 /* Call with listener lock held by lg.*/
2879 static void internal_listener_free(pn_listener_t *l, csguard &g) {
2880 bool can_free = true;
2881 if (l->context.proactor) {
2882 can_free = proactor_remove(&l->context);
2883 }
2884 g.release();
2885 if (can_free)
2886 listener_final_free(l);
2887 // else final free is done by proactor_disconnect()
2888 }
2889
2890 static bool listener_maybe_free(pn_listener_t *l, csguard &g) {
2891 if (listener_can_free(l)) {
2892 internal_listener_free(l, g);
2893 return true;
2894 }
2895 return false;
2896 }
2897
2898 static pn_event_batch_t *listener_process(pn_listener_t *l, iocp_result_t *result) {
2899 accept_result_t *accept_result = NULL;
2900 psocket_t *ps = NULL;
2901 {
2902 csguard g(&l->context.cslock);
2903 if (!result) {
2904 wake_complete(&l->context);
2905 if (listener_maybe_free(l, g)) return NULL;
2906 return batch_owned(l);
2907 }
2908 else
2909 ps = (psocket_t *) result->iocpd->active_completer;
2910
2911 if (!l->context.closing && result->status) {
2912 psocket_error(ps, WSAGetLastError(), "listen on "); // initiates close/multi-reap
2913 }
2914 if (l->context.closing) {
2915 if (l->context.proactor->reaper->process(result)) {
2916 ps->iocpd = NULL;
2917 if (listener_maybe_free(l, g)) return NULL;
2918 }
2919 return batch_owned(l);
2920 }
2921
2922 accept_result = (accept_result_t *) result;
2923 l->context.completion_ops++; // prevent accidental deletion while lock is temporarily removed
2924 }
2925
2926 // No lock
2927
2928 pn_socket_t accept_sock = accept_result->new_sock->socket;
2929 // AcceptEx special setsockopt:
2930 setsockopt(accept_sock, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, (char*)&ps->iocpd->socket,
2931 sizeof (SOCKET));
2932 // Connected.
2933 iocpdesc_t *conn_iocpd = accept_result->new_sock;
2934 conn_iocpd->read_closed = false;
2935 conn_iocpd->write_closed = false;
2936 pni_configure_sock_2(conn_iocpd->socket);
2937
2938 {
2939 csguard g(&l->context.cslock);
2940 l->context.completion_ops--;
2941 accept_result->new_sock->ops_in_progress--;
2942 ps->iocpd->ops_in_progress--;
2943
2944 // add even if closing to reuse cleanup code
2945 l->pending_accepts->push(accept_result);
2946 if (!ps->iocpd->ops_in_progress)
2947 begin_accept(ps->iocpd->acceptor, NULL); // Start another, up to IOCP_MAX_ACCEPTS
2948 l->pending_events++;
2949 if (l->context.closing)
2950 release_pending_accepts(l);
2951 if (listener_maybe_free(l, g)) return NULL;
2952 return batch_owned(l);
2953 }
2954 }
2955
2956 pn_proactor_t *pn_connection_proactor(pn_connection_t* c) {
2957 pconnection_t *pc = get_pconnection(c);
2958 return pc ? pc->context.proactor : NULL;
2959 }
2960
2961 void pn_connection_wake(pn_connection_t* c) {
2962 pconnection_t *pc = get_pconnection(c);
2963 csguard g(&pc->context.cslock);
2964 if (!pc->context.closing) {
2965 pc->wake_count++;
2966 wakeup(&pc->psocket);
2967 }
2968 }
2969
2970 pn_proactor_t *pn_proactor() {
2971 HANDLE tq = NULL;
2972 bool wsa = false;
2973 iocp_t *iocp = NULL;
2974 pn_proactor_t *p = NULL;
2975 pn_collector_t *c = NULL;
2976 class reaper *r = NULL;
2977
2978 tq = CreateTimerQueue();
2979 if (tq) {
2980 p = (pn_proactor_t*)calloc(1, sizeof(*p));
2981 c = pn_collector();
2982 if (p && c) {
2983 /* Request WinSock 2.2 */
2984 WORD wsa_ver = MAKEWORD(2, 2);
2985 WSADATA unused;
2986 if (!WSAStartup(wsa_ver, &unused)) {
2987 wsa = true;
2988 if (iocp = pni_iocp()) {
2989 InitializeCriticalSectionAndSpinCount(&p->context.cslock, 4000);
2990 InitializeCriticalSectionAndSpinCount(&p->write_lock, 4000);
2991 InitializeCriticalSectionAndSpinCount(&p->timer_lock, 4000);
2992 InitializeCriticalSectionAndSpinCount(&p->bind_lock, 4000);
2993 try {
2994 r = new reaper(p, &p->write_lock, iocp);
2995 // success
2996 p->iocp = iocp;
2997 p->reaper = r;
2998 p->batch.next_event = &proactor_batch_next;
2999 p->collector = c;
3000 p->timer_queue = tq;
3001 return p;
3002 } catch (...) {}
3003 }
3004 }
3005 }
3006 }
3007 fprintf(stderr, "%s\n", errno_str("Windows Proton proactor OS resource failure", false).c_str());
3008 if (iocp) pn_free((void *) iocp);
3009 if (wsa) WSACleanup();
3010 free(c);
3011 free(p);
3012 if (tq) DeleteTimerQueueEx(tq, NULL);
3013 return NULL;
3014 }
3015
3016 void pn_proactor_free(pn_proactor_t *p) {
3017 DeleteTimerQueueEx(p->timer_queue, INVALID_HANDLE_VALUE);
3018 DeleteCriticalSection(&p->timer_lock);
3019 DeleteCriticalSection(&p->bind_lock);
3020 proactor_shutdown(p);
3021
3022 delete p->reaper;
3023 WSACleanup();
3024 pn_collector_free(p->collector);
3025 free(p);
3026 }
3027
3028 static pn_event_t *listener_batch_next(pn_event_batch_t *batch) {
3029 pn_listener_t *l = batch_listener(batch);
3030 {
3031 csguard g(&l->context.cslock);
3032 if (!listener_has_event(l) && l->pending_events) {
3033 pn_collector_put(l->collector, PN_CLASSCLASS(pn_listener), l, PN_LISTENER_ACCEPT);
3034 l->pending_events--;
3035 }
3036 pn_event_t *e = pn_collector_next(l->collector);
3037 if (e && pn_event_type(e) == PN_LISTENER_CLOSE)
3038 l->close_dispatched = true;
3039 return pni_log_event(l, e);
3040 }
3041 }
3042
3043 static void listener_done(pn_listener_t *l) {
3044 {
3045 csguard g(&l->context.cslock);
3046 l->context.working = false;
3047 if (l->close_dispatched) {
3048 listener_maybe_free(l, g);
3049 return;
3050 }
3051 else
3052 if (listener_has_event(l))
3053 wakeup(l->psockets);
3054 }
3055 }
3056
3057 pn_listener_t *pn_listener() {
3058 pn_listener_t *l = (pn_listener_t*)calloc(1, sizeof(pn_listener_t));
3059 if (l) {
3060 l->batch.next_event = listener_batch_next;
3061 l->collector = pn_collector();
3062 l->condition = pn_condition();
3063 l->attachments = pn_record();
3064 l->pending_accepts = new std::queue<accept_result_t *>();
3065 if (!l->condition || !l->collector || !l->attachments) {
3066 pn_listener_free(l);
3067 return NULL;
3068 }
3069 pn_proactor_t *unknown = NULL; // won't know until pn_proactor_listen
3070 pcontext_init(&l->context, LISTENER, unknown, l);
3071 }
3072 return l;
3073 }
3074
3075 void pn_listener_free(pn_listener_t *l) {
3076 /* Note at this point either the listener has never been used (freed
3077 by user) or it has been closed, and all pending operations
3078 completed, i.e. listener_can_free() is true.
3079 */
3080 if (l) {
3081 csguard g(&l->context.cslock);
3082 if (l->context.proactor) {
3083 internal_listener_free(l, g);
3084 return;
3085 }
3086 // freed by user
3087 g.release();
3088 listener_final_free(l);
3089 }
3090 }
3091
3092 static void listener_begin_close(pn_listener_t* l) {
3093 if (l->context.closing)
3094 return;
3095 l->context.closing = true;
3096 listener_close_all(l);
3097 release_pending_accepts(l);
3098 pn_collector_put(l->collector, PN_CLASSCLASS(pn_listener), l, PN_LISTENER_CLOSE);
3099 }
3100
3101 void pn_listener_close(pn_listener_t* l) {
3102 csguard g(&l->context.cslock);
3103 listener_begin_close(l);
3104 wakeup(&l->psockets[0]);
3105 }
3106
3107 pn_proactor_t *pn_listener_proactor(pn_listener_t* l) {
3108 return l ? l->context.proactor : NULL;
3109 }
3110
3111 pn_condition_t* pn_listener_condition(pn_listener_t* l) {
3112 return l->condition;
3113 }
3114
3115 void *pn_listener_get_context(pn_listener_t *l) {
3116 return l->listener_context;
3117 }
3118
3119 void pn_listener_set_context(pn_listener_t *l, void *context) {
3120 l->listener_context = context;
3121 }
3122
3123 pn_record_t *pn_listener_attachments(pn_listener_t *l) {
3124 return l->attachments;
3125 }
3126
3127 static void release_pending_accepts(pn_listener_t *l) {
3128 // called with lock held or at shutdown
3129 while (!l->pending_accepts->empty()) {
3130 accept_result_t *accept_result = l->pending_accepts->front();
3131 l->pending_accepts->pop();
3132 psocket_t *ps = (psocket_t *) accept_result->base.iocpd->active_completer;
3133 accept_result->new_sock->ops_in_progress--;
3134 ps->iocpd->ops_in_progress--;
3135 l->context.proactor->reaper->add(accept_result->new_sock);
3136 begin_accept(accept_result->base.iocpd->acceptor, accept_result); // does proper disposal when closing
3137 }
3138 l->pending_events = 0;
3139 }
3140
3141 static void recycle_result(accept_result_t *accept_result) {
3142 psocket_t *ps = (psocket_t *) accept_result->base.iocpd->active_completer;
3143 pn_listener_t *l = ps->listener;
3144 reset_accept_result(accept_result);
3145 accept_result->new_sock = create_same_type_socket(ps->iocpd);
3146 {
3147 csguard g(&l->context.cslock);
3148 if (l->context.closing && accept_result->new_sock) {
3149 closesocket(accept_result->new_sock->socket);
3150 accept_result->new_sock->socket = INVALID_SOCKET;
3151 }
3152 begin_accept(ps->iocpd->acceptor, accept_result); // cleans up if closing
3153 l->context.completion_ops--;
3154 if (l->context.closing && listener_maybe_free(l, g))
3155 return;
3156 }
3157 }
3158
3159 void pn_listener_accept2(pn_listener_t *l, pn_connection_t *c, pn_transport_t *t) {
3160 accept_result_t *accept_result = NULL;
3161 DWORD err = 0;
3162 psocket_t *ps = NULL;
3163 pn_proactor_t *p = l->context.proactor;
3164
3165 {
3166 csguard g(&l->context.cslock);
3167 pconnection_t *pc = (pconnection_t*) pn_class_new(&pconnection_class, sizeof(pconnection_t));
3168 assert(pc); // TODO: memory safety
3169 const char *err_str = pconnection_setup(pc, p, c, t, true, "");
3170 if (err_str) {
3171 PN_LOG_DEFAULT(PN_SUBSYSTEM_EVENT, PN_LEVEL_ERROR, "pn_listener_accept failure: %s", err_str);
3172 return;
3173 }
3174 proactor_add(&pc->context);
3175
3176 if (l->context.closing)
3177 err = WSAESHUTDOWN;
3178 else if (l->pending_accepts->empty())
3179 err = WSAEWOULDBLOCK;
3180 else {
3181 accept_result = l->pending_accepts->front();
3182 l->pending_accepts->pop();
3183 ps = (psocket_t *) accept_result->base.iocpd->active_completer;
3184 l->context.completion_ops++; // for recycle_result
3185 iocpdesc_t *conn_iocpd = accept_result->new_sock;
3186 pc->psocket.iocpd = conn_iocpd;
3187 conn_iocpd->active_completer =&pc->psocket;
3188 set_sock_names(pc);
3189 pc->started = true;
3190 csguard g(&pc->context.cslock);
3191 pni_iocpdesc_start(conn_iocpd);
3192 }
3193
3194 if (err) {
3195 psocket_error(&pc->psocket, err, "listen on");
3196 wakeup(&pc->psocket);
3197 }
3198 }
3199 // Use another thread to prepare a replacement async accept request
3200 post_completion(p->iocp, recycle_accept_key, accept_result);
3201 }
3202
3203
3204
3205 // Call with lock held. Leave unchanged if events pending.
3206 // Return true if there is an event in the collector
3207 static bool proactor_update_batch(pn_proactor_t *p) {
3208 if (proactor_has_event(p))
3209 return true;
3210 if (p->need_timeout) {
3211 p->need_timeout = false;
3212 proactor_add_event(p, PN_PROACTOR_TIMEOUT);
3213 return true;
3214 }
3215 if (p->need_interrupt) {
3216 p->need_interrupt = false;
3217 proactor_add_event(p, PN_PROACTOR_INTERRUPT);
3218 return true;
3219 }
3220 if (p->need_inactive) {
3221 p->need_inactive = false;
3222 proactor_add_event(p, PN_PROACTOR_INACTIVE);
3223 return true;
3224 }
3225 return false;
3226 }
3227
3228 static pn_event_t *proactor_batch_next(pn_event_batch_t *batch) {
3229 pn_proactor_t *p = batch_proactor(batch);
3230 pn_event_t *e = pn_collector_next(p->collector);
3231 if (!e) {
3232 csguard g(&p->context.cslock);
3233 proactor_update_batch(p);
3234 e = pn_collector_next(p->collector);
3235 }
3236 if (e && pn_event_type(e) == PN_PROACTOR_TIMEOUT)
3237 p->timeout_processed = true;
3238 return pni_log_event(p, e);
3239 }
3240
3241 static void proactor_add(pcontext_t *ctx) {
3242 pn_proactor_t *p = ctx->proactor;
3243 csguard g(&p->context.cslock);
3244 if (p->contexts) {
3245 p->contexts->prev = ctx;
3246 ctx->next = p->contexts;
3247 }
3248 p->contexts = ctx;
3249 }
3250
3251 // call with pcontext lock held
3252 static bool proactor_remove(pcontext_t *ctx) {
3253 pn_proactor_t *p = ctx->proactor;
3254 csguard g(&p->context.cslock);
3255 bool can_free = true;
3256 if (ctx->disconnecting) {
3257 // No longer on contexts list
3258 --p->disconnects_pending;
3259 if (--ctx->disconnect_ops != 0) {
3260 // proactor_disconnect() does the free
3261 can_free = false;
3262 }
3263 }
3264 else {
3265 // normal case
3266 if (ctx->prev)
3267 ctx->prev->next = ctx->next;
3268 else {
3269 p->contexts = ctx->next;
3270 ctx->next = NULL;
3271 if (p->contexts)
3272 p->contexts->prev = NULL;
3273 }
3274 if (ctx->next) {
3275 ctx->next->prev = ctx->prev;
3276 }
3277 }
3278 wake_if_inactive(p);
3279 return can_free;
3280 }
3281
3282 static void pconnection_forced_shutdown(pconnection_t *pc) {
3283 // Called by proactor_free, no competing threads processing iocp activity.
3284 pconnection_begin_close(pc);
3285 // Timer threads may lurk. No lock held, so no deadlock risk
3286 stop_timer(pc->context.proactor->timer_queue, &pc->tick_timer);
3287 pconnection_final_free(pc);
3288 }
3289
3290 static void listener_forced_shutdown(pn_listener_t *l) {
3291 // Called by proactor_free, no competing threads, no iocp activity.
3292 listener_close_all(l); // reaper gets all iocp descriptors to cleanup
3293 listener_final_free(l);
3294 }
3295
3296
3297 static void proactor_shutdown(pn_proactor_t *p) {
3298 // Called from free(), no competing threads except our own timer queue callbacks.
3299 p->shutting_down = true;
3300 while (p->contexts) {
3301 pcontext_t *ctx = p->contexts;
3302 p->contexts = ctx->next;
3303 switch (ctx->type) {
3304 case PCONNECTION:
3305 pconnection_forced_shutdown(pcontext_pconnection(ctx));
3306 break;
3307 case LISTENER:
3308 listener_forced_shutdown(pcontext_listener(ctx));
3309 break;
3310 default:
3311 break;
3312 }
3313 }
3314
3315 // Graceful close of the sockets (zombies), closes completion port, free iocp related resources
3316 p->reaper->final_shutdown();
3317 }
3318
3319 void pn_proactor_disconnect(pn_proactor_t *p, pn_condition_t *cond) {
3320 pcontext_t *disconnecting_pcontexts = NULL;
3321 pcontext_t *ctx = NULL;
3322 {
3323 csguard g(&p->context.cslock);
3324 // Move the whole contexts list into a disconnecting state
3325 disconnecting_pcontexts = p->contexts;
3326 p->contexts = NULL;
3327 // First pass: mark each pcontext as disconnecting and update global pending count.
3328 pcontext_t *ctx = disconnecting_pcontexts;
3329 while (ctx) {
3330 ctx->disconnecting = true;
3331 ctx->disconnect_ops = 2; // Second pass below and proactor_remove(), in any order.
3332 p->disconnects_pending++;
3333 ctx = ctx->next;
3334 }
3335 }
3336 // no lock
3337
3338 if (!disconnecting_pcontexts) {
3339 csguard p_guard(&p->context.cslock);
3340 wake_if_inactive(p);
3341 return;
3342 }
3343
3344 // Second pass: different locking, close the pcontexts, free them if !disconnect_ops
3345 pcontext_t *next = disconnecting_pcontexts;
3346 while (next) {
3347 ctx = next;
3348 next = ctx->next; /* Save next pointer in case we free ctx */
3349 bool do_free = false;
3350 pconnection_t *pc = pcontext_pconnection(ctx);
3351 pn_listener_t *l = pc ? NULL : pcontext_listener(ctx);
3352 CRITICAL_SECTION *ctx_cslock = pc ? &pc->context.cslock : &l->context.cslock;
3353 csguard ctx_guard(ctx_cslock);
3354 if (pc) {
3355 pc->can_wake = false;
3356 if (!ctx->closing) {
3357 if (ctx->working) {
3358 // Must defer
3359 pc->queued_disconnect = true;
3360 if (cond) {
3361 if (!pc->disconnect_condition)
3362 pc->disconnect_condition = pn_condition();
3363 pn_condition_copy(pc->disconnect_condition, cond);
3364 }
3365 }
3366 else {
3367 // No conflicting working context.
3368 if (cond) {
3369 pn_condition_copy(pn_transport_condition(pc->driver.transport), cond);
3370 }
3371 pn_connection_driver_close(&pc->driver);
3372 }
3373 }
3374 } else {
3375 assert(l);
3376 if (!ctx->closing) {
3377 if (cond) {
3378 pn_condition_copy(pn_listener_condition(l), cond);
3379 }
3380 listener_begin_close(l);
3381 }
3382 }
3383
3384 csguard p_guard(&p->context.cslock);
3385 if (--ctx->disconnect_ops == 0) {
3386 do_free = true;
3387 wake_if_inactive(p);
3388 } else {
3389 // If initiating the close, wake the pcontext to do the free.
3390 wakeup(pc ? &pc->psocket : l->psockets);
3391 }
3392 p_guard.release();
3393 ctx_guard.release();
3394
3395 if (do_free) {
3396 if (pc) pconnection_final_free(pc);
3397 else listener_final_free(pcontext_listener(ctx));
3398 }
3399 }
3400 }
3401
3402 const pn_netaddr_t *pn_transport_local_addr(pn_transport_t *t) {
3403 pconnection_t *pc = get_pconnection(pn_transport_connection(t));
3404 return pc? &pc->local : NULL;
3405 }
3406
3407 const pn_netaddr_t *pn_transport_remote_addr(pn_transport_t *t) {
3408 pconnection_t *pc = get_pconnection(pn_transport_connection(t));
3409 return pc ? &pc->remote : NULL;
3410 }
3411
3412 const pn_netaddr_t *pn_listener_addr(pn_listener_t *l) {
3413 return l->psockets ? &l->psockets[0].listen_addr : NULL;
3414 }
3415
3416 pn_millis_t pn_proactor_now(void) {
3417 return (pn_millis_t) pn_proactor_now_64();
3418 }
3419
3420 int64_t pn_proactor_now_64(void) {
3421 return GetTickCount64();
3422 }
3423
3424 // Empty stubs for raw connection code
3425 pn_raw_connection_t *pn_raw_connection(void) { return NULL; }
3426 void pn_proactor_raw_connect(pn_proactor_t *p, pn_raw_connection_t *rc, const char *addr) {}
3427 void pn_listener_raw_accept(pn_listener_t *l, pn_raw_connection_t *rc) {}
3428 void pn_raw_connection_wake(pn_raw_connection_t *conn) {}
3429 void pn_raw_connection_close(pn_raw_connection_t *conn) {}
3430 void pn_raw_connection_read_close(pn_raw_connection_t *conn) {}
3431 void pn_raw_connection_write_close(pn_raw_connection_t *conn) {}
3432 const struct pn_netaddr_t *pn_raw_connection_local_addr(pn_raw_connection_t *connection) { return NULL; }
3433 const struct pn_netaddr_t *pn_raw_connection_remote_addr(pn_raw_connection_t *connection) { return NULL; }