-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathasync_request.c
More file actions
2175 lines (1931 loc) · 85 KB
/
async_request.c
File metadata and controls
2175 lines (1931 loc) · 85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* async_request.c - Async request state machine implementation
*/
/* Define feature test macros before any includes */
#ifndef _WIN32
#define _POSIX_C_SOURCE 200809L
#define _DEFAULT_SOURCE
#endif
#include "async_request.h"
#include "io_engine.h"
#include "internal/proxy.h"
#include "internal/util.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/* SSL/TLS support */
#include <openssl/ssl.h>
#include <openssl/err.h>
/* Debug output control */
#ifdef HTTPMORPH_DEBUG
#define DEBUG_PRINT(...) printf(__VA_ARGS__)
#else
#define DEBUG_PRINT(...) ((void)0)
#endif
/* Platform-specific headers */
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <mswsock.h> /* For ConnectEx, AcceptEx, etc. */
/* Extension function pointers (loaded dynamically) */
static LPFN_CONNECTEX pfnConnectEx = NULL;
static bool wsa_extensions_loaded = false;
#else
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/time.h>
#endif
/* Default buffer sizes */
#define SEND_BUFFER_SIZE (64 * 1024) /* 64KB */
#define RECV_BUFFER_SIZE (256 * 1024) /* 256KB */
/* ID generation */
static uint64_t next_request_id = 1;
/**
* Get current time in microseconds
*/
static uint64_t get_time_us(void) {
#ifdef _WIN32
FILETIME ft;
ULARGE_INTEGER uli;
/* Get current time as FILETIME (100-nanosecond intervals since 1601-01-01) */
GetSystemTimeAsFileTime(&ft);
/* Convert to 64-bit integer */
uli.LowPart = ft.dwLowDateTime;
uli.HighPart = ft.dwHighDateTime;
/* Convert to microseconds since Unix epoch (1970-01-01) */
/* FILETIME epoch is 1601-01-01, Unix epoch is 1970-01-01 */
/* Difference is 11644473600 seconds */
uint64_t microseconds = uli.QuadPart / 10; /* Convert 100-ns to microseconds */
microseconds -= 11644473600ULL * 1000000ULL; /* Adjust to Unix epoch */
return microseconds;
#else
struct timeval tv;
gettimeofday(&tv, NULL);
return (uint64_t)tv.tv_sec * 1000000 + (uint64_t)tv.tv_usec;
#endif
}
/**
* Initialize Windows Socket Extensions (ConnectEx, etc.)
*/
#ifdef _WIN32
static int init_wsa_extensions(int sockfd) {
if (wsa_extensions_loaded) {
return 0; /* Already loaded */
}
GUID guid_connectex = WSAID_CONNECTEX;
DWORD bytes = 0;
/* Load ConnectEx function pointer */
if (WSAIoctl(sockfd, SIO_GET_EXTENSION_FUNCTION_POINTER,
&guid_connectex, sizeof(guid_connectex),
&pfnConnectEx, sizeof(pfnConnectEx),
&bytes, NULL, NULL) == SOCKET_ERROR) {
DEBUG_PRINT("[async_request] Failed to load ConnectEx: %d\n", WSAGetLastError());
return -1;
}
wsa_extensions_loaded = true;
DEBUG_PRINT("[async_request] WSA extensions loaded successfully\n");
return 0;
}
/**
* Allocate and initialize OVERLAPPED structure for IOCP
* Note: For IOCP, hEvent should be NULL as IOCP uses completion ports
*/
static void* alloc_overlapped(void) {
OVERLAPPED *ov = (OVERLAPPED*)calloc(1, sizeof(OVERLAPPED));
/* For IOCP, don't create an event - IOCP uses the completion port */
/* hEvent is already NULL from calloc */
return ov;
}
/**
* Free OVERLAPPED structure
*/
static void free_overlapped(void *overlapped) {
if (overlapped) {
free(overlapped);
}
}
#endif
/**
* Get state name for debugging
*/
const char* async_request_state_name(async_request_state_t state) {
switch (state) {
case ASYNC_STATE_INIT: return "INIT";
case ASYNC_STATE_DNS_LOOKUP: return "DNS_LOOKUP";
case ASYNC_STATE_CONNECTING: return "CONNECTING";
case ASYNC_STATE_PROXY_CONNECT: return "PROXY_CONNECT";
case ASYNC_STATE_TLS_HANDSHAKE: return "TLS_HANDSHAKE";
case ASYNC_STATE_SENDING_REQUEST: return "SENDING_REQUEST";
case ASYNC_STATE_RECEIVING_HEADERS: return "RECEIVING_HEADERS";
case ASYNC_STATE_RECEIVING_BODY: return "RECEIVING_BODY";
case ASYNC_STATE_COMPLETE: return "COMPLETE";
case ASYNC_STATE_ERROR: return "ERROR";
default: return "UNKNOWN";
}
}
/**
* Create a new async request
*/
async_request_t* async_request_create(
const httpmorph_request_t *request,
io_engine_t *io_engine,
SSL_CTX *ssl_ctx,
uint32_t timeout_ms,
async_request_callback_t callback,
void *user_data)
{
if (!request || !io_engine) {
return NULL;
}
async_request_t *req = calloc(1, sizeof(async_request_t));
if (!req) {
return NULL;
}
/* Initialize basic fields */
req->id = next_request_id++;
req->state = ASYNC_STATE_INIT;
req->request = (httpmorph_request_t*)request; /* Store pointer */
req->io_engine = io_engine;
req->sockfd = -1;
req->ssl = NULL;
req->refcount = 1;
req->dns_resolved = false;
/* Determine if HTTPS first (needed before creating SSL) */
req->is_https = request->use_tls;
/* Timing */
req->start_time_us = get_time_us();
req->timeout_ms = timeout_ms;
if (timeout_ms > 0) {
req->deadline_us = req->start_time_us + (uint64_t)timeout_ms * 1000;
} else {
req->deadline_us = 0; /* No timeout */
}
/* Allocate send buffer */
req->send_buf = malloc(SEND_BUFFER_SIZE);
if (!req->send_buf) {
free(req);
return NULL;
}
/* Allocate receive buffer */
req->recv_buf = malloc(RECV_BUFFER_SIZE);
if (!req->recv_buf) {
free(req->send_buf);
free(req);
return NULL;
}
req->recv_capacity = RECV_BUFFER_SIZE;
/* Set callback */
req->on_complete = callback;
req->user_data = user_data;
/* Initialize Windows-specific fields */
#ifdef _WIN32
req->overlapped_connect = NULL;
req->overlapped_send = NULL;
req->overlapped_recv = NULL;
req->iocp_operation_pending = false;
req->iocp_last_error = 0;
req->iocp_bytes_transferred = 0;
req->iocp_completion_callback = NULL;
/* Create completion event (manual-reset, initially non-signaled) */
req->iocp_completion_event = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!req->iocp_completion_event) {
DEBUG_PRINT("[async_request] Failed to create completion event\n");
free(req->recv_buf);
free(req);
return NULL;
}
#endif
/* Parse URL to extract hostname and port if not already set */
if (!request->host && request->url) {
char *scheme = NULL, *host = NULL, *path = NULL;
uint16_t port = 0;
extern int httpmorph_parse_url(const char *url, char **scheme, char **host, uint16_t *port, char **path);
if (httpmorph_parse_url(request->url, &scheme, &host, &port, &path) == 0) {
/* Store parsed values in request structure */
((httpmorph_request_t*)request)->host = host; /* Transfer ownership */
((httpmorph_request_t*)request)->port = port;
((httpmorph_request_t*)request)->use_tls = (scheme && strcmp(scheme, "https") == 0);
req->is_https = ((httpmorph_request_t*)request)->use_tls;
/* Free scheme and path as we don't need them */
free(scheme);
free(path);
}
}
/* Initialize proxy fields */
req->using_proxy = false;
req->proxy_host = NULL;
req->proxy_port = 0;
req->proxy_username = NULL;
req->proxy_password = NULL;
req->proxy_use_tls = false;
req->target_host = NULL;
req->target_port = 0;
req->proxy_connect_sent = false;
req->proxy_recv_buf = NULL;
req->proxy_recv_len = 0;
/* Parse and configure proxy if provided */
if (request->proxy_url && request->proxy_url[0] != '\0') {
/* Parse proxy URL */
if (httpmorph_parse_proxy_url(
request->proxy_url,
&req->proxy_host,
&req->proxy_port,
&req->proxy_username,
&req->proxy_password,
&req->proxy_use_tls) == 0) {
req->using_proxy = true;
/* Override with explicit proxy credentials if provided */
if (request->proxy_username) {
free(req->proxy_username);
req->proxy_username = strdup(request->proxy_username);
}
if (request->proxy_password) {
free(req->proxy_password);
req->proxy_password = strdup(request->proxy_password);
}
/* Store original target host/port */
if (request->host) {
req->target_host = strdup(request->host);
req->target_port = request->port;
}
/* Allocate proxy receive buffer for CONNECT response */
req->proxy_recv_buf = malloc(4096);
if (!req->proxy_recv_buf) {
/* Cleanup on failure */
free(req->proxy_host);
free(req->proxy_username);
free(req->proxy_password);
free(req->target_host);
free(req->send_buf);
free(req->recv_buf);
free(req);
return NULL;
}
DEBUG_PRINT("[async_request] Using proxy %s:%u for target %s:%u (id=%lu)\n",
req->proxy_host, req->proxy_port,
req->target_host, req->target_port,
(unsigned long)req->id);
}
}
/* Create SSL object for HTTPS requests */
if (req->is_https && ssl_ctx) {
req->ssl = SSL_new(ssl_ctx);
if (!req->ssl) {
/* Cleanup and return NULL */
free(req->send_buf);
free(req->recv_buf);
free(req);
return NULL;
}
/* Set SSL verification mode based on request setting */
if (request->verify_ssl) {
SSL_set_verify(req->ssl, SSL_VERIFY_PEER, NULL);
} else {
SSL_set_verify(req->ssl, SSL_VERIFY_NONE, NULL);
}
/* Set SNI hostname if available */
if (request->host) {
SSL_set_tlsext_host_name(req->ssl, request->host);
}
/* Set SSL to non-blocking mode (will be done when socket is created) */
DEBUG_PRINT("[async_request] Created SSL object for HTTPS (id=%lu)\n",
(unsigned long)req->id);
}
return req;
}
/**
* Destroy an async request
*/
void async_request_destroy(async_request_t *req) {
if (!req) {
return;
}
/* Clean up I/O operation */
if (req->current_op) {
io_op_destroy(req->current_op);
req->current_op = NULL;
}
/* Clean up Windows OVERLAPPED structures and event */
#ifdef _WIN32
free_overlapped(req->overlapped_connect);
free_overlapped(req->overlapped_send);
free_overlapped(req->overlapped_recv);
req->overlapped_connect = NULL;
req->overlapped_send = NULL;
req->overlapped_recv = NULL;
/* Close completion event */
if (req->iocp_completion_event) {
CloseHandle((HANDLE)req->iocp_completion_event);
req->iocp_completion_event = NULL;
}
#endif
/* Close socket (but never close stdin/stdout/stderr) */
if (req->sockfd > 2) {
#ifdef _WIN32
closesocket(req->sockfd);
#else
close(req->sockfd);
#endif
req->sockfd = -1;
}
/* Clean up SSL */
if (req->ssl) {
SSL_free(req->ssl);
req->ssl = NULL;
}
/* Free buffers */
free(req->send_buf);
free(req->recv_buf);
/* Free proxy buffers and strings */
free(req->proxy_host);
free(req->proxy_username);
free(req->proxy_password);
free(req->target_host);
free(req->proxy_recv_buf);
/* Free response if allocated */
if (req->response) {
httpmorph_response_destroy(req->response);
req->response = NULL;
}
free(req);
}
/**
* Reference counting
*/
void async_request_ref(async_request_t *req) {
if (req) {
req->refcount++;
}
}
void async_request_unref(async_request_t *req) {
if (req) {
req->refcount--;
if (req->refcount <= 0) {
async_request_destroy(req);
}
}
}
/**
* Get current state
*/
async_request_state_t async_request_get_state(const async_request_t *req) {
return req ? req->state : ASYNC_STATE_ERROR;
}
/**
* Get file descriptor
*/
int async_request_get_fd(const async_request_t *req) {
return req ? req->sockfd : -1;
}
/**
* Check timeout
*/
bool async_request_is_timeout(const async_request_t *req) {
if (!req || req->deadline_us == 0) {
return false;
}
return get_time_us() >= req->deadline_us;
}
/**
* Set error state
*/
void async_request_set_error(async_request_t *req, int error_code, const char *error_msg) {
if (!req) {
return;
}
req->state = ASYNC_STATE_ERROR;
req->error_code = error_code;
if (error_msg) {
snprintf(req->error_msg, sizeof(req->error_msg), "%s", error_msg);
}
}
/**
* Get response
*/
httpmorph_response_t* async_request_get_response(async_request_t *req) {
if (!req || req->state != ASYNC_STATE_COMPLETE) {
return NULL;
}
return req->response;
}
/**
* Get error message
*/
const char* async_request_get_error_message(const async_request_t *req) {
if (!req || req->error_msg[0] == '\0') {
return "No error message";
}
return req->error_msg;
}
/**
* State: DNS lookup
*/
static int step_dns_lookup(async_request_t *req) {
/* Check if already resolved */
if (req->dns_resolved) {
req->state = ASYNC_STATE_CONNECTING;
return ASYNC_STATUS_IN_PROGRESS;
}
/* Perform blocking DNS lookup (for now) */
/* Note: In production, this should use async DNS (getaddrinfo_a or thread pool) */
/* If using proxy, resolve proxy hostname instead of target hostname */
const char *hostname;
uint16_t port;
if (req->using_proxy) {
hostname = req->proxy_host;
port = req->proxy_port;
DEBUG_PRINT("[async_request] Resolving proxy %s:%u (target: %s:%u) (id=%lu)\n",
hostname, port, req->target_host, req->target_port, (unsigned long)req->id);
} else {
hostname = req->request->host;
port = req->request->port;
DEBUG_PRINT("[async_request] Resolving %s:%u (id=%lu)\n",
hostname, port, (unsigned long)req->id);
}
if (!hostname) {
async_request_set_error(req, -1, "No hostname specified");
return ASYNC_STATUS_ERROR;
}
/* Setup hints for getaddrinfo */
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM; /* TCP socket */
hints.ai_flags = AI_ADDRCONFIG; /* Only return addresses we can use */
/* Convert port to string */
char port_str[16];
snprintf(port_str, sizeof(port_str), "%u", port);
/* Perform DNS lookup */
struct addrinfo *result = NULL;
int ret = getaddrinfo(hostname, port_str, &hints, &result);
if (ret != 0) {
char error_buf[256];
snprintf(error_buf, sizeof(error_buf), "DNS lookup failed: %s", gai_strerror(ret));
async_request_set_error(req, ret, error_buf);
return ASYNC_STATUS_ERROR;
}
if (!result) {
async_request_set_error(req, -1, "DNS lookup returned no results");
return ASYNC_STATUS_ERROR;
}
/* Store the first result */
memcpy(&req->addr, result->ai_addr, result->ai_addrlen);
req->addr_len = result->ai_addrlen;
req->dns_resolved = true;
DEBUG_PRINT("[async_request] DNS resolved for %s:%u (id=%lu)\n",
hostname, port, (unsigned long)req->id);
/* Free the result */
freeaddrinfo(result);
/* Move to connecting state */
req->state = ASYNC_STATE_CONNECTING;
return ASYNC_STATUS_IN_PROGRESS;
}
/**
* State: Connecting
*/
static int step_connecting(async_request_t *req) {
/* Verify DNS was resolved */
if (!req->dns_resolved) {
async_request_set_error(req, -1, "DNS not resolved before connect");
return ASYNC_STATUS_ERROR;
}
/* If socket not created yet, create it and initiate connection */
if (req->sockfd < 0) {
/* Get address family from resolved address */
int af = ((struct sockaddr*)&req->addr)->sa_family;
/* Create non-blocking socket */
req->sockfd = io_socket_create_nonblocking(af, SOCK_STREAM, 0);
if (req->sockfd < 0) {
async_request_set_error(req, errno, "Failed to create socket");
return ASYNC_STATUS_ERROR;
}
/* Set performance options */
io_socket_set_performance_opts(req->sockfd);
DEBUG_PRINT("[async_request] Connecting to %s:%u on fd=%d (id=%lu)\n",
req->request->host, req->request->port, req->sockfd, (unsigned long)req->id);
#ifdef _WIN32
/* Windows IOCP path with ConnectEx - skip for SSL sockets */
if (req->io_engine && req->io_engine->type == IO_ENGINE_IOCP && !req->is_https) {
/* Initialize WSA extensions if needed */
if (init_wsa_extensions(req->sockfd) < 0) {
async_request_set_error(req, -1, "Failed to load WSA extensions");
return ASYNC_STATUS_ERROR;
}
/* ConnectEx requires socket to be bound first */
struct sockaddr_storage local_addr;
memset(&local_addr, 0, sizeof(local_addr));
local_addr.ss_family = af;
if (bind(req->sockfd, (struct sockaddr*)&local_addr,
af == AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)) == SOCKET_ERROR) {
req->iocp_last_error = WSAGetLastError();
char error_buf[256];
snprintf(error_buf, sizeof(error_buf), "Bind failed: %d", req->iocp_last_error);
async_request_set_error(req, req->iocp_last_error, error_buf);
return ASYNC_STATUS_ERROR;
}
/* Associate socket with IOCP ONLY if NOT using SSL */
/* SSL sockets CANNOT use IOCP because SSL_write/SSL_read use regular I/O */
if (!req->is_https) {
if (CreateIoCompletionPort((HANDLE)req->sockfd, (HANDLE)req->io_engine->iocp_handle,
(ULONG_PTR)req, 0) == NULL) {
req->iocp_last_error = GetLastError();
char error_buf[256];
snprintf(error_buf, sizeof(error_buf), "Failed to associate socket with IOCP: %d",
req->iocp_last_error);
async_request_set_error(req, req->iocp_last_error, error_buf);
return ASYNC_STATUS_ERROR;
}
DEBUG_PRINT("[async_request] Socket fd=%d associated with IOCP, completion_key=%p (id=%lu)\n",
req->sockfd, (void*)req, (unsigned long)req->id);
} else {
DEBUG_PRINT("[async_request] Socket fd=%d NOT associated with IOCP (SSL socket) (id=%lu)\n",
req->sockfd, (unsigned long)req->id);
}
/* Allocate OVERLAPPED structure */
if (!req->overlapped_connect) {
req->overlapped_connect = alloc_overlapped();
if (!req->overlapped_connect) {
async_request_set_error(req, -1, "Failed to allocate OVERLAPPED");
return ASYNC_STATUS_ERROR;
}
}
/* Reset completion event before starting new operation */
ResetEvent((HANDLE)req->iocp_completion_event);
/* Start async connect */
BOOL result = pfnConnectEx(req->sockfd, (struct sockaddr*)&req->addr, req->addr_len,
NULL, 0, NULL, (OVERLAPPED*)req->overlapped_connect);
if (!result) {
req->iocp_last_error = WSAGetLastError();
if (req->iocp_last_error == ERROR_IO_PENDING) {
/* Async operation started successfully */
req->iocp_operation_pending = true;
DEBUG_PRINT("[async_request] ConnectEx started (id=%lu)\n", (unsigned long)req->id);
return ASYNC_STATUS_NEED_WRITE;
} else {
/* Connect failed immediately */
char error_buf[256];
snprintf(error_buf, sizeof(error_buf), "ConnectEx failed: %d", req->iocp_last_error);
async_request_set_error(req, req->iocp_last_error, error_buf);
return ASYNC_STATUS_ERROR;
}
}
/* Connected immediately (rare) */
req->iocp_operation_pending = false;
DEBUG_PRINT("[async_request] ConnectEx completed immediately (id=%lu)\n", (unsigned long)req->id);
/* Update socket context (required after ConnectEx) */
setsockopt(req->sockfd, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0);
/* Move to next state */
if (req->using_proxy && req->is_https) {
/* HTTPS via proxy: establish tunnel with CONNECT */
req->state = ASYNC_STATE_PROXY_CONNECT;
} else if (req->using_proxy && !req->is_https) {
/* HTTP via proxy: send request directly to proxy (no CONNECT needed) */
req->state = ASYNC_STATE_SENDING_REQUEST;
} else if (req->is_https) {
/* Direct HTTPS connection, do TLS handshake */
req->state = ASYNC_STATE_TLS_HANDSHAKE;
} else {
/* Direct HTTP connection, send request */
req->state = ASYNC_STATE_SENDING_REQUEST;
}
return ASYNC_STATUS_IN_PROGRESS;
}
#endif
/* Non-Windows or non-IOCP path: standard non-blocking connect */
int ret = connect(req->sockfd, (struct sockaddr*)&req->addr, req->addr_len);
if (ret == 0) {
/* Connected immediately (rare for non-blocking) */
DEBUG_PRINT("[async_request] Connected immediately (id=%lu)\n",
(unsigned long)req->id);
/* Move to next state */
if (req->using_proxy && req->is_https) {
/* HTTPS via proxy: establish tunnel with CONNECT */
req->state = ASYNC_STATE_PROXY_CONNECT;
} else if (req->using_proxy && !req->is_https) {
/* HTTP via proxy: send request directly to proxy (no CONNECT needed) */
req->state = ASYNC_STATE_SENDING_REQUEST;
} else if (req->is_https) {
/* Direct HTTPS connection, do TLS handshake */
req->state = ASYNC_STATE_TLS_HANDSHAKE;
} else {
/* Direct HTTP connection, send request */
req->state = ASYNC_STATE_SENDING_REQUEST;
}
return ASYNC_STATUS_IN_PROGRESS;
}
#ifndef _WIN32
if (errno == EINPROGRESS) {
/* Connection in progress, wait for writable */
return ASYNC_STATUS_NEED_WRITE;
}
#else
if (WSAGetLastError() == WSAEWOULDBLOCK) {
/* Connection in progress, wait for writable */
return ASYNC_STATUS_NEED_WRITE;
}
#endif
/* Connect failed immediately */
async_request_set_error(req, errno, "Connection failed");
return ASYNC_STATUS_ERROR;
}
/* Socket already exists, check if connect completed */
#ifdef _WIN32
/* For HTTPS (SSL) sockets, skip IOCP and use regular getsockopt check below */
if (req->io_engine && req->io_engine->type == IO_ENGINE_IOCP && !req->is_https &&
req->overlapped_connect != NULL) {
/* IOCP path: check the completion event (non-blocking) */
DWORD wait_result = WaitForSingleObject((HANDLE)req->iocp_completion_event, 0);
if (wait_result == WAIT_OBJECT_0) {
/* Operation completed - process result */
DEBUG_PRINT("[async_request] ConnectEx completed via dispatcher (error=%d, bytes=%lu, id=%lu)\n",
req->iocp_last_error, (unsigned long)req->iocp_bytes_transferred, (unsigned long)req->id);
/* Reset event for next operation */
ResetEvent((HANDLE)req->iocp_completion_event);
/* Check socket error to get actual connection result */
int sock_error = 0;
socklen_t len = sizeof(sock_error);
if (getsockopt(req->sockfd, SOL_SOCKET, SO_ERROR, (char*)&sock_error, &len) == 0) {
if (sock_error == 0 || sock_error == ERROR_IO_PENDING) {
/* Connection successful (ERROR_IO_PENDING is ok, means it's now connected) */
/* Update socket context (required after ConnectEx) */
setsockopt(req->sockfd, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0);
/* Move to next state */
if (req->using_proxy && req->is_https) {
/* HTTPS via proxy: establish tunnel with CONNECT */
req->state = ASYNC_STATE_PROXY_CONNECT;
/* Wait one more cycle to ensure socket is fully ready */
return ASYNC_STATUS_NEED_WRITE;
} else if (req->using_proxy && !req->is_https) {
/* HTTP via proxy: send request directly to proxy (no CONNECT needed) */
req->state = ASYNC_STATE_SENDING_REQUEST;
} else if (req->is_https) {
/* Direct HTTPS connection, do TLS handshake */
req->state = ASYNC_STATE_TLS_HANDSHAKE;
} else {
/* Direct HTTP connection, send request */
req->state = ASYNC_STATE_SENDING_REQUEST;
}
return ASYNC_STATUS_IN_PROGRESS;
} else {
/* Connection failed */
char error_buf[256];
snprintf(error_buf, sizeof(error_buf), "ConnectEx failed: %d", sock_error);
async_request_set_error(req, sock_error, error_buf);
return ASYNC_STATUS_ERROR;
}
} else {
/* Failed to get socket error */
char error_buf[256];
snprintf(error_buf, sizeof(error_buf), "Failed to get socket error after ConnectEx");
async_request_set_error(req, -1, error_buf);
return ASYNC_STATUS_ERROR;
}
} else if (wait_result == WAIT_TIMEOUT) {
/* Still pending */
return ASYNC_STATUS_NEED_WRITE;
} else {
/* Wait failed */
req->iocp_last_error = GetLastError();
char error_buf[256];
snprintf(error_buf, sizeof(error_buf), "WaitForSingleObject failed: %d", req->iocp_last_error);
async_request_set_error(req, req->iocp_last_error, error_buf);
return ASYNC_STATUS_ERROR;
}
}
/* For Windows SSL sockets (not using IOCP), check connect completion */
if (req->is_https) {
/* Use WSAPoll to check if socket is writable (connected) */
WSAPOLLFD poll_fd;
poll_fd.fd = req->sockfd;
poll_fd.events = POLLOUT; /* Check if writable */
poll_fd.revents = 0;
int poll_ret = WSAPoll(&poll_fd, 1, 0); /* 0 timeout = non-blocking */
if (poll_ret > 0) {
/* Socket has activity */
if (poll_fd.revents & POLLERR) {
/* Socket has an error */
int error = 0;
socklen_t len = sizeof(error);
getsockopt(req->sockfd, SOL_SOCKET, SO_ERROR, (char*)&error, &len);
char error_buf[256];
snprintf(error_buf, sizeof(error_buf), "Connection failed: %d", error);
async_request_set_error(req, error, error_buf);
return ASYNC_STATUS_ERROR;
}
if (poll_fd.revents & POLLOUT) {
/* Socket is writable - verify connection succeeded */
int error = 0;
socklen_t len = sizeof(error);
if (getsockopt(req->sockfd, SOL_SOCKET, SO_ERROR, (char*)&error, &len) == 0 && error == 0) {
/* Connection successful */
DEBUG_PRINT("[async_request] Connected successfully (SSL socket) (id=%lu)\n",
(unsigned long)req->id);
/* Move to next state */
if (req->using_proxy && req->is_https) {
/* HTTPS via proxy: establish tunnel with CONNECT */
req->state = ASYNC_STATE_PROXY_CONNECT;
/* Wait one more cycle to ensure socket is fully ready */
return ASYNC_STATUS_NEED_WRITE;
} else if (req->using_proxy && !req->is_https) {
/* HTTP via proxy: send request directly (no CONNECT needed) */
req->state = ASYNC_STATE_SENDING_REQUEST;
} else {
/* Direct HTTPS connection, do TLS handshake */
req->state = ASYNC_STATE_TLS_HANDSHAKE;
}
return ASYNC_STATUS_IN_PROGRESS;
} else if (error != 0) {
/* Connection failed */
char error_buf[256];
snprintf(error_buf, sizeof(error_buf), "Connection failed: %d", error);
async_request_set_error(req, error, error_buf);
return ASYNC_STATUS_ERROR;
}
}
} else if (poll_ret < 0) {
/* Poll error */
int last_error = WSAGetLastError();
char error_buf[256];
snprintf(error_buf, sizeof(error_buf), "WSAPoll failed: %d", last_error);
async_request_set_error(req, last_error, error_buf);
return ASYNC_STATUS_ERROR;
}
/* Still connecting */
return ASYNC_STATUS_NEED_WRITE;
}
#endif
#ifndef _WIN32
int error = 0;
socklen_t len = sizeof(error);
if (getsockopt(req->sockfd, SOL_SOCKET, SO_ERROR, &error, &len) == 0) {
if (error == 0) {
/* Connection successful */
DEBUG_PRINT("[async_request] Connected successfully (id=%lu)\n",
(unsigned long)req->id);
/* Move to next state */
if (req->using_proxy && req->is_https) {
/* HTTPS via proxy: establish tunnel with CONNECT */
req->state = ASYNC_STATE_PROXY_CONNECT;
} else if (req->using_proxy && !req->is_https) {
/* HTTP via proxy: send request directly to proxy (no CONNECT needed) */
req->state = ASYNC_STATE_SENDING_REQUEST;
/* For HTTP proxy, wait for socket to be writable before sending */
return ASYNC_STATUS_NEED_WRITE;
} else if (req->is_https) {
/* Direct HTTPS connection, do TLS handshake */
req->state = ASYNC_STATE_TLS_HANDSHAKE;
} else {
/* Direct HTTP connection, send request */
req->state = ASYNC_STATE_SENDING_REQUEST;
/* For plain HTTP, wait for socket to be writable before sending */
return ASYNC_STATUS_NEED_WRITE;
}
return ASYNC_STATUS_IN_PROGRESS;
} else if (error == EINPROGRESS || error == EALREADY) {
/* Still connecting, need to wait */
return ASYNC_STATUS_NEED_WRITE;
} else {
/* Connection failed */
char error_buf[256];
snprintf(error_buf, sizeof(error_buf), "Connection failed: %s", strerror(error));
async_request_set_error(req, error, error_buf);
return ASYNC_STATUS_ERROR;
}
}
#endif
/* Waiting for connection to complete */
return ASYNC_STATUS_NEED_WRITE;
}
/**
* State: TLS handshake
*/
static int step_tls_handshake(async_request_t *req) {
/* SSL object should exist for HTTPS */
if (!req->ssl) {
async_request_set_error(req, -1, "No SSL object for HTTPS");
return ASYNC_STATUS_ERROR;
}
/* Bind SSL to socket if not already done */
if (SSL_get_fd(req->ssl) != req->sockfd) {
if (SSL_set_fd(req->ssl, req->sockfd) != 1) {
async_request_set_error(req, -1, "Failed to bind SSL to socket");
return ASYNC_STATUS_ERROR;
}
/* Set connect state (client mode) */
SSL_set_connect_state(req->ssl);
DEBUG_PRINT("[async_request] SSL bound to socket fd=%d (id=%lu)\n",
req->sockfd, (unsigned long)req->id);
}
/* Perform non-blocking handshake */
int ret = SSL_do_handshake(req->ssl);
if (ret == 1) {
/* Handshake complete */
DEBUG_PRINT("[async_request] TLS handshake complete (id=%lu)\n",
(unsigned long)req->id);
req->state = ASYNC_STATE_SENDING_REQUEST;
/* Continue immediately to sending */
return ASYNC_STATUS_IN_PROGRESS;
}
/* Check error */
int err = SSL_get_error(req->ssl, ret);
switch (err) {
case SSL_ERROR_WANT_READ:
/* Need to wait for socket to be readable */
return ASYNC_STATUS_NEED_READ;
case SSL_ERROR_WANT_WRITE:
/* Need to wait for socket to be writable */
return ASYNC_STATUS_NEED_WRITE;
case SSL_ERROR_ZERO_RETURN:
/* Connection closed */
async_request_set_error(req, -1, "TLS connection closed");
return ASYNC_STATUS_ERROR;
default:
/* Other error */
{
char err_buf[256];
unsigned long ssl_err = ERR_get_error();
if (ssl_err != 0) {
ERR_error_string_n(ssl_err, err_buf, sizeof(err_buf));
snprintf(req->error_msg, sizeof(req->error_msg), "TLS handshake failed: %s", err_buf);
} else if (err == SSL_ERROR_SYSCALL) {
/* Get system error */
#ifdef _WIN32
int sys_err = WSAGetLastError();
snprintf(req->error_msg, sizeof(req->error_msg), "TLS handshake failed: system error %d (WSAERR)", sys_err);
#else
snprintf(req->error_msg, sizeof(req->error_msg), "TLS handshake failed: system error %d (errno)", errno);
#endif
} else {
snprintf(req->error_msg, sizeof(req->error_msg), "TLS handshake failed: SSL error code %d", err);
}
req->state = ASYNC_STATE_ERROR;
}
return ASYNC_STATUS_ERROR;
}
}
/**
* Build HTTP request from httpmorph_request_t structure
*/
static int build_http_request(async_request_t *req) {
httpmorph_request_t *request = req->request;
/* Method string mapping */