-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathna_net.h
1478 lines (1194 loc) · 39.3 KB
/
na_net.h
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
/*
na_net.h - v0.02
Nick Aversano's C++ networking library for TCP/UDP and HTTP
===========================================================================
LICENSE
This software is dual-licensed to the public domain and under the following
license: you are granted a perpetual, irrevocable license to copy, modify,
publish, and distribute this file as you see fit.
CREDITS
Written by Nick Aversano
VERSION HISTORY
0.02 - Update to na.h v0.07
0.01 - Initial release
*/
//
// TODO(nick):
// - handle chunked responses
// - replace `select` calls with Linux epoll / win32 / MacOS kqueue solution
// - support IPV6 addresses
// - fix HTTP server slowness on Chrome/Windows?
//
#ifndef NA_NET_H
#define NA_NET_H
typedef u32 Socket_Type;
enum
{
SocketType_TCP,
SocketType_UDP,
};
typedef struct Socket Socket;
struct Socket
{
Socket_Type type;
i64 handle;
};
typedef struct Socket_Address Socket_Address;
struct Socket_Address
{
u32 host; // ipv4
//u64 host[2]; // ipv6 requires more space
u16 port;
};
typedef u32 Http_Status;
enum
{
HttpStatus_Pending,
HttpStatus_Completed,
HttpStatus_Failed,
};
typedef struct Http Http;
struct Http
{
Socket socket;
Http_Status status;
// Request data
String request_data;
bool is_ready;
bool request_sent;
// Response data
String response_data;
String response_headers;
String response_body;
int status_code;
String content_type;
};
typedef struct Http_Header Http_Header;
struct Http_Header
{
String key;
String value;
};
typedef struct Http_Header_Array Http_Header_Array;
struct Http_Header_Array
{
i64 capacity;
i64 count;
Http_Header *data;
};
typedef struct Http_Request Http_Request;
struct Http_Request
{
Socket_Address address;
String method;
String url;
};
typedef struct Http_Response Http_Response;
struct Http_Response
{
i32 status_code;
Http_Header_Array headers;
String content_type;
String body;
};
typedef struct Http_Pool Http_Pool;
struct Http_Pool
{
Arena *arena;
struct {
Http *data;
u64 count;
u64 capacity;
} requests;
};
typedef struct Http_Server Http_Server;
struct Http_Server
{
Socket socket;
};
#define HTTP_REQUEST_CALLBACK(name) void name(Http_Request *request, Http_Response *response)
typedef HTTP_REQUEST_CALLBACK(Http_Request_Callback);
//
// Socket methods
//
function bool socket_init();
function void socket_shutdown();
function bool socket_is_valid(Socket socket);
function Socket socket_open(Socket_Type type);
function void socket_close(Socket *socket);
function bool socket_bind(Socket *socket, Socket_Address address);
function bool socket_connect(Socket *socket, Socket_Address address);
function bool socket_listen(Socket *socket);
function bool socket_accept(Socket *socket, Socket *from_socket, Socket_Address *from_address);
function bool socket_can_write(Socket *socket);
function bool socket_is_ready(Socket *socket);
function bool socket_send(Socket *socket, Socket_Address address, String message);
function i64 socket_recieve_bytes(Socket *socket, u8 *data, u64 count, Socket_Address *address);
function bool socket_recieve(Socket *socket, String *buffer, Socket_Address *address);
function String socket_recieve_entire_stream(Arena *arena, Socket *socket);
function String socket_get_address_name(Socket_Address address);
function Socket_Address socket_make_address(String host, u16 port);
function Socket_Address socket_make_address_from_url(String url);
function Socket socket_create_tcp_connection(Socket_Address address);
function Socket socket_create_udp_server(Socket_Address address);
function Socket socket_create_udp_client(Socket_Address address);
//
// HTTP methods
//
function Http http_request(String verb, String url, String headers, String data);
function Http http_get(String url);
function Http http_post(String url, String data);
function Http http_put(String url, String data);
function Http http_delete(String url);
function void http_process(Http *http);
function Http_Header_Array http_parse_headers(Arena *arena, String headers);
function Http_Request http_parse_request(String request);
function String http_status_name_from_code(i32 status_code);
function String http_content_type_from_extension(String ext);
//
// high-level HTTP APIs
//
function void http_pool_init(Http_Pool *pool);
function void http_pool_add(Http_Pool *pool, Http request);
function void http_pool_update(Http_Pool *pool);
function Http_Server http_server_init(String server_url);
function bool http_server_poll(Http_Server *server, Socket *client, Socket_Address *client_address);
function void http_server_tick(Http_Server *server, Http_Request_Callback request_handler);
function void http_server_run(String server_url, Http_Request_Callback request_handler);
//
// Implementation:
//
#if OS_WINDOWS
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include <winsock2.h>
#include <ws2tcpip.h>
// NOTE(nick): all the inet_ functions, etc, need to be loaded from the DLL
#pragma comment(lib, "ws2_32.lib")
static HMODULE w32_socket_lib;
typedef int WSAStartup_Func(WORD wVersionRequired, LPWSADATA lpWSAData);
static WSAStartup_Func *W32_WSAStartup;
typedef int WSAGetLastError_Func();
static WSAGetLastError_Func *W32_WSAGetLastError;
typedef void WSACleanup_Func();
static WSACleanup_Func *W32_WSACleanup;
#define SOCKET_WOULD_BLOCK WSAEWOULDBLOCK
#define SOCKET_IN_PROGRESS WSAEINPROGRESS
#define SOCKET_LAST_ERROR() WSAGetLastError()
#else // OS_WINDOWS
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#define SOCKET_ERROR -1
#define INVALID_SOCKET -1
#define SOCKET_WOULD_BLOCK EWOULDBLOCK
#define SOCKET_IN_PROGRESS WINPROGRESS
#define SOCKET_LAST_ERROR() errno
#endif // OS_WINDOWS
#if defined(__APPLE__)
#include <arpa/inet.h>
#define TIMEVAL struct timeval
#define SOCKADDR_IN struct sockaddr_in
#endif
typedef struct Http_URL_Parts Http_URL_Parts;
struct Http_URL_Parts
{
String protocol; // http or https
String host; // nickav.co
i64 port; // 80
String path; // robots.txt
};
function Socket_Address socket_make_address(String host, u16 port)
{
Socket_Address result = {0};
if (host.data == NULL)
{
result.host = INADDR_ANY;
}
else
{
char host_cstr[1024];
assert(host.count < count_of(host_cstr));
MemoryCopy(host_cstr, host.data, host.count);
host_cstr[host.count] = '\0';
inet_pton(AF_INET, host_cstr, &result.host);
if (result.host == 0 || result.host == INADDR_NONE)
{
struct hostent *hostent = gethostbyname(host_cstr);
if (hostent)
{
MemoryCopy(&result.host, hostent->h_addr, hostent->h_length);
result.port = port;
}
else
{
print("[socket] Invalid host name: %.*s\n", LIT(host));
}
}
/*
inet_pton(AF_INET6, host, &result.host[0]);
*/
}
return result;
}
function Http_URL_Parts http__socket_parse_url(String url)
{
Http_URL_Parts result = {0};
i64 index;
index = string_find(url, S("://"), 0, 0);
if (index < url.count)
{
result.protocol = string_slice(url, 0, index);
url = string_slice(url, index + 3, url.count);
}
index = string_find(url, S("/"), 0, 0);
if (index < url.count)
{
result.path = string_slice(url, index, url.count);
url = string_prefix(url, index);
}
result.port = 80;
index = string_find(url, S(":"), 0, 0);
if (index < url.count)
{
String port_str = string_slice(url, index + 1, url.count);
result.port = string_to_i64(port_str, 10);
if (result.port <= 0 || result.port > U16_MAX) {
result.port = 0;
}
url = string_slice(url, 0, index);
}
result.host = url;
return result;
}
static bool __socket_initted = false;
function bool socket_init()
{
if (__socket_initted) return true;
#if OS_WINDOWS
w32_socket_lib = LoadLibraryA("ws2_32.dll");
if (w32_socket_lib == 0)
{
print("[net] Failed to load ws2_32.dll\n");
return false;
}
W32_WSAStartup = (WSAStartup_Func *) GetProcAddress(w32_socket_lib, "WSAStartup");
W32_WSACleanup = (WSACleanup_Func *) GetProcAddress(w32_socket_lib, "WSACleanup");
W32_WSAGetLastError = (WSAGetLastError_Func *)GetProcAddress(w32_socket_lib, "WSAGetLastError");
if (W32_WSAStartup == 0 || W32_WSACleanup == 0 || W32_WSAGetLastError == 0)
{
print("[net] Failed to load required win32 functions\n");
return false;
}
WSADATA wsdata;
if (W32_WSAStartup(0x202, &wsdata))
{
print("WSAStartup failed: %d", W32_WSAGetLastError());
return false;
}
#endif // OS_WINDOWS
__socket_initted = true;
return true;
}
function void socket_shutdown()
{
if (!__socket_initted) return;
#if OS_WINDOWS
if (w32_socket_lib)
{
FreeLibrary(w32_socket_lib);
w32_socket_lib = 0;
}
W32_WSACleanup();
#endif // OS_WINDOWS
__socket_initted = false;
}
function bool socket__set_non_blocking(i64 handle)
{
int ret;
#if OS_WINDOWS
u_long nb = 1;
ret = ioctlsocket(handle, FIONBIO, &nb);
#else
ret = fcntl(handle, F_SETFL, O_NONBLOCK);
#endif
return ret == 0;
}
function Socket socket_open(Socket_Type type)
{
Socket result = {0};
bool udp = type == SocketType_UDP;
// AF_INET6
#if OS_WINDOWS
result.handle = WSASocket(AF_INET, udp ? SOCK_DGRAM : SOCK_STREAM, udp ? IPPROTO_UDP : IPPROTO_TCP, 0, 0, WSA_FLAG_OVERLAPPED);
#else
result.handle = socket(AF_INET, udp ? SOCK_DGRAM : SOCK_STREAM, udp ? IPPROTO_UDP : IPPROTO_TCP);
#endif
result.type = type;
if (result.handle == INVALID_SOCKET)
{
print("[socket] Failed to open socket!\n");
socket_close(&result);
return result;
}
// Set non-blocking
{
bool success = socket__set_non_blocking(result.handle);
if (!success)
{
print("[socket] Failed to set socket to non-blocking!\n");
socket_close(&result);
return result;
}
}
return result;
}
function bool socket_bind(Socket *socket, Socket_Address address)
{
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = address.host;
addr.sin_port = htons(address.port);
if (bind(socket->handle, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) != 0)
{
return false;
}
return true;
}
function bool socket_listen(Socket *socket)
{
#ifndef SOMAXCONN
#define SOMAXCONN 10
#endif
if (listen(socket->handle, SOMAXCONN) != 0)
{
return false;
}
return true;
}
function bool socket_accept(Socket *socket, Socket *from_socket, Socket_Address *from_address)
{
struct sockaddr_in from;
int addr_len = sizeof(from);
i64 sock = accept(socket->handle, (struct sockaddr *)&from, (socklen_t *)&addr_len);
if (sock != INVALID_SOCKET)
{
socket__set_non_blocking(sock);
if (from_address != NULL)
{
from_address->host = from.sin_addr.s_addr;
from_address->port = ntohs(from.sin_port);
}
if (from_socket != NULL)
{
from_socket->type = SocketType_TCP; // @Incomplete: will this always be true?
from_socket->handle = sock;
}
return true;
}
// @Incomplete
return false;
}
function bool socket_connect(Socket *socket, Socket_Address address)
{
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = address.host;
addr.sin_port = htons(address.port);
int result = connect(socket->handle, (struct sockaddr *)&addr, sizeof(addr));
if (result == SOCKET_ERROR)
{
#ifdef _WIN32
if (WSAGetLastError() != WSAEWOULDBLOCK && WSAGetLastError() != WSAEINPROGRESS)
{
return false;
}
#else
if (errno != EWOULDBLOCK && errno != EINPROGRESS && errno != EAGAIN)
{
return false;
}
#endif
}
return true;
}
function void socket_close(Socket *socket)
{
if (socket && socket->handle)
{
#if OS_WINDOWS
closesocket(socket->handle);
#else
close(socket->handle);
#endif
socket->handle = 0;
}
}
function bool socket_can_write(Socket *socket)
{
if (!socket) return false;
fd_set write_fds;
FD_ZERO(&write_fds);
FD_SET(socket->handle, &write_fds);
TIMEVAL timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
int result = select(0, NULL, &write_fds, NULL, &timeout);
if (result > 0)
{
if (FD_ISSET(socket->handle, &write_fds))
{
return true;
}
}
return false;
}
// @Cleanup @Incomplete: socket_is_ready should really be socket_is_ready_to_write
// Also merge this with socket_can_write if possible??
function bool socket_is_ready(Socket *socket)
{
if (!socket) return false;
fd_set write_fds;
FD_ZERO(&write_fds);
FD_SET(socket->handle, &write_fds);
TIMEVAL timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
// select returns the number of file descriptors
int result = select(0, NULL, &write_fds, NULL, &timeout);
return result > 0;
}
function bool socket_send(Socket *socket, Socket_Address address, String message)
{
if (!socket) return false;
if (socket->type == SocketType_UDP)
{
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = address.host;
addr.sin_port = htons(address.port);
int sent_bytes = sendto(socket->handle, (char *)message.data, message.count, 0, (struct sockaddr *)&addr, sizeof(addr));
if (sent_bytes < 0)
{
return false;
}
// @Incomplete: should this send the message in chunks?
if (sent_bytes != message.count)
{
return false;
}
return true;
}
else
{
// @Incomplete: non-blocking TCP
int sent_bytes = send(socket->handle, (char *)message.data, message.count, 0);
if (sent_bytes < 0)
{
return false;
}
// @Incomplete: check errno == EAGAIN or errno == EWOULDBLOCK
// and use select to determine when we can send again?
if (sent_bytes != message.count)
{
u8 *data = message.data + sent_bytes;
while (sent_bytes < message.count)
{
i64 bytes_remaining = message.count - sent_bytes;
i64 s = send(socket->handle, (char *)(message.data + sent_bytes), bytes_remaining, 0);
if (s > 0)
{
sent_bytes += s;
}
}
return true;
}
return true;
}
}
function i64 socket_recieve_bytes(Socket *socket, u8 *data, u64 count, Socket_Address *address)
{
if (!socket) return false;
if (!data || count == 0)
{
print("[socket] Recive must have a buffer of non-zero size!\n");
return 0;
}
if (socket->type == SocketType_UDP)
{
SOCKADDR_IN from;
int from_size = sizeof(from);
int bytes_received = recvfrom(
socket->handle,
(char *)data, count, 0, (struct sockaddr *)&from, (socklen_t *)&from_size
);
if (address != NULL)
{
address->host = from.sin_addr.s_addr;
address->port = ntohs(from.sin_port);
}
return bytes_received;
}
else
{
// @Incomplete: non-blocking TCP?
int bytes_received = recv(socket->handle, (char *)data, count, 0);
return bytes_received;
}
}
function bool socket_recieve(Socket *socket, String *buffer, Socket_Address *address)
{
i64 count = socket_recieve_bytes(socket, buffer->data, buffer->count, address);
if (count >= 0)
{
buffer->count = count;
}
return count > 0;
}
function String socket_recieve_entire_stream(Arena *arena, Socket *socket)
{
i64 bytes_received = 0;
i64 buffer_size = 4096;
u8 *buffer = PushArray(arena, u8, buffer_size);
u8 *at = buffer;
for (;;)
{
i64 count = socket_recieve_bytes(socket, at, buffer_size, NULL);
if (count <= 0)
{
// @Incomplete: test this?
if (bytes_received > 0) break;
else continue;
}
bytes_received += count;
at += count;
buffer_size += 4096;
assert(arena_push(arena, buffer_size));
}
arena_pop(arena, buffer_size - bytes_received);
return string_make(buffer, bytes_received);
}
function String socket_get_address_name(Socket_Address address)
{
char ip4[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &address.host, ip4, INET_ADDRSTRLEN);
/*
char ip6[INET6_ADDRSTRLEN];
u64 host_ipv6[2];
inet_ntop(AF_INET6, &host_ipv6, ip6, INET6_ADDRSTRLEN);
*/
return string_from_cstr(ip4);
}
function bool socket_is_valid(Socket socket)
{
// @Incomplete @Robustness: can valid socket handles be 0?
return socket.handle != INVALID_SOCKET && socket.handle != 0;
}
function Socket_Address socket_make_address_from_url(String url)
{
Http_URL_Parts parts = http__socket_parse_url(url);
Socket_Address result = socket_make_address(parts.host, parts.port);
return result;
}
function Socket socket_create_udp_server(Socket_Address address)
{
Socket result = socket_open(SocketType_UDP);
if (!socket_bind(&result, address))
{
String url = socket_get_address_name(address);
print("[socket] Failed to bind to address: %S\n", url);
socket_close(&result);
return result;
}
return result;
}
function Socket socket_create_udp_client(Socket_Address address)
{
Socket result = socket_open(SocketType_UDP);
//socket_bind(&result, socket_make_address(0, 0));
if (!socket_connect(&result, address))
{
String url = socket_get_address_name(address);
print("[socket] Failed to connect to server address: %S\n", url);
socket_close(&result);
return result;
}
return result;
}
function Socket socket_create_tcp_server(Socket_Address address)
{
Socket result = socket_open(SocketType_TCP);
if (!socket_bind(&result, address))
{
String url = socket_get_address_name(address);
print("[socket] Failed to bind to address: %S:%d\n", url, address.port);
socket_close(&result);
return result;
}
if (!socket_listen(&result))
{
print("[socket] Failed to listen\n");
socket_close(&result);
return result;
}
return result;
}
//
// HTTP methods
//
function Http http_get(String url)
{
return http_request(S("GET"), url, S(""), S(""));
}
function Http http_post(String url, String data)
{
return http_request(S("POST"), url, S(""), data);
}
function Http http_put(String url, String data)
{
return http_request(S("PUT"), url, S(""), data);
}
function Http http_delete(String url)
{
return http_request(S("DELETE"), url, S(""), S(""));
}
function Http http_request(String verb, String url, String headers, String data)
{
Http result = {0};
Http_URL_Parts parts = http__socket_parse_url(url);
if (!parts.path.count)
{
parts.path = S("/");
}
if (parts.protocol.count > 0 && !string_equals(parts.protocol, S("http")))
{
print("[http] Protocol not supported: %S\n", parts.protocol);
result.status = HttpStatus_Failed;
return result;
}
if (parts.port == 0)
{
print("[http] Invalid port\n");
result.status = HttpStatus_Failed;
return result;
}
Socket_Address address = socket_make_address(parts.host, parts.port);
result.socket = socket_open(SocketType_TCP);
if (!socket_connect(&result.socket, address))
{
print("[http] Failed to connect to TCP socket\n");
socket_close(&result.socket);
result.status = HttpStatus_Failed;
return result;
}
assert(string_starts_with(parts.path, S("/")));
String array[10] = {0};
u32 count = 0;
array[count++] = sprint("%S %S HTTP/1.0\r\nHost: %S:%d\r\n", verb, parts.path, parts.host, parts.port);
if (data.count)
{
array[count++] = sprint("Content-Length: %d", data.count);
}
if (headers.count)
{
array[count++] = headers;
}
array[count++] = S("\r\n\r\n");
if (data.count)
{
array[count++] = data;
}
assert(count < count_of(array));
String request_data = string_alloc(string_concat_array(temp_arena(), array, count));
result.request_data = request_data;
result.status = HttpStatus_Pending;
return result;
}
function Http_Header_Array http_parse_headers(Arena *arena, String headers)
{
Http_Header_Array results = {0};
String_List lines = string_split(arena, headers, S("\r\n"));
results.count = 0;
results.capacity = lines.node_count;
results.data = PushArray(arena, Http_Header, lines.node_count);
for (String_Node *node = lines.first; node != NULL; node = node->next)
{
String line = node->string;
i64 index = string_find(line, S(":"), 0, 0);
if (index < line.count)
{
Http_Header *it = &results.data[results.count];
results.count += 1;
it->key = string_slice(line, 0, index);
it->value = string_trim_whitespace(string_slice(line, index + 1, line.count));
}
}
return results;
}
function Http_Request http_parse_request(String request)
{
Http_Request result = {0};
i64 index;
index = string_find(request, S("\r\n"), 0, 0);
if (index < request.count)
{
request = string_slice(request, 0, index);
}
index = string_find(request, S(" "), 0, 0);
if (index < request.count)
{
result.method = string_slice(request, 0, index);
i64 index2 = string_find(request, S(" "), index + 1, 0);
if (index2 < request.count)
{
result.url = string_slice(request, index + 1, index2);
}
}
return result;
}
function void http_process(Http *http)
{
if (http->status == HttpStatus_Failed || http->status == HttpStatus_Completed)
{
return;
}
if (!http->is_ready)
{
if (socket_is_ready(&http->socket))
{
http->is_ready = true;
}
}
if (!http->is_ready) return;
if (!http->request_sent)
{
if (!socket_send(&http->socket, Socket_Address{0, 0}, http->request_data))
{
http->status = HttpStatus_Failed;
return;
}
string_free(&http->request_data);
http->request_sent = true;
return;
}
// NOTE(nick): it seems like having this structure created _before_ the while loop
// is actually critical to returning all the data needed from the response!
// Otherwise, we were only getting parts of it sometimes, so we couldn't just return it all in one go
fd_set sockets_to_check;
FD_ZERO(&sockets_to_check);
FD_SET(http->socket.handle, &sockets_to_check);
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
while (select(0, &sockets_to_check, NULL, NULL, &timeout) > 0)
{
Arena *arena = temp_arena();
i64 bytes_received = 0;
i64 buffer_size = 4096;
u8 *buffer = PushArray(arena, u8, buffer_size);
u8 *at = buffer;
for (;;)
{
i64 count = socket_recieve_bytes(&http->socket, at, buffer_size, NULL);
if (count <= 0) break;
bytes_received += count;
at += count;
buffer_size *= 2;
assert(arena_push(arena, buffer_size));
}