-
Notifications
You must be signed in to change notification settings - Fork 95
/
sim_sock.c
1423 lines (1287 loc) · 49 KB
/
sim_sock.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
/* sim_sock.c: OS-dependent socket routines
Copyright (c) 2001-2010, Robert M Supnik
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
ROBERT M SUPNIK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Robert M Supnik shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Robert M Supnik.
15-Oct-12 MP Added definitions needed to detect possible tcp
connect failures
25-Sep-12 MP Reworked for RFC3493 interfaces supporting IPv6 and IPv4
22-Jun-10 RMS Fixed types in sim_accept_conn (from Mark Pizzolato)
19-Nov-05 RMS Added conditional for OpenBSD (from Federico G. Schwindt)
16-Aug-05 RMS Fixed spurious SIGPIPE signal error in Unix
14-Apr-05 RMS Added WSAEINPROGRESS test (from Tim Riker)
09-Jan-04 RMS Fixed typing problem in Alpha Unix (found by Tim Chapman)
17-Apr-03 RMS Fixed non-implemented version of sim_close_sock
(found by Mark Pizzolato)
17-Dec-02 RMS Added sim_connect_socket, sim_create_socket
08-Oct-02 RMS Revised for .NET compatibility
22-Aug-02 RMS Changed calling sequence for sim_accept_conn
22-May-02 RMS Added OS2 EMX support from Holger Veit
06-Feb-02 RMS Added VMS support from Robert Alan Byer
16-Sep-01 RMS Added Macintosh support from Peter Schorn
02-Sep-01 RMS Fixed UNIX bugs found by Mirian Lennox and Tom Markson
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "sim_sock.h"
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#if defined(AF_INET6) && defined(_WIN32)
#include <ws2tcpip.h>
#endif
#ifdef SIM_HAVE_DLOPEN
#include <dlfcn.h>
#endif
#ifndef WSAAPI
#define WSAAPI
#endif
#if defined(SHUT_RDWR) && !defined(SD_BOTH)
#define SD_BOTH SHUT_RDWR
#endif
#ifndef NI_MAXHOST
#define NI_MAXHOST 1025
#endif
/* OS dependent routines
sim_master_sock create master socket
sim_connect_sock connect a socket to a remote destination
sim_connect_sock_ex connect a socket to a remote destination
sim_accept_conn accept connection
sim_read_sock read from socket
sim_write_sock write from socket
sim_close_sock close socket
sim_setnonblock set socket non-blocking
*/
/* First, all the non-implemented versions */
#if defined (__OS2__) && !defined (__EMX__)
void sim_init_sock (void)
{
}
void sim_cleanup_sock (void)
{
}
SOCKET sim_master_sock_ex (const char *hostport, int *parse_status, int opt_flags)
{
return INVALID_SOCKET;
}
SOCKET sim_connect_sock_ex (const char *sourcehostport, const char *hostport, const char *default_host, const char *default_port, int opt_flags)
{
return INVALID_SOCKET;
}
SOCKET sim_accept_conn (SOCKET master, char **connectaddr);
{
return INVALID_SOCKET;
}
int sim_read_sock (SOCKET sock, char *buf, int nbytes)
{
return -1;
}
int sim_write_sock (SOCKET sock, char *msg, int nbytes)
{
return 0;
}
void sim_close_sock (SOCKET sock)
{
return;
}
#else /* endif unimpl */
/* UNIX, Win32, Macintosh, VMS, OS2 (Berkeley socket) routines */
static struct sock_errors {
int value;
const char *text;
} sock_errors[] = {
{WSAEWOULDBLOCK, "Operation would block"},
{WSAENAMETOOLONG, "File name too long"},
{WSAEINPROGRESS, "Operation now in progress "},
{WSAETIMEDOUT, "Connection timed out"},
{WSAEISCONN, "Transport endpoint is already connected"},
{WSAECONNRESET, "Connection reset by peer"},
{WSAECONNREFUSED, "Connection refused"},
{WSAECONNABORTED, "Connection aborted"},
{WSAEHOSTUNREACH, "No route to host"},
{WSAEADDRINUSE, "Address already in use"},
#if defined (WSAEAFNOSUPPORT)
{WSAEAFNOSUPPORT, "Address family not supported by protocol"},
#endif
{WSAEACCES, "Permission denied"},
{0, NULL}
};
const char *sim_get_err_sock (const char *emsg)
{
int err = WSAGetLastError ();
int i;
static char err_buf[512];
for (i=0; (sock_errors[i].text) && (sock_errors[i].value != err); i++)
;
if (sock_errors[i].value == err)
sprintf (err_buf, "Sockets: %s error %d - %s\n", emsg, err, sock_errors[i].text);
else
#if defined(_WIN32)
sprintf (err_buf, "Sockets: %s error %d\n", emsg, err);
#else
sprintf (err_buf, "Sockets: %s error %d - %s\n", emsg, err, strerror(err));
#endif
return err_buf;
}
SOCKET sim_err_sock (SOCKET s, const char *emsg)
{
sim_printf ("%s", sim_get_err_sock (emsg));
if (s != INVALID_SOCKET) {
int err = WSAGetLastError ();
sim_close_sock (s);
WSASetLastError (err); /* Retain Original socket error value */
}
return INVALID_SOCKET;
}
typedef void (WSAAPI *freeaddrinfo_func) (struct addrinfo *ai);
static freeaddrinfo_func p_freeaddrinfo;
typedef int (WSAAPI *getaddrinfo_func) (const char *hostname,
const char *service,
const struct addrinfo *hints,
struct addrinfo **res);
static getaddrinfo_func p_getaddrinfo;
#if defined(VMS)
typedef size_t socklen_t;
#if !defined(EAI_OVERFLOW)
#define EAI_OVERFLOW EAI_FAIL
#endif
#endif
#if defined(__hpux)
#if !defined(EAI_OVERFLOW)
#define EAI_OVERFLOW EAI_FAIL
#endif
#endif
typedef int (WSAAPI *getnameinfo_func) (const struct sockaddr *sa, socklen_t salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags);
static getnameinfo_func p_getnameinfo;
static void WSAAPI s_freeaddrinfo (struct addrinfo *ai)
{
struct addrinfo *a, *an;
for (a=ai; a != NULL; a=an) {
an = a->ai_next;
free (a->ai_canonname);
free (a->ai_addr);
free (a);
}
}
static int WSAAPI s_getaddrinfo (const char *hostname,
const char *service,
const struct addrinfo *hints,
struct addrinfo **res)
{
struct hostent *he;
struct servent *se = NULL;
struct sockaddr_in *sin;
struct addrinfo *result = NULL;
struct addrinfo *ai, *lai = NULL;
struct addrinfo dhints;
struct in_addr ipaddr;
struct in_addr *fixed[2];
struct in_addr **ips = NULL;
struct in_addr **ip;
const char *cname = NULL;
int port = 0;
// Validate parameters
if ((hostname == NULL) && (service == NULL))
return EAI_NONAME;
if (hints) {
if ((hints->ai_family != PF_INET) && (hints->ai_family != PF_UNSPEC))
return EAI_FAMILY;
switch (hints->ai_socktype)
{
default:
return EAI_SOCKTYPE;
case SOCK_DGRAM:
case SOCK_STREAM:
case 0:
break;
}
}
else {
hints = &dhints;
memset(&dhints, 0, sizeof(dhints));
dhints.ai_family = PF_UNSPEC;
}
if (service) {
char *c;
port = strtoul(service, &c, 10);
port = htons((unsigned short)port);
if ((port == 0) || (*c != '\0')) {
switch (hints->ai_socktype)
{
case SOCK_DGRAM:
se = getservbyname(service, "udp");
break;
case SOCK_STREAM:
case 0:
se = getservbyname(service, "tcp");
break;
}
if (NULL == se)
return EAI_SERVICE;
port = se->s_port;
}
}
if (hostname) {
if ((0xffffffff != (ipaddr.s_addr = inet_addr(hostname))) ||
(0 == strcmp("255.255.255.255", hostname))) {
fixed[0] = &ipaddr;
fixed[1] = NULL;
if ((hints->ai_flags & AI_CANONNAME) && !(hints->ai_flags & AI_NUMERICHOST)) {
he = gethostbyaddr((char *)&ipaddr, 4, AF_INET);
if (NULL != he)
cname = he->h_name;
else
cname = hostname;
}
ips = fixed;
}
else {
if (hints->ai_flags & AI_NUMERICHOST)
return EAI_NONAME;
he = gethostbyname(hostname);
if (he) {
ips = (struct in_addr **)he->h_addr_list;
if (hints->ai_flags & AI_CANONNAME)
cname = he->h_name;
}
else {
switch (h_errno)
{
case HOST_NOT_FOUND:
case NO_DATA:
return EAI_NONAME;
case TRY_AGAIN:
return EAI_AGAIN;
default:
return EAI_FAIL;
}
}
}
}
else {
if (hints->ai_flags & AI_PASSIVE)
ipaddr.s_addr = htonl(INADDR_ANY);
else
ipaddr.s_addr = htonl(INADDR_LOOPBACK);
fixed[0] = &ipaddr;
fixed[1] = NULL;
ips = fixed;
}
for (ip=ips; (ip != NULL) && (*ip != NULL); ++ip) {
ai = (struct addrinfo *)calloc(1, sizeof(*ai));
if (NULL == ai) {
s_freeaddrinfo(result);
return EAI_MEMORY;
}
ai->ai_family = PF_INET;
ai->ai_socktype = hints->ai_socktype;
ai->ai_protocol = hints->ai_protocol;
ai->ai_addr = NULL;
ai->ai_addrlen = sizeof(struct sockaddr_in);
ai->ai_canonname = NULL;
ai->ai_next = NULL;
ai->ai_addr = (struct sockaddr *)calloc(1, sizeof(struct sockaddr_in));
if (NULL == ai->ai_addr) {
free(ai);
s_freeaddrinfo(result);
return EAI_MEMORY;
}
sin = (struct sockaddr_in *)ai->ai_addr;
sin->sin_family = PF_INET;
sin->sin_port = (unsigned short)port;
memcpy(&sin->sin_addr, *ip, sizeof(sin->sin_addr));
if (NULL == result)
result = ai;
else
lai->ai_next = ai;
lai = ai;
}
if (cname) {
result->ai_canonname = (char *)calloc(1, strlen(cname)+1);
if (NULL == result->ai_canonname) {
s_freeaddrinfo(result);
return EAI_MEMORY;
}
strcpy(result->ai_canonname, cname);
}
*res = result;
return 0;
}
#ifndef EAI_OVERFLOW
#define EAI_OVERFLOW WSAENAMETOOLONG
#endif
static int WSAAPI s_getnameinfo (const struct sockaddr *sa, socklen_t salen,
char *host, size_t hostlen,
char *serv, size_t servlen,
int flags)
{
struct hostent *he;
struct servent *se = NULL;
const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
if (sin->sin_family != PF_INET)
return EAI_FAMILY;
if ((NULL == host) && (NULL == serv))
return EAI_NONAME;
if ((serv) && (servlen > 0)) {
if (flags & NI_NUMERICSERV)
se = NULL;
else
if (flags & NI_DGRAM)
se = getservbyport(sin->sin_port, "udp");
else
se = getservbyport(sin->sin_port, "tcp");
if (se) {
if (servlen <= strlen(se->s_name))
return EAI_OVERFLOW;
strcpy(serv, se->s_name);
}
else {
char buf[16];
sprintf(buf, "%d", ntohs(sin->sin_port));
if (servlen <= strlen(buf))
return EAI_OVERFLOW;
strcpy(serv, buf);
}
}
if ((host) && (hostlen > 0)) {
if (flags & NI_NUMERICHOST)
he = NULL;
else
he = gethostbyaddr((const char *)&sin->sin_addr, 4, AF_INET);
if (he) {
if (hostlen < strlen(he->h_name)+1)
return EAI_OVERFLOW;
strcpy(host, he->h_name);
}
else {
if (flags & NI_NAMEREQD)
return EAI_NONAME;
if (hostlen < strlen(inet_ntoa(sin->sin_addr))+1)
return EAI_OVERFLOW;
strcpy(host, inet_ntoa(sin->sin_addr));
}
}
return 0;
}
#if defined(_WIN32) || defined(__CYGWIN__)
#if !defined(IPV6_V6ONLY) /* Older XP environments may not define IPV6_V6ONLY */
#define IPV6_V6ONLY 27 /* Treat wildcard bind as AF_INET6-only. */
#endif
#if defined(TEST_INFO_STUBS)
#undef IPV6_V6ONLY
#undef AF_INET6
#endif
/* Dynamic DLL load variables */
#ifdef _WIN32
static HINSTANCE hLib = 0; /* handle to DLL */
#else
static void *hLib = NULL; /* handle to Library */
#endif
static int lib_loaded = 0; /* 0=not loaded, 1=loaded, 2=library load failed, 3=Func load failed */
static const char* lib_name = "Ws2_32.dll";
/* load function pointer from DLL */
typedef int (*_func)();
static void load_function(const char* function, _func* func_ptr) {
#ifdef _WIN32
*func_ptr = (_func)GetProcAddress(hLib, function);
#else
*func_ptr = (_func)dlsym(hLib, function);
#endif
if (*func_ptr == 0) {
sim_printf ("Sockets: Failed to find function '%s' in %s\r\n", function, lib_name);
lib_loaded = 3;
}
}
/* load Ws2_32.dll as required */
int load_ws2(void) {
switch(lib_loaded) {
case 0: /* not loaded */
/* attempt to load DLL */
#ifdef _WIN32
hLib = LoadLibraryA(lib_name);
#else
hLib = dlopen(lib_name, RTLD_NOW);
#endif
if (hLib == 0) {
/* failed to load DLL */
sim_printf ("Sockets: Failed to load %s\r\n", lib_name);
lib_loaded = 2;
break;
} else {
/* library loaded OK */
lib_loaded = 1;
}
/* load required functions; sets dll_load=3 on error */
load_function("getaddrinfo", (_func *) &p_getaddrinfo);
load_function("getnameinfo", (_func *) &p_getnameinfo);
load_function("freeaddrinfo", (_func *) &p_freeaddrinfo);
if (lib_loaded != 1) {
/* unsuccessful load, connect stubs */
p_getaddrinfo = (getaddrinfo_func)s_getaddrinfo;
p_getnameinfo = (getnameinfo_func)s_getnameinfo;
p_freeaddrinfo = (freeaddrinfo_func)s_freeaddrinfo;
}
break;
default: /* loaded or failed */
break;
}
return (lib_loaded == 1) ? 1 : 0;
}
#endif
/* OS independent routines
sim_parse_addr parse a hostname/ipaddress from port and apply defaults
and optionally validate an address match
sim_addr_acl_check parse a hostname/ipaddress (possibly in CIDR form) and
test against an acl
*/
/* sim_parse_addr host:port
Presumption is that the cptr input, if it doesn't contain a ':' character
is a port specifier. If the host field contains one or more colon characters
(i.e. it is an IPv6 address), the IPv6 address MUST be enclosed in square
bracket characters (i.e. Domain Literal format)
Inputs:
cptr = pointer to input string
host = optional pointer to host buffer
host_len = length of host buffer
default_host = optional pointer to default host if none specified
in cptr
port = optional pointer to port buffer
port_len = length of port buffer
default_port = optional pointer to default port if none specified
in cptr
validate_addr = optional name/addr which is checked to be equivalent
to the host result of parsing the other input. This
address would usually be returned by sim_accept_conn.
The validate_addr can also be a CIDR address specifier
which will match against the provided host.
If the validate_addr is provided with cptr as NULL,
the validate_addr is parsed for reasonableness and
the result returned with 0 indicating a reasonable
value and -1 indicating a parsing error.
Outputs:
host = pointer to buffer for IP address (may be NULL), 0 = none
port = pointer to buffer for IP port (may be NULL), 0 = none
result = status (0 on complete success or -1 if
parsing can't happen due to bad syntax, a value is
out of range, a result can't fit into a result buffer,
a service name doesn't exist, or a validation name
doesn't match the parsed host)
*/
int sim_parse_addr (const char *cptr, char *host, size_t host_len, const char *default_host,
char *port, size_t port_len, const char *default_port,
const char *validate_addr)
{
char gbuf[CBUFSIZE], default_pbuf[CBUFSIZE];
const char *hostp;
char *portp;
char *endc;
unsigned long portval;
if ((host != NULL) && (host_len != 0))
memset (host, 0, host_len);
if ((port != NULL) && (port_len != 0))
memset (port, 0, port_len);
if ((cptr == NULL) || (*cptr == 0)) {
if (((default_host == NULL) || (*default_host == 0)) ||
((default_port == NULL) || (*default_port == 0)))
return -1;
if ((host == NULL) || (port == NULL))
return -1; /* no place */
if ((strlen(default_host) >= host_len) || (strlen(default_port) >= port_len))
return -1; /* no room */
strcpy (host, default_host);
strcpy (port, default_port);
return 0;
}
memset (default_pbuf, 0, sizeof(default_pbuf));
if (default_port)
strncpy (default_pbuf, default_port, sizeof(default_pbuf)-1);
gbuf[sizeof(gbuf)-1] = '\0';
strncpy (gbuf, cptr, sizeof(gbuf)-1);
hostp = gbuf; /* default addr */
portp = NULL;
if ((portp = strrchr (gbuf, ':')) && /* x:y? split */
(NULL == strchr (portp, ']'))) {
*portp++ = 0;
if (*portp == '\0')
portp = default_pbuf;
}
else { /* No colon in input */
portp = gbuf; /* Input is the port specifier */
hostp = (const char *)default_host; /* host is defaulted if provided */
}
if ((portp != NULL) && (*portp != '\0')) {
portval = strtoul(portp, &endc, 10);
if ((*endc == '\0') && ((portval == 0) || (portval > 65535)))
return -1; /* numeric value too big */
if (*endc != '\0') {
struct servent *se = getservbyname(portp, "tcp");
if (se == NULL)
return -1; /* invalid service name */
}
}
if (port) /* port wanted? */
if (portp != NULL) {
if (strlen(portp) >= port_len)
return -1; /* no room */
else
strcpy (port, portp);
}
if ((hostp != NULL) && (*hostp != '\0')) {
if (']' == hostp[strlen(hostp)-1]) {
if ('[' != hostp[0])
return -1; /* invalid domain literal */
/* host may be the const default_host so move to temp buffer before modifying */
strncpy(gbuf, hostp+1, sizeof(gbuf)-1); /* remove brackets from domain literal host */
gbuf[strlen(gbuf)-1] = '\0';
hostp = gbuf;
}
}
if (host) { /* host wanted? */
if (hostp != NULL) {
if (strlen(hostp) >= host_len)
return -1; /* no room */
else
if (('\0' != hostp[0]) || (default_host == NULL))
strcpy (host, hostp);
else
if (strlen(default_host) >= host_len)
return -1; /* no room */
else
strcpy (host, default_host);
}
else {
if (default_host) {
if (strlen(default_host) >= host_len)
return -1; /* no room */
else
strcpy (host, default_host);
}
}
}
if (validate_addr) {
struct addrinfo *ai_host, *ai_validate, *ai, *aiv;
int status;
if ((hostp == NULL) ||
(0 != p_getaddrinfo(hostp, NULL, NULL, &ai_host)))
return -1;
if (p_getaddrinfo(validate_addr, NULL, NULL, &ai_validate)) {
p_freeaddrinfo (ai_host);
return -1;
}
status = -1;
for (ai = ai_host; (ai != NULL) && (status == -1); ai = ai->ai_next) {
for (aiv = ai_validate; aiv != NULL; aiv = aiv->ai_next) {
if ((ai->ai_addrlen == aiv->ai_addrlen) &&
(ai->ai_family == aiv->ai_family) &&
(0 == memcmp (ai->ai_addr, aiv->ai_addr, ai->ai_addrlen))) {
status = 0;
break;
}
}
}
if (status != 0) {
/* be generous and allow successful validations against variations of localhost addresses */
if (((0 == strcmp("127.0.0.1", hostp)) &&
(0 == strcmp("::1", validate_addr))) ||
((0 == strcmp("127.0.0.1", validate_addr)) &&
(0 == strcmp("::1", hostp))))
status = 0;
}
p_freeaddrinfo (ai_host);
p_freeaddrinfo (ai_validate);
return status;
}
return 0;
}
/* sim_addr_acl_check host:port,acl
parse a hostname/ipaddress (possibly in CIDR form) and
test against an acl
Inputs:
validate_addr = This address would usually be returned by
sim_accept_conn. The validate_addr can also be a
CIDR address specifier and in that mode, acl should
be NULL so that we're just validating the syntax
of what will likely become an entry in an acl list.
If the validate_addr is provided with cptr as NULL,
the validate_addr is parsed for reasonableness and
the result returned with 0 indicating a reasonable
value and -1 indicating a parsing error.
acl = pointer to acl string which is comprised of comma
separated entries each which may have a + or -
prefix that indicated a permit or deny status when
the entry matches. Each entry may specify a CIDR
form match criteria.
Outputs:
result = status (0 on complete success or -1 if
parsing can't happen due to bad syntax, a value is
out of range or the validate_addr matches a reject
entry in the acl or it is not mentioned at all in
the acl.
*/
int sim_addr_acl_check (const char *validate_addr, const char *acl)
{
int status = -1;
int done = 0;
struct addrinfo *ai_validate;
unsigned long bits = 0;
const char *c;
char *c1, v_cpy[256];
if (validate_addr == NULL)
return status;
c = strchr (validate_addr, '/');
if (c != NULL) {
bits = strtoul (c + 1, &c1, 10);
if ((bits == 0) || (bits > 128) || (*c1 != '\0'))
return status;
if ((c - validate_addr) > sizeof (v_cpy) - 1)
return status;
memcpy (v_cpy, validate_addr, c - validate_addr); /* Copy everything before the / */
v_cpy[c - validate_addr] = '\0'; /* NUL terminate the result */
validate_addr = v_cpy; /* Use the original string minus the prefix specifier */
}
if (p_getaddrinfo(validate_addr, NULL, NULL, &ai_validate))
return status;
if (acl == NULL) { /* Just checking validate_addr syntax? */
status = 0;
if ((ai_validate->ai_family == AF_INET) && (bits > 32))
status = -1;
p_freeaddrinfo (ai_validate);
return status;
}
status = -1;
while ((*acl != '\0') && !done) {
struct addrinfo *ai_rule, *ai, *aiv;
int permit;
unsigned long bits = 0;
const char *cc;
char *c,*c1, rule[260];
permit = (*acl == '+');
cc = strchr (acl, ',');
if (cc != NULL) {
if ((cc - acl) > sizeof (rule))
break; /* Too big - error */
memcpy (rule, acl + 1, cc - (acl + 1));
rule[cc - (acl + 1)] = '\0';
}
else {
if (strlen (acl) >= sizeof (rule))
break; /* Too big - error */
strcpy (rule, acl + 1);
}
acl += strlen (rule) + 1 + (cc != NULL);
c = strchr (rule, '/');
if (c != NULL) {
bits = strtoul (c + 1, &c1, 10);
if ((bits == 0) || (bits > 128) || (*c1 != '\0'))
break;
*c = '\0';
}
if (p_getaddrinfo(rule, NULL, NULL, &ai_rule))
break;
for (ai = ai_rule; (ai != NULL) && (done == 0); ai = ai->ai_next) {
for (aiv = ai_validate; aiv != NULL; aiv = aiv->ai_next) {
if ((ai->ai_addrlen == aiv->ai_addrlen) &&
(ai->ai_family == aiv->ai_family)) {
unsigned int bit, addr_bits;
unsigned char *da, *dav;
if (ai->ai_family == AF_INET) {
da = (unsigned char *)&((struct sockaddr_in *)ai->ai_addr)->sin_addr;
dav = (unsigned char *)&((struct sockaddr_in *)aiv->ai_addr)->sin_addr;
addr_bits = 32;
}
#if !defined(AF_INET6)
else {
done = 1;
break;
}
#else
else {
if (ai->ai_family == AF_INET6) {
da = (unsigned char *)&((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr;
dav = (unsigned char *)&((struct sockaddr_in6 *)aiv->ai_addr)->sin6_addr;
addr_bits = 128;
}
else {
done = 1;
break;
}
}
#endif
if (bits == 0) /* Bits not specified? */
bits = addr_bits; /* Use them all */
for (bit=0; (bit < bits) && (bit < addr_bits); bit++) {
unsigned int bitmask = 1 << (7 - (bit & 7));
if ((da[bit>>3] & bitmask) != (dav[bit>>3] & bitmask))
break;
}
if (bit == bits) { /* All desired bits matched? */
done = 1;
status = permit ? 0 : -1;
break;
}
}
}
}
p_freeaddrinfo (ai_rule);
}
p_freeaddrinfo (ai_validate);
return status;
}
/* sim_parse_addr_ex localport:host:port
Presumption is that the input, if it doesn't contain a ':' character is a port specifier.
If the host field contains one or more colon characters (i.e. it is an IPv6 address),
the IPv6 address MUST be enclosed in square bracket characters (i.e. Domain Literal format)
llll:w.x.y.z:rrrr
llll:name.domain.com:rrrr
llll::rrrr
rrrr
w.x.y.z:rrrr
[w.x.y.z]:rrrr
name.domain.com:rrrr
Inputs:
cptr = pointer to input string
default_host
= optional pointer to default host if none specified
host_len = length of host buffer
default_port
= optional pointer to default port if none specified
port_len = length of port buffer
Outputs:
host = pointer to buffer for IP address (may be NULL), 0 = none
port = pointer to buffer for IP port (may be NULL), 0 = none
localport
= pointer to buffer for local IP port (may be NULL), 0 = none
result = status (0 on complete success or -1 if
parsing can't happen due to bad syntax, a value is
out of range, a result can't fit into a result buffer,
a service name doesn't exist, or a validation name
doesn't match the parsed host)
*/
int sim_parse_addr_ex (const char *cptr, char *host, size_t hostlen, const char *default_host, char *port, size_t port_len, char *localport, size_t localport_len, const char *default_port)
{
const char *hostp;
if ((localport != NULL) && (localport_len != 0))
memset (localport, 0, localport_len);
hostp = strchr (cptr, ':');
if ((hostp != NULL) && ((hostp[1] == '[') || (NULL != strchr (hostp+1, ':')))) {
if ((localport != NULL) && (localport_len != 0)) {
localport_len -= 1;
if (localport_len > (size_t)(hostp-cptr))
localport_len = (size_t)(hostp-cptr);
memcpy (localport, cptr, localport_len);
}
return sim_parse_addr (hostp+1, host, hostlen, default_host, port, port_len, default_port, NULL);
}
return sim_parse_addr (cptr, host, hostlen, default_host, port, port_len, default_port, NULL);
}
void sim_init_sock (void)
{
#if defined (_WIN32)
int err;
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD (2, 2);
err = WSAStartup (wVersionRequested, &wsaData); /* start Winsock */
if (err != 0)
sim_printf ("Winsock: startup error %d\n", err);
#if defined(AF_INET6)
load_ws2 ();
#endif /* endif AF_INET6 */
#else /* Use native addrinfo APIs */
#if defined(AF_INET6)
p_getaddrinfo = (getaddrinfo_func)getaddrinfo;
p_getnameinfo = (getnameinfo_func)getnameinfo;
p_freeaddrinfo = (freeaddrinfo_func)freeaddrinfo;
#else
/* Native APIs not available, connect stubs */
p_getaddrinfo = (getaddrinfo_func)s_getaddrinfo;
p_getnameinfo = (getnameinfo_func)s_getnameinfo;
p_freeaddrinfo = (freeaddrinfo_func)s_freeaddrinfo;
#endif /* endif AF_INET6 */
#endif /* endif _WIN32 */
#if defined (SIGPIPE)
signal (SIGPIPE, SIG_IGN); /* no pipe signals */
#endif
#if defined(TEST_INFO_STUBS)
/* force use of stubs */
p_getaddrinfo = (getaddrinfo_func)s_getaddrinfo;
p_getnameinfo = (getnameinfo_func)s_getnameinfo;
p_freeaddrinfo = (freeaddrinfo_func)s_freeaddrinfo;
#endif
}
void sim_cleanup_sock (void)
{
#if defined (_WIN32)
WSACleanup ();
#endif
}
#if defined (_WIN32) /* Windows */
static int sim_setnonblock (SOCKET sock)
{
unsigned long non_block = 1;
return ioctlsocket (sock, FIONBIO, &non_block); /* set nonblocking */
}
#elif defined (VMS) /* VMS */
static int sim_setnonblock (SOCKET sock)
{
int non_block = 1;
return ioctl (sock, FIONBIO, &non_block); /* set nonblocking */
}
#else /* Mac, Unix, OS/2 */
static int sim_setnonblock (SOCKET sock)
{
int fl, sta;
fl = fcntl (sock, F_GETFL,0); /* get flags */
if (fl == -1)
return SOCKET_ERROR;
sta = fcntl (sock, F_SETFL, fl | O_NONBLOCK); /* set nonblock */
if (sta == -1)
return SOCKET_ERROR;
#if !defined (macintosh) && !defined (__EMX__) && \
!defined (__HAIKU__) /* Unix only */
sta = fcntl (sock, F_SETOWN, getpid()); /* set ownership */
if (sta == -1)
return SOCKET_ERROR;
#endif
return 0;
}
#endif /* endif !Win32 && !VMS */
static int sim_setnodelay (SOCKET sock)
{
int nodelay = 1;
int sta;
/* disable Nagle algorithm */
sta = setsockopt (sock, IPPROTO_TCP, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay));
if (sta == -1)
return SOCKET_ERROR;
#if defined(TCP_NODELAYACK)
/* disable delayed ack algorithm */
sta = setsockopt (sock, IPPROTO_TCP, TCP_NODELAYACK, (char *)&nodelay, sizeof(nodelay));
if (sta == -1)
return SOCKET_ERROR;
#endif
#if defined(TCP_QUICKACK)
/* disable delayed ack algorithm */
sta = setsockopt (sock, IPPROTO_TCP, TCP_QUICKACK, (char *)&nodelay, sizeof(nodelay));
if (sta == -1)
return SOCKET_ERROR;
#endif
return sta;
}
static SOCKET sim_create_sock (int af, int opt_flags)
{
SOCKET newsock;
int err;
newsock = socket (af, ((opt_flags & SIM_SOCK_OPT_DATAGRAM) ? SOCK_DGRAM : SOCK_STREAM), 0);/* create socket */
if (newsock == INVALID_SOCKET) { /* socket error? */
err = WSAGetLastError ();
#if defined(WSAEAFNOSUPPORT)
if (err == WSAEAFNOSUPPORT) /* expected error, just return */
return newsock;
#endif
return sim_err_sock (newsock, "socket"); /* report error and return */
}
return newsock;
}