-
Notifications
You must be signed in to change notification settings - Fork 48
/
SDL_net.c
1697 lines (1436 loc) · 53.7 KB
/
SDL_net.c
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
/*
SDL_net: A simple networking library for use with SDL
Copyright (C) 1997-2024 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifdef _WIN32
#ifdef _WIN32_WINNT
# if _WIN32_WINNT < 0x0600 // we need APIs that didn't arrive until Windows Vista.
# undef _WIN32_WINNT
# endif
#endif
#ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x0600
#endif
#endif /* _WIN32 */
#include "SDL3_net/SDL_net.h"
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN 1
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
typedef SOCKET Socket;
typedef int SockLen;
typedef SOCKADDR_STORAGE AddressStorage;
static int write(SOCKET s, const void *buf, size_t count) {
return send(s, (const char *)buf, (int) count, 0);
}
static int read(SOCKET s, char *buf, size_t count) {
WSABUF wsabuf;
wsabuf.buf = buf;
wsabuf.len = (ULONG) count;
DWORD count_received;
DWORD flags = 0;
const int res = WSARecv(s, &wsabuf, 1, &count_received, &flags, NULL, NULL);
if (res != 0) {
return -1;
}
return (int)count_received;
}
#define poll WSAPoll
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <poll.h>
#include <unistd.h>
#include <fcntl.h>
#include <ifaddrs.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
typedef int Socket;
typedef socklen_t SockLen;
typedef struct sockaddr_storage AddressStorage;
#endif
typedef enum SDLNet_SocketType
{
SOCKETTYPE_STREAM,
SOCKETTYPE_DATAGRAM,
SOCKETTYPE_SERVER
} SDLNet_SocketType;
int SDLNet_Version(void)
{
return SDL_NET_VERSION;
}
struct SDLNet_Address
{
char *hostname;
char *human_readable;
char *errstr;
SDL_AtomicInt refcount;
SDL_AtomicInt status; // 0==in progress, 1==resolved, -1==error
struct addrinfo *ainfo;
SDLNet_Address *resolver_next; // a linked list for the resolution job queue.
};
#define MIN_RESOLVER_THREADS 2
#define MAX_RESOLVER_THREADS 10
static SDLNet_Address *resolver_queue = NULL;
static SDL_Thread *resolver_threads[MAX_RESOLVER_THREADS];
static SDL_Mutex *resolver_lock = NULL;
static SDL_Condition *resolver_condition = NULL;
static SDL_AtomicInt resolver_shutdown;
static SDL_AtomicInt resolver_num_threads;
static SDL_AtomicInt resolver_num_requests;
static SDL_AtomicInt resolver_percent_loss;
// I really want an SDL_random(). :(
static int random_seed = 0;
static int RandomNumber(void)
{
// this is POSIX.1-2001's potentially bad suggestion, but we're not exactly doing cryptography here.
random_seed = random_seed * 1103515245 + 12345;
return (int) ((unsigned int) (random_seed / 65536) % 32768);
}
// between lo and hi (inclusive; it can return lo or hi itself, too!).
static int RandomNumberBetween(const int lo, const int hi)
{
return (RandomNumber() % (hi + 1 - lo)) + lo;
}
static int CloseSocketHandle(Socket handle)
{
#ifdef _WIN32
return closesocket(handle);
#else
return close(handle);
#endif
}
static int LastSocketError(void)
{
#ifdef _WIN32
return WSAGetLastError();
#else
return errno;
#endif
}
static char *CreateSocketErrorString(int rc)
{
#ifdef _WIN32
WCHAR msgbuf[256];
const DWORD bw = FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
rc,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
msgbuf,
SDL_arraysize(msgbuf),
NULL
);
if (bw == 0) {
return SDL_strdup("Unknown error");
}
return SDL_iconv_string("UTF-8", "UTF-16LE", (const char *)msgbuf, (((size_t) bw)+1) * sizeof (WCHAR));
#else
return SDL_strdup(strerror(rc));
#endif
}
static char *CreateGetAddrInfoErrorString(int rc)
{
#ifdef _WIN32
return CreateSocketErrorString(rc); // same error codes.
#else
return SDL_strdup((rc == EAI_SYSTEM) ? strerror(errno) : gai_strerror(rc));
#endif
}
static int SetSocketError(const char *msg, int err)
{
char *errmsg = CreateSocketErrorString(err);
SDL_SetError("%s: %s", msg, errmsg);
SDL_free(errmsg);
return -1;
}
static int SetLastSocketError(const char *msg)
{
return SetSocketError(msg, LastSocketError());
}
static int SetGetAddrInfoError(const char *msg, int err)
{
char *errmsg = CreateGetAddrInfoErrorString(err);
SDL_SetError("%s: %s", msg, errmsg);
SDL_free(errmsg);
return -1;
}
// this blocks!
static int ResolveAddress(SDLNet_Address *addr)
{
SDL_assert(addr != NULL); // we control all this, so this shouldn't happen.
struct addrinfo *ainfo = NULL;
int rc;
//SDL_Log("getaddrinfo '%s'", addr->hostname);
rc = getaddrinfo(addr->hostname, NULL, NULL, &ainfo);
//SDL_Log("rc=%d", rc);
if (rc != 0) {
addr->errstr = CreateGetAddrInfoErrorString(rc);
return -1; // error
} else if (ainfo == NULL) {
addr->errstr = SDL_strdup("Unknown error (query succeeded but result was NULL!)");
return -1;
}
char buf[128];
rc = getnameinfo(ainfo->ai_addr, ainfo->ai_addrlen, buf, sizeof (buf), NULL, 0, NI_NUMERICHOST);
if (rc != 0) {
addr->errstr = CreateGetAddrInfoErrorString(rc);
freeaddrinfo(ainfo);
return -1; // error
}
addr->human_readable = SDL_strdup(buf);
addr->ainfo = ainfo;
return 1; // success (zero means "still in progress").
}
static int SDLCALL ResolverThread(void *data)
{
const int threadnum = (int) ((intptr_t) data);
//SDL_Log("ResolverThread #%d starting up!", threadnum);
SDL_LockMutex(resolver_lock);
while (!SDL_AtomicGet(&resolver_shutdown)) {
SDLNet_Address *addr = SDL_AtomicGetPtr((void **) &resolver_queue);
if (!addr) {
if (SDL_AtomicGet(&resolver_num_threads) > MIN_RESOLVER_THREADS) { // nothing pending and too many threads waiting in reserve? Quit.
SDL_DetachThread(resolver_threads[threadnum]); // detach ourselves so no one has to wait on us.
SDL_AtomicSetPtr((void **) &resolver_threads[threadnum], NULL);
break; // we quit. They'll spawn new threads if necessary.
}
// Block until there's something to do.
SDL_WaitCondition(resolver_condition, resolver_lock); // surrenders the lock, sleeps until alerted, then relocks.
continue; // check for shutdown and new work again!
}
SDL_AtomicSetPtr((void **) &resolver_queue, addr->resolver_next); // take this task off the list, then release the lock so others can work.
SDL_UnlockMutex(resolver_lock);
//SDL_Log("ResolverThread #%d got new task ('%s')", threadnum, addr->hostname);
const int simulated_loss = SDL_AtomicGet(&resolver_percent_loss);
if (simulated_loss && (RandomNumberBetween(0, 100) > simulated_loss)) {
// won the percent_loss lottery? Delay resolving this address between 250 and 7000 milliseconds
SDL_Delay(RandomNumberBetween(250, 2000 + (50 * simulated_loss)));
}
int outcome;
if (!simulated_loss || (RandomNumberBetween(0, 100) > simulated_loss)) {
outcome = ResolveAddress(addr);
} else {
outcome = -1;
addr->errstr = SDL_strdup("simulated failure");
}
SDL_AtomicSet(&addr->status, outcome);
//SDL_Log("ResolverThread #%d finished current task (%s, '%s' => '%s')", threadnum, (outcome < 0) ? "failure" : "success", addr->hostname, (outcome < 0) ? addr->errstr : addr->human_readable);
SDLNet_UnrefAddress(addr); // we're done with it, but others might still own it.
SDL_AtomicAdd(&resolver_num_requests, -1);
// okay, we're done with this task, grab the lock so we can see what's next.
SDL_LockMutex(resolver_lock);
SDL_BroadcastCondition(resolver_condition); // wake up anything waiting on results, and also give all resolver threads a chance to see if they are still needed.
}
SDL_AtomicAdd(&resolver_num_threads, -1);
SDL_UnlockMutex(resolver_lock); // we're quitting, let go of the lock.
//SDL_Log("ResolverThread #%d ending!", threadnum);
return 0;
}
static SDL_Thread *SpinResolverThread(const int num)
{
char name[16];
SDL_snprintf(name, sizeof (name), "SDLNetRslv%d", num);
SDL_assert(resolver_threads[num] == NULL);
SDL_AtomicAdd(&resolver_num_threads, 1);
const SDL_PropertiesID props = SDL_CreateProperties();
SDL_SetProperty(props, SDL_PROP_THREAD_CREATE_ENTRY_FUNCTION_POINTER, (void *) ResolverThread);
SDL_SetStringProperty(props, SDL_PROP_THREAD_CREATE_NAME_STRING, name);
SDL_SetProperty(props, SDL_PROP_THREAD_CREATE_USERDATA_POINTER, (void *) ((intptr_t) num));
SDL_SetNumberProperty(props, SDL_PROP_THREAD_CREATE_STACKSIZE_NUMBER, 64 * 1024);
resolver_threads[num] = SDL_CreateThreadWithProperties(props);
SDL_DestroyProperties(props);
if (!resolver_threads[num]) {
SDL_AtomicAdd(&resolver_num_threads, -1);
}
return resolver_threads[num];
}
static void DestroyAddress(SDLNet_Address *addr)
{
if (addr) {
if (addr->ainfo) {
freeaddrinfo(addr->ainfo);
}
SDL_free(addr->hostname);
SDL_free(addr->human_readable);
SDL_free(addr->errstr);
SDL_free(addr);
}
}
static SDLNet_Address *CreateSDLNetAddrFromSockAddr(struct sockaddr *saddr, SockLen saddrlen)
{
// !!! FIXME: this all seems inefficient in the name of keeping addresses generic.
char hostbuf[128];
int gairc = getnameinfo(saddr, saddrlen, hostbuf, sizeof (hostbuf), NULL, 0, NI_NUMERICHOST);
if (gairc != 0) {
SetGetAddrInfoError("Failed to determine address", gairc);
return NULL;
}
SDLNet_Address *addr = (SDLNet_Address *) SDL_calloc(1, sizeof (SDLNet_Address));
if (!addr) {
return NULL;
}
SDL_AtomicSet(&addr->status, 1);
struct addrinfo hints;
SDL_zero(hints);
hints.ai_family = saddr->sa_family;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = 0;
hints.ai_flags = AI_NUMERICHOST;
gairc = getaddrinfo(hostbuf, NULL, &hints, &addr->ainfo);
if (gairc != 0) {
SDL_free(addr);
SetGetAddrInfoError("Failed to determine address", gairc);
return NULL;
}
addr->human_readable = SDL_strdup(hostbuf);
if (!addr->human_readable) {
freeaddrinfo(addr->ainfo);
SDL_free(addr);
return NULL;
}
return SDLNet_RefAddress(addr);
}
static SDL_AtomicInt initialize_count;
int SDLNet_Init(void)
{
if (SDL_AtomicAdd(&initialize_count, 1) > 0) {
return 0; // already initialized, call it a success.
}
char *origerrstr = NULL;
#ifdef _WIN32
WSADATA data;
if (WSAStartup(MAKEWORD(1, 1), &data) != 0) {
return SetSocketError("WSAStartup() failed", LastSocketError());
}
#else
signal(SIGPIPE, SIG_IGN);
#endif
SDL_zeroa(resolver_threads);
SDL_AtomicSet(&resolver_shutdown, 0);
SDL_AtomicSet(&resolver_num_threads, 0);
SDL_AtomicSet(&resolver_num_requests, 0);
SDL_AtomicSet(&resolver_percent_loss, 0);
resolver_queue = NULL;
resolver_lock = SDL_CreateMutex();
if (!resolver_lock) {
goto failed;
}
resolver_condition = SDL_CreateCondition();
if (!resolver_condition) {
goto failed;
}
for (int i = 0; i < MIN_RESOLVER_THREADS; i++) {
if (!SpinResolverThread(i)) {
goto failed;
}
}
random_seed = (int) ((unsigned int) (SDL_GetPerformanceCounter() & 0xFFFFFFFF));
return 0; // good to go.
failed:
origerrstr = SDL_strdup(SDL_GetError());
SDLNet_Quit();
if (origerrstr) {
SDL_SetError("%s", origerrstr);
SDL_free(origerrstr);
}
return -1;
}
void SDLNet_Quit(void)
{
const int prevcount = SDL_AtomicAdd(&initialize_count, -1);
if (prevcount <= 0) {
SDL_AtomicAdd(&initialize_count, 1); // bump back up.
return; // we weren't initialized!
} else if (prevcount > 1) {
return; // need to quit more, to match previous init calls.
}
if (resolver_lock && resolver_condition) {
SDL_LockMutex(resolver_lock);
SDL_AtomicSet(&resolver_shutdown, 1);
for (int i = 0; i < ((int) SDL_arraysize(resolver_threads)); i++) {
if (resolver_threads[i]) {
SDL_BroadcastCondition(resolver_condition);
SDL_UnlockMutex(resolver_lock);
SDL_WaitThread(resolver_threads[i], NULL);
SDL_LockMutex(resolver_lock);
resolver_threads[i] = NULL;
}
}
SDL_UnlockMutex(resolver_lock);
}
SDL_AtomicSet(&resolver_shutdown, 0);
SDL_AtomicSet(&resolver_num_threads, 0);
SDL_AtomicSet(&resolver_num_requests, 0);
SDL_AtomicSet(&resolver_percent_loss, 0);
if (resolver_condition) {
SDL_DestroyCondition(resolver_condition);
resolver_condition = NULL;
}
if (resolver_lock) {
SDL_DestroyMutex(resolver_lock);
resolver_lock = NULL;
}
resolver_queue = NULL;
#ifdef _WIN32
WSACleanup();
#endif
}
SDLNet_Address *SDLNet_ResolveHostname(const char *host)
{
SDLNet_Address *addr = SDL_calloc(1, sizeof (SDLNet_Address));
if (!addr) {
return NULL;
}
addr->hostname = SDL_strdup(host);
if (!addr->hostname) {
SDL_free(addr);
return NULL;
}
SDL_AtomicSet(&addr->refcount, 2); // one for creation, one for the resolver thread to unref when done.
SDL_LockMutex(resolver_lock);
// !!! FIXME: this should append to the list, not prepend; as is, new requests will make existing pending requests take longer to start processing.
SDL_AtomicSetPtr((void **) &addr->resolver_next, SDL_AtomicGetPtr((void **) &resolver_queue));
SDL_AtomicSetPtr((void **) &resolver_queue, addr);
const int num_threads = SDL_AtomicGet(&resolver_num_threads);
const int num_requests = SDL_AtomicAdd(&resolver_num_requests, 1) + 1;
//SDL_Log("num_threads=%d, num_requests=%d", num_threads, num_requests);
if ((num_requests >= num_threads) && (num_threads < MAX_RESOLVER_THREADS)) { // all threads are busy? Maybe spawn a new one.
// if this didn't actually spin one up, it is what it is...the existing threads will eventually get there.
for (int i = 0; i < ((int) SDL_arraysize(resolver_threads)); i++) {
if (!resolver_threads[i]) {
SpinResolverThread(i);
break;
}
}
}
SDL_SignalCondition(resolver_condition);
SDL_UnlockMutex(resolver_lock);
return addr;
}
int SDLNet_WaitUntilResolved(SDLNet_Address *addr, Sint32 timeout)
{
if (!addr) {
return SDL_InvalidParamError("address"); // obviously nothing to wait for.
}
// we _could_ use a different lock for this, but this is Good Enough.
if (timeout) {
SDL_LockMutex(resolver_lock);
if (timeout < 0) {
while (SDL_AtomicGet(&addr->status) == 0) {
SDL_WaitCondition(resolver_condition, resolver_lock);
}
} else {
const Uint64 endtime = (SDL_GetTicks() + timeout);
SDL_LockMutex(resolver_lock);
while (SDL_AtomicGet(&addr->status) == 0) {
const Uint64 now = SDL_GetTicks();
if (now >= endtime) {
break;
}
SDL_WaitConditionTimeout(resolver_condition, resolver_lock, (Uint64) (endtime - now));
}
}
SDL_UnlockMutex(resolver_lock);
}
return SDLNet_GetAddressStatus(addr); // so we set the error string if necessary.
}
int SDLNet_GetAddressStatus(SDLNet_Address *addr)
{
if (!addr) {
return SDL_InvalidParamError("address");
}
const int retval = SDL_AtomicGet(&addr->status);
if (retval == -1) {
SDL_SetError("%s", (const char *) SDL_AtomicGetPtr((void **) &addr->errstr));
}
return retval;
}
const char *SDLNet_GetAddressString(SDLNet_Address *addr)
{
if (!addr) {
SDL_InvalidParamError("address");
return NULL;
}
const char *retval = (const char *) SDL_AtomicGetPtr((void **) &addr->human_readable);
if (!retval) {
const int rc = SDLNet_GetAddressStatus(addr);
if (rc != -1) { // if -1, it'll set the error message.
SDL_SetError("Address not yet resolved"); // if this resolved in a race condition, too bad, try again.
}
}
return retval;
}
int SDLNet_CompareAddresses(const SDLNet_Address *sdlneta, const SDLNet_Address *sdlnetb)
{
const struct addrinfo *a;
const struct addrinfo *b;
if (sdlneta == sdlnetb) { // same pointer?
return 0;
} else if (sdlneta && !sdlnetb) {
return -1;
} else if (!sdlneta && sdlnetb) {
return 1;
}
a = sdlneta->ainfo;
b = sdlnetb->ainfo;
if (a == b) { // same pointer?
return 0;
} else if (a && !b) {
return -1;
} else if (!a && b) {
return 1;
} else if (a->ai_family < b->ai_family) {
return -1;
} else if (a->ai_family > b->ai_family) {
return 1;
} else if (a->ai_addrlen < b->ai_addrlen) {
return -1;
} else if (a->ai_addrlen > b->ai_addrlen) {
return 1;
}
return SDL_memcmp(a->ai_addr, b->ai_addr, a->ai_addrlen);
}
SDLNet_Address *SDLNet_RefAddress(SDLNet_Address *addr)
{
if (addr) {
SDL_AtomicIncRef(&addr->refcount);
}
return addr;
}
void SDLNet_UnrefAddress(SDLNet_Address *addr)
{
if (addr && SDL_AtomicDecRef(&addr->refcount)) {
DestroyAddress(addr);
}
}
void SDLNet_SimulateAddressResolutionLoss(int percent_loss)
{
percent_loss = SDL_min(100, percent_loss);
percent_loss = SDL_max(0, percent_loss);
SDL_AtomicSet(&resolver_percent_loss, percent_loss);
}
SDLNet_Address **SDLNet_GetLocalAddresses(int *num_addresses)
{
int count = 0;
SDLNet_Address **retval = NULL;
int dummy_addresses;
if (!num_addresses) {
num_addresses = &dummy_addresses;
}
*num_addresses = 0;
#ifdef _WIN32
// !!! FIXME: maybe LoadLibrary(iphlpapi) on the first call, since most
// !!! FIXME: things won't ever use this.
// MSDN docs say start with a 15K buffer, which usually works on the first
// try, instead of trying to query for size, allocate, and then retry,
// since this tends to be more expensive.
ULONG buflen = 15 * 1024;
IP_ADAPTER_ADDRESSES *addrs = NULL;
ULONG rc;
do {
SDL_free(addrs);
addrs = (IP_ADAPTER_ADDRESSES *) SDL_malloc(buflen);
if (!addrs) {
return NULL;
}
const ULONG flags = GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME;
rc = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, addrs, &buflen);
} while (rc == ERROR_BUFFER_OVERFLOW);
if (rc != NO_ERROR) {
SetSocketError("GetAdaptersAddresses failed", rc);
SDL_free(addrs);
return NULL;
}
for (IP_ADAPTER_ADDRESSES *i = addrs; i != NULL; i = i->Next) {
for (IP_ADAPTER_UNICAST_ADDRESS *j = i->FirstUnicastAddress; j != NULL; j = j->Next) {
count++;
}
}
retval = (SDLNet_Address **) SDL_calloc(((size_t)count) + 1, sizeof (SDLNet_Address *));
if (!retval) {
SDL_free(addrs);
return NULL;
}
count = 0;
for (IP_ADAPTER_ADDRESSES *i = addrs; i != NULL; i = i->Next) {
for (IP_ADAPTER_UNICAST_ADDRESS *j = i->FirstUnicastAddress; j != NULL; j = j->Next) {
SDLNet_Address *addr = CreateSDLNetAddrFromSockAddr(j->Address.lpSockaddr, j->Address.iSockaddrLength);
if (addr) {
retval[count++] = addr;
}
}
}
SDL_free(addrs);
#else
struct ifaddrs *ifaddr;
if (getifaddrs(&ifaddr) == -1) {
SDL_SetError("getifaddrs failed: %s", strerror(errno));
return NULL; // oh well.
}
for (struct ifaddrs *i = ifaddr; i != NULL; i = i->ifa_next) {
if (i->ifa_name != NULL) {
count++;
}
}
retval = (SDLNet_Address **) SDL_calloc(count + 1, sizeof (SDLNet_Address *));
if (!retval) {
if (ifaddr) {
freeifaddrs(ifaddr);
}
return NULL;
}
count = 0;
for (struct ifaddrs *i = ifaddr; i != NULL; i = i->ifa_next) {
if (i->ifa_name != NULL) {
SDLNet_Address *addr = NULL;
// !!! FIXME: getifaddrs doesn't return the sockaddr length, so we have to go with known protocols. :/
if (i->ifa_addr->sa_family == AF_INET) {
addr = CreateSDLNetAddrFromSockAddr(i->ifa_addr, sizeof (struct sockaddr_in));
} else if (i->ifa_addr->sa_family == AF_INET6) {
addr = CreateSDLNetAddrFromSockAddr(i->ifa_addr, sizeof (struct sockaddr_in6));
}
if (addr) {
retval[count++] = addr;
}
}
}
if (ifaddr) {
freeifaddrs(ifaddr);
}
#endif
*num_addresses = count;
// try to shrink allocation.
void *ptr = SDL_realloc(retval, (((size_t) count) + 1) * sizeof (SDLNet_Address *));
if (ptr) {
retval = (SDLNet_Address **) ptr;
}
return retval;
}
void SDLNet_FreeLocalAddresses(SDLNet_Address **addresses)
{
if (addresses) {
for (int i = 0; addresses[i] != NULL; i++) {
SDLNet_UnrefAddress(addresses[i]);
}
SDL_free(addresses);
}
}
static struct addrinfo *MakeAddrInfoWithPort(const SDLNet_Address *addr, const int socktype, const Uint16 port)
{
const struct addrinfo *ainfo = addr ? addr->ainfo : NULL;
SDL_assert(!addr || ainfo);
// we need to set up a sockaddr with the port in it for connect(), etc, which is kind of a pain, since we
// want to keep things generic and also not set up a port at resolve time.
struct addrinfo hints;
SDL_zero(hints);
hints.ai_family = ainfo ? ainfo->ai_family : AF_UNSPEC;
hints.ai_socktype = socktype;
//hints.ai_protocol = ainfo ? ainfo->ai_protocol : 0;
hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV | (!ainfo ? AI_PASSIVE : 0);
char service[16];
SDL_snprintf(service, sizeof (service), "%d", (int) port);
struct addrinfo *addrwithport = NULL;
int rc = getaddrinfo(addr ? addr->human_readable : NULL, service, &hints, &addrwithport);
if (rc != 0) {
char *errstr = CreateGetAddrInfoErrorString(rc);
SDL_SetError("Failed to prepare address with port: %s", errstr);
SDL_free(errstr);
return NULL;
}
return addrwithport;
}
struct SDLNet_StreamSocket
{
SDLNet_SocketType socktype;
SDLNet_Address *addr;
Uint16 port;
Socket handle;
int status;
Uint8 *pending_output_buffer;
int pending_output_len;
int pending_output_allocation;
int percent_loss;
Uint64 simulated_failure_until;
};
static int MakeSocketNonblocking(Socket handle)
{
#ifdef _WIN32
DWORD one = 1;
return ioctlsocket(handle, FIONBIO, &one);
#else
return fcntl(handle, F_SETFL, fcntl(handle, F_GETFL, 0) | O_NONBLOCK);
#endif
}
static SDL_bool WouldBlock(const int err)
{
#ifdef _WIN32
return (err == WSAEWOULDBLOCK) ? SDL_TRUE : SDL_FALSE;
#else
return ((err == EWOULDBLOCK) || (err == EAGAIN) || (err == EINPROGRESS)) ? SDL_TRUE : SDL_FALSE;
#endif
}
SDLNet_StreamSocket *SDLNet_CreateClient(SDLNet_Address *addr, Uint16 port)
{
if (addr == NULL) {
SDL_InvalidParamError("address");
return NULL;
} else if (SDL_AtomicGet(&addr->status) != 1) {
SDL_SetError("Address is not resolved");
return NULL;
}
SDLNet_StreamSocket *sock = (SDLNet_StreamSocket *) SDL_calloc(1, sizeof (SDLNet_StreamSocket));
if (!sock) {
return NULL;
}
sock->socktype = SOCKETTYPE_STREAM;
sock->addr = addr;
sock->port = port;
// we need to set up a sockaddr with the port in it for connect(), which is kind of a pain, since we
// want to keep things generic and also not set up a port at resolve time.
struct addrinfo *addrwithport = MakeAddrInfoWithPort(addr, SOCK_STREAM, port);
if (!addrwithport) {
SDL_free(sock);
return NULL;
}
sock->handle = socket(addrwithport->ai_family, addrwithport->ai_socktype, addrwithport->ai_protocol);
if (sock->handle == INVALID_SOCKET) {
SetLastSocketError("Failed to create socket");
freeaddrinfo(addrwithport);
SDL_free(sock);
return NULL;
}
if (MakeSocketNonblocking(sock->handle) < 0) {
CloseSocketHandle(sock->handle);
freeaddrinfo(addrwithport);
SDL_free(sock);
SDL_SetError("Failed to make new socket non-blocking");
return NULL;
}
const int rc = connect(sock->handle, addrwithport->ai_addr, addrwithport->ai_addrlen);
freeaddrinfo(addrwithport);
if (rc == SOCKET_ERROR) {
const int err = LastSocketError();
if (!WouldBlock(err)) {
SetSocketError("Connection failed at startup", err);
CloseSocketHandle(sock->handle);
SDL_free(sock);
return NULL;
}
}
SDLNet_RefAddress(addr);
return sock;
}
static int CheckClientConnection(SDLNet_StreamSocket *sock, int timeoutms)
{
if (!sock) {
return SDL_InvalidParamError("sock");
} else if (sock->status == 0) { // still pending?
/*!!! FIXME: add this later?
if (sock->simulated_failure_ticks) {
if (SDL_GetTicks() >= sock->simulated_failure_ticks) {
sock->status = SDL_SetError("simulated failure");
} else */
if (SDLNet_WaitUntilInputAvailable((void **) &sock, 1, timeoutms) == -1) {
sock->status = -1; // just abandon the whole enterprise.
}
}
return sock->status;
}
int SDLNet_WaitUntilConnected(SDLNet_StreamSocket *sock, Sint32 timeout)
{
return CheckClientConnection(sock, (int) timeout);
}
int SDLNet_GetConnectionStatus(SDLNet_StreamSocket *sock)
{
return CheckClientConnection(sock, 0);
}
struct SDLNet_Server
{
SDLNet_SocketType socktype;
SDLNet_Address *addr; // bound to this address (NULL for any).
Uint16 port;
Socket handle;
};
SDLNet_Server *SDLNet_CreateServer(SDLNet_Address *addr, Uint16 port)
{
if (addr && SDL_AtomicGet(&addr->status) != 1) {
SDL_SetError("Address is not resolved"); // strictly speaking, this should be a local interface, but a resolved address can fail later.
return NULL;
}
SDLNet_Server *server = (SDLNet_Server *) SDL_calloc(1, sizeof (SDLNet_Server));
if (!server) {
return NULL;
}
server->socktype = SOCKETTYPE_SERVER;
server->addr = addr;
server->port = port;
struct addrinfo *addrwithport = MakeAddrInfoWithPort(addr, SOCK_STREAM, port);
if (!addrwithport) {
SDL_free(server);
return NULL;
}
server->handle = socket(addrwithport->ai_family, addrwithport->ai_socktype, addrwithport->ai_protocol);
if (server->handle == INVALID_SOCKET) {
SetLastSocketError("Failed to create listen socket");
freeaddrinfo(addrwithport);
SDL_free(server);
return NULL;
}
if (MakeSocketNonblocking(server->handle) < 0) {
CloseSocketHandle(server->handle);
freeaddrinfo(addrwithport);
SDL_free(server);
SDL_SetError("Failed to make new listen socket non-blocking");
return NULL;
}
int zero = 0;
setsockopt(server->handle, IPPROTO_IPV6, IPV6_V6ONLY, (const char *) &zero, sizeof (zero)); // if this fails, oh well.
int rc = bind(server->handle, addrwithport->ai_addr, addrwithport->ai_addrlen);
freeaddrinfo(addrwithport);
if (rc == SOCKET_ERROR) {
const int err = LastSocketError();
SDL_assert(!WouldBlock(err)); // binding shouldn't be a blocking operation.
SetSocketError("Failed to bind listen socket", err);
CloseSocketHandle(server->handle);
SDL_free(server);
return NULL;
}
rc = listen(server->handle, 16);
if (rc == SOCKET_ERROR) {
const int err = LastSocketError();
SDL_assert(!WouldBlock(err)); // listen shouldn't be a blocking operation.
SetSocketError("Failed to listen on socket", err);
CloseSocketHandle(server->handle);
SDL_free(server);
return NULL;
}
SDLNet_RefAddress(addr);
return server;
}
int SDLNet_AcceptClient(SDLNet_Server *server, SDLNet_StreamSocket **client_stream)
{
if (!client_stream) {
return SDL_InvalidParamError("client_stream");
}
*client_stream = NULL;
if (!server) {
return SDL_InvalidParamError("server");
}
AddressStorage from;
SockLen fromlen = sizeof (from);
const Socket handle = accept(server->handle, (struct sockaddr *) &from, &fromlen);
if (handle == INVALID_SOCKET) {
const int err = LastSocketError();