-
Notifications
You must be signed in to change notification settings - Fork 872
/
Copy pathsockutils.c
2112 lines (1938 loc) · 62.4 KB
/
sockutils.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
/*
* Copyright (c) 2002 - 2003
* NetGroup, Politecnico di Torino (Italy)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/*
* \file sockutils.c
*
* The goal of this file is to provide a common set of primitives for socket
* manipulation.
*
* Although the socket interface defined in the RFC 2553 (and its updates)
* is excellent, there are still differences between the behavior of those
* routines on UN*X and Windows, and between UN*Xes.
*
* These calls provide an interface similar to the socket interface, but
* that hides the differences between operating systems. It does not
* attempt to significantly improve on the socket interface in other
* ways.
*/
#include "ftmacros.h"
#include <string.h>
#include <errno.h> /* for the errno variable */
#include <stdio.h> /* for the stderr file */
#include <stdlib.h> /* for malloc() and free() */
#include <limits.h> /* for INT_MAX */
#include "pcap-int.h"
#include "sockutils.h"
#include "portability.h"
#ifdef _WIN32
/*
* Winsock initialization.
*
* Ask for Winsock 2.2.
*/
#define WINSOCK_MAJOR_VERSION 2
#define WINSOCK_MINOR_VERSION 2
static int sockcount = 0; /*!< Variable that allows calling the WSAStartup() only one time */
#endif
/* Some minor differences between UNIX and Win32 */
#ifdef _WIN32
#define SHUT_WR SD_SEND /* The control code for shutdown() is different in Win32 */
#endif
/* Size of the buffer that has to keep error messages */
#define SOCK_ERRBUF_SIZE 1024
/* Constants; used in order to keep strings here */
#define SOCKET_NO_NAME_AVAILABLE "No name available"
#define SOCKET_NO_PORT_AVAILABLE "No port available"
#define SOCKET_NAME_NULL_DAD "Null address (possibly DAD Phase)"
/*
* On UN*X, send() and recv() return ssize_t.
*
* On Windows, send() and recv() return an int.
*
* With MSVC, there *is* no ssize_t.
*
* With MinGW, there is an ssize_t type; it is either an int (32 bit)
* or a long long (64 bit).
*
* So, on Windows, if we don't have ssize_t defined, define it as an
* int, so we can use it, on all platforms, as the type of variables
* that hold the return values from send() and recv().
*/
#if defined(_WIN32) && !defined(_SSIZE_T_DEFINED)
typedef int ssize_t;
#endif
/****************************************************
* *
* Locally defined functions *
* *
****************************************************/
static int sock_ismcastaddr(const struct sockaddr *saddr);
/****************************************************
* *
* Function bodies *
* *
****************************************************/
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
const uint8_t *fuzzBuffer;
size_t fuzzSize;
size_t fuzzPos;
void sock_initfuzz(const uint8_t *Data, size_t Size) {
fuzzPos = 0;
fuzzSize = Size;
fuzzBuffer = Data;
}
static int fuzz_recv(char *bufp, int remaining) {
if (remaining > fuzzSize - fuzzPos) {
remaining = fuzzSize - fuzzPos;
}
if (fuzzPos < fuzzSize) {
memcpy(bufp, fuzzBuffer + fuzzPos, remaining);
}
fuzzPos += remaining;
return remaining;
}
#endif
int sock_geterrcode(void)
{
#ifdef _WIN32
return GetLastError();
#else
return errno;
#endif
}
/*
* Format an error message given an errno value (UN*X) or a Winsock error
* (Windows).
*/
void sock_vfmterrmsg(char *errbuf, size_t errbuflen, int errcode,
const char *fmt, va_list ap)
{
if (errbuf == NULL)
return;
#ifdef _WIN32
pcap_vfmt_errmsg_for_win32_err(errbuf, errbuflen, errcode,
fmt, ap);
#else
pcap_vfmt_errmsg_for_errno(errbuf, errbuflen, errcode,
fmt, ap);
#endif
}
void sock_fmterrmsg(char *errbuf, size_t errbuflen, int errcode,
const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
sock_vfmterrmsg(errbuf, errbuflen, errcode, fmt, ap);
va_end(ap);
}
/*
* Format an error message for the last socket error.
*/
void sock_geterrmsg(char *errbuf, size_t errbuflen, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
sock_vfmterrmsg(errbuf, errbuflen, sock_geterrcode(), fmt, ap);
va_end(ap);
}
/*
* Types of error.
*
* These are sorted by how likely they are to be the "underlying" problem,
* so that lower-rated errors for a given address in a given family
* should not overwrite higher-rated errors for another address in that
* family, and higher-rated errors should overwrit elower-rated errors.
*/
typedef enum {
SOCK_CONNERR, /* connection error */
SOCK_HOSTERR, /* host error */
SOCK_NETERR, /* network error */
SOCK_AFNOTSUPERR, /* address family not supported */
SOCK_UNKNOWNERR, /* unknown error */
SOCK_NOERR /* no error */
} sock_errtype;
static sock_errtype sock_geterrtype(int errcode)
{
switch (errcode) {
#ifdef _WIN32
case WSAECONNRESET:
case WSAECONNABORTED:
case WSAECONNREFUSED:
#else
case ECONNRESET:
case ECONNABORTED:
case ECONNREFUSED:
#endif
/*
* Connection error; this means the problem is probably
* that there's no server set up on the remote machine,
* or that it is set up, but it's IPv4-only or IPv6-only
* and we're trying the wrong address family.
*
* These overwrite all other errors, as they indicate
* that, even if somethng else went wrong in another
* attempt, this probably wouldn't work even if the
* other problems were fixed.
*/
return (SOCK_CONNERR);
#ifdef _WIN32
case WSAENETUNREACH:
case WSAETIMEDOUT:
case WSAEHOSTDOWN:
case WSAEHOSTUNREACH:
#else
case ENETUNREACH:
case ETIMEDOUT:
case EHOSTDOWN:
case EHOSTUNREACH:
#endif
/*
* Network errors that could be IPv4-specific, IPv6-
* specific, or present with both.
*
* Don't overwrite connection errors, but overwrite
* everything else.
*/
return (SOCK_HOSTERR);
#ifdef _WIN32
case WSAENETDOWN:
case WSAENETRESET:
#else
case ENETDOWN:
case ENETRESET:
#endif
/*
* Network error; this means we don't know whether
* there's a server set up on the remote machine,
* and we don't have a reason to believe that IPv6
* any worse or better than IPv4.
*
* These probably indicate a local failure, e.g.
* an interface is down.
*
* Don't overwrite connection errors or host errors,
* but overwrite everything else.
*/
return (SOCK_NETERR);
#ifdef _WIN32
case WSAEAFNOSUPPORT:
#else
case EAFNOSUPPORT:
#endif
/*
* "Address family not supported" probably means
* "No soup^WIPv6 for you!".
*
* Don't overwrite connection errors, host errors, or
* network errors (none of which we should get for this
* address family if it's not supported), but overwrite
* everything else.
*/
return (SOCK_AFNOTSUPERR);
default:
/*
* Anything else.
*
* Don't overwrite any errors.
*/
return (SOCK_UNKNOWNERR);
}
}
/*
* \brief This function initializes the socket mechanism if it hasn't
* already been initialized or reinitializes it after it has been
* cleaned up.
*
* On UN*Xes, it doesn't need to do anything; on Windows, it needs to
* initialize Winsock.
*
* \param errbuf: a pointer to an user-allocated buffer that will contain
* the complete error message. This buffer has to be at least 'errbuflen'
* in length. It can be NULL; in this case no error message is supplied.
*
* \param errbuflen: length of the buffer that will contains the error.
* The error message cannot be larger than 'errbuflen - 1' because the
* last char is reserved for the string terminator.
*
* \return '0' if everything is fine, '-1' if some errors occurred. The
* error message is returned in the buffer pointed to by 'errbuf' variable.
*/
#ifdef _WIN32
int sock_init(char *errbuf, int errbuflen)
{
if (sockcount == 0)
{
WSADATA wsaData; /* helper variable needed to initialize Winsock */
if (WSAStartup(MAKEWORD(WINSOCK_MAJOR_VERSION,
WINSOCK_MINOR_VERSION), &wsaData) != 0)
{
if (errbuf)
snprintf(errbuf, errbuflen, "Failed to initialize Winsock\n");
WSACleanup();
return -1;
}
}
sockcount++;
return 0;
}
#else
int sock_init(char *errbuf _U_, int errbuflen _U_)
{
/*
* Nothing to do on UN*Xes.
*/
return 0;
}
#endif
/*
* \brief This function cleans up the socket mechanism if we have no
* sockets left open.
*
* On UN*Xes, it doesn't need to do anything; on Windows, it needs
* to clean up Winsock.
*
* \return No error values.
*/
void sock_cleanup(void)
{
#ifdef _WIN32
sockcount--;
if (sockcount == 0)
WSACleanup();
#endif
}
/*
* \brief It checks if the sockaddr variable contains a multicast address.
*
* \return '0' if the address is multicast, '-1' if it is not.
*/
static int sock_ismcastaddr(const struct sockaddr *saddr)
{
if (saddr->sa_family == PF_INET)
{
struct sockaddr_in *saddr4 = (struct sockaddr_in *) saddr;
if (IN_MULTICAST(ntohl(saddr4->sin_addr.s_addr))) return 0;
else return -1;
}
else
{
struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *) saddr;
if (IN6_IS_ADDR_MULTICAST(&saddr6->sin6_addr)) return 0;
else return -1;
}
}
struct addr_status {
struct addrinfo *info;
int errcode;
sock_errtype errtype;
};
/*
* Sort by IPv4 address vs. IPv6 address.
*/
static int compare_addrs_to_try_by_address_family(const void *a, const void *b)
{
const struct addr_status *addr_a = (const struct addr_status *)a;
const struct addr_status *addr_b = (const struct addr_status *)b;
return addr_a->info->ai_family - addr_b->info->ai_family;
}
/*
* Sort by error type and, within a given error type, by error code and,
* within a given error code, by IPv4 address vs. IPv6 address.
*/
static int compare_addrs_to_try_by_status(const void *a, const void *b)
{
const struct addr_status *addr_a = (const struct addr_status *)a;
const struct addr_status *addr_b = (const struct addr_status *)b;
if (addr_a->errtype == addr_b->errtype)
{
if (addr_a->errcode == addr_b->errcode)
{
return addr_a->info->ai_family - addr_b->info->ai_family;
}
return addr_a->errcode - addr_b->errcode;
}
return addr_a->errtype - addr_b->errtype;
}
static SOCKET sock_create_socket(struct addrinfo *addrinfo, char *errbuf,
int errbuflen)
{
SOCKET sock;
#ifdef SO_NOSIGPIPE
int on = 1;
#endif
sock = socket(addrinfo->ai_family, addrinfo->ai_socktype,
addrinfo->ai_protocol);
if (sock == INVALID_SOCKET)
{
sock_geterrmsg(errbuf, errbuflen, "socket() failed");
return INVALID_SOCKET;
}
/*
* Disable SIGPIPE, if we have SO_NOSIGPIPE. We don't want to
* have to deal with signals if the peer closes the connection,
* especially in client programs, which may not even be aware that
* they're sending to sockets.
*/
#ifdef SO_NOSIGPIPE
if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, (char *)&on,
sizeof (int)) == -1)
{
sock_geterrmsg(errbuf, errbuflen,
"setsockopt(SO_NOSIGPIPE) failed");
closesocket(sock);
return INVALID_SOCKET;
}
#endif
return sock;
}
/*
* \brief It initializes a network connection both from the client and the server side.
*
* In case of a client socket, this function calls socket() and connect().
* In the meanwhile, it checks for any socket error.
* If an error occurs, it writes the error message into 'errbuf'.
*
* In case of a server socket, the function calls socket(), bind() and listen().
*
* This function is usually preceded by the sock_initaddress().
*
* \param host: for client sockets, the host name to which we're trying
* to connect.
*
* \param addrinfo: pointer to an addrinfo variable which will be used to
* open the socket and such. This variable is the one returned by the previous call to
* sock_initaddress().
*
* \param server: '1' if this is a server socket, '0' otherwise.
*
* \param nconn: number of the connections that are allowed to wait into the listen() call.
* This value has no meanings in case of a client socket.
*
* \param errbuf: a pointer to an user-allocated buffer that will contain the complete
* error message. This buffer has to be at least 'errbuflen' in length.
* It can be NULL; in this case the error cannot be printed.
*
* \param errbuflen: length of the buffer that will contains the error. The error message cannot be
* larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
*
* \return the socket that has been opened (that has to be used in the following sockets calls)
* if everything is fine, INVALID_SOCKET if some errors occurred. The error message is returned
* in the 'errbuf' variable.
*/
SOCKET sock_open(const char *host, struct addrinfo *addrinfo, int server, int nconn, char *errbuf, int errbuflen)
{
SOCKET sock;
/* This is a server socket */
if (server)
{
int on;
/*
* Attempt to create the socket.
*/
sock = sock_create_socket(addrinfo, errbuf, errbuflen);
if (sock == INVALID_SOCKET)
{
return INVALID_SOCKET;
}
/*
* Allow a new server to bind the socket after the old one
* exited, even if lingering sockets are still present.
*
* Don't treat an error as a failure.
*/
on = 1;
(void)setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
(char *)&on, sizeof (on));
#if defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY)
/*
* Force the use of IPv6-only addresses.
*
* RFC 3493 indicates that you can support IPv4 on an
* IPv6 socket:
*
* https://tools.ietf.org/html/rfc3493#section-3.7
*
* and that this is the default behavior. This means
* that if we first create an IPv6 socket bound to the
* "any" address, it is, in effect, also bound to the
* IPv4 "any" address, so when we create an IPv4 socket
* and try to bind it to the IPv4 "any" address, it gets
* EADDRINUSE.
*
* Not all network stacks support IPv4 on IPv6 sockets;
* pre-NT 6 Windows stacks don't support it, and the
* OpenBSD stack doesn't support it for security reasons
* (see the OpenBSD inet6(4) man page). Therefore, we
* don't want to rely on this behavior.
*
* So we try to disable it, using either the IPV6_V6ONLY
* option from RFC 3493:
*
* https://tools.ietf.org/html/rfc3493#section-5.3
*
* or the IPV6_BINDV6ONLY option from older UN*Xes.
*/
#ifndef IPV6_V6ONLY
/* For older systems */
#define IPV6_V6ONLY IPV6_BINDV6ONLY
#endif /* IPV6_V6ONLY */
if (addrinfo->ai_family == PF_INET6)
{
on = 1;
if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
(char *)&on, sizeof (int)) == -1)
{
if (errbuf)
snprintf(errbuf, errbuflen, "setsockopt(IPV6_V6ONLY)");
closesocket(sock);
return INVALID_SOCKET;
}
}
#endif /* defined(IPV6_V6ONLY) || defined(IPV6_BINDV6ONLY) */
/* WARNING: if the address is a mcast one, I should place the proper Win32 code here */
if (bind(sock, addrinfo->ai_addr, (int) addrinfo->ai_addrlen) != 0)
{
sock_geterrmsg(errbuf, errbuflen, "bind() failed");
closesocket(sock);
return INVALID_SOCKET;
}
if (addrinfo->ai_socktype == SOCK_STREAM)
if (listen(sock, nconn) == -1)
{
sock_geterrmsg(errbuf, errbuflen,
"listen() failed");
closesocket(sock);
return INVALID_SOCKET;
}
/* server side ended */
return sock;
}
else /* we're the client */
{
struct addr_status *addrs_to_try;
struct addrinfo *tempaddrinfo;
size_t numaddrinfos;
size_t i;
int current_af = AF_UNSPEC;
/*
* We have to loop though all the addrinfos returned.
* For instance, we can have both IPv6 and IPv4 addresses,
* but the service we're trying to connect to is unavailable
* in IPv6, so we have to try in IPv4 as well.
*
* How many addrinfos do we have?
*/
numaddrinfos = 0;
for (tempaddrinfo = addrinfo; tempaddrinfo != NULL;
tempaddrinfo = tempaddrinfo->ai_next)
{
numaddrinfos++;
}
if (numaddrinfos == 0)
{
snprintf(errbuf, errbuflen,
"There are no addresses in the address list");
return INVALID_SOCKET;
}
/*
* Allocate an array of struct addr_status and fill it in.
*/
addrs_to_try = calloc(numaddrinfos, sizeof *addrs_to_try);
if (addrs_to_try == NULL)
{
snprintf(errbuf, errbuflen,
"Out of memory connecting to %s", host);
return INVALID_SOCKET;
}
for (tempaddrinfo = addrinfo, i = 0; tempaddrinfo != NULL;
tempaddrinfo = tempaddrinfo->ai_next, i++)
{
addrs_to_try[i].info = tempaddrinfo;
addrs_to_try[i].errcode = 0;
addrs_to_try[i].errtype = SOCK_NOERR;
}
/*
* Sort the structures to put the IPv4 addresses before the
* IPv6 addresses; we will have to create an IPv4 socket
* for the IPv4 addresses and an IPv6 socket for the IPv6
* addresses (one of the arguments to socket() is the
* address/protocol family to use, and IPv4 and IPv6 are
* separate address/protocol families).
*/
qsort(addrs_to_try, numaddrinfos, sizeof *addrs_to_try,
compare_addrs_to_try_by_address_family);
/* Start out with no socket. */
sock = INVALID_SOCKET;
/*
* Now try them all.
*/
for (i = 0; i < numaddrinfos; i++)
{
tempaddrinfo = addrs_to_try[i].info;
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
break;
#endif
/*
* If we have a socket, but it's for a
* different address family, close it.
*/
if (sock != INVALID_SOCKET &&
current_af != tempaddrinfo->ai_family)
{
closesocket(sock);
sock = INVALID_SOCKET;
}
/*
* If we don't have a socket, open one
* for *this* address's address family.
*/
if (sock == INVALID_SOCKET)
{
sock = sock_create_socket(tempaddrinfo,
errbuf, errbuflen);
if (sock == INVALID_SOCKET)
{
free(addrs_to_try);
return INVALID_SOCKET;
}
}
if (connect(sock, tempaddrinfo->ai_addr, (int) tempaddrinfo->ai_addrlen) == -1)
{
addrs_to_try[i].errcode = sock_geterrcode();
addrs_to_try[i].errtype =
sock_geterrtype(addrs_to_try[i].errcode);
}
else
break;
}
/*
* Check how we exited from the previous loop.
* If tempaddrinfo is equal to NULL, it means that all
* the connect() attempts failed. Construct an
* error message.
*/
if (i == numaddrinfos)
{
int same_error_for_all;
int first_error;
closesocket(sock);
/*
* Sort the statuses to group together categories
* of errors, errors within categories, and
* address families within error sets.
*/
qsort(addrs_to_try, numaddrinfos, sizeof *addrs_to_try,
compare_addrs_to_try_by_status);
/*
* Are all the errors the same?
*/
same_error_for_all = 1;
first_error = addrs_to_try[0].errcode;
for (i = 1; i < numaddrinfos; i++)
{
if (addrs_to_try[i].errcode != first_error)
{
same_error_for_all = 0;
break;
}
}
if (same_error_for_all) {
/*
* Yes. No need to show the IP
* addresses.
*/
if (addrs_to_try[0].errtype == SOCK_CONNERR) {
/*
* Connection error; note that
* the daemon might not be set
* up correctly, or set up at all.
*/
sock_fmterrmsg(errbuf, errbuflen,
addrs_to_try[0].errcode,
"Is the server properly installed? Cannot connect to %s",
host);
} else {
sock_fmterrmsg(errbuf, errbuflen,
addrs_to_try[0].errcode,
"Cannot connect to %s", host);
}
} else {
/*
* Show all the errors and the IP addresses
* to which they apply.
*/
char *errbufptr;
size_t bufspaceleft;
size_t msglen;
snprintf(errbuf, errbuflen,
"Connect to %s failed: ", host);
msglen = strlen(errbuf);
errbufptr = errbuf + msglen;
bufspaceleft = errbuflen - msglen;
for (i = 0; i < numaddrinfos &&
addrs_to_try[i].errcode != SOCK_NOERR;
i++)
{
/*
* Get the string for the address
* and port that got this error.
*/
sock_getascii_addrport((struct sockaddr_storage *) addrs_to_try[i].info->ai_addr,
errbufptr, (int)bufspaceleft,
NULL, 0, NI_NUMERICHOST, NULL, 0);
msglen = strlen(errbuf);
errbufptr = errbuf + msglen;
bufspaceleft = errbuflen - msglen;
if (i + 1 < numaddrinfos &&
addrs_to_try[i + 1].errcode == addrs_to_try[i].errcode)
{
/*
* There's another error
* after this, and it has
* the same error code.
*
* Append a comma, as the
* list of addresses with
* this error has another
* entry.
*/
snprintf(errbufptr, bufspaceleft,
", ");
}
else
{
/*
* Either there are no
* more errors after this,
* or the next error is
* different.
*
* Append a colon and
* the message for tis
* error, followed by a
* comma if there are
* more errors.
*/
sock_fmterrmsg(errbufptr,
bufspaceleft,
addrs_to_try[i].errcode,
"%s", "");
msglen = strlen(errbuf);
errbufptr = errbuf + msglen;
bufspaceleft = errbuflen - msglen;
if (i + 1 < numaddrinfos &&
addrs_to_try[i + 1].errcode != SOCK_NOERR)
{
/*
* More to come.
*/
snprintf(errbufptr,
bufspaceleft,
", ");
}
}
msglen = strlen(errbuf);
errbufptr = errbuf + msglen;
bufspaceleft = errbuflen - msglen;
}
}
free(addrs_to_try);
return INVALID_SOCKET;
}
else
{
free(addrs_to_try);
return sock;
}
}
}
/*
* \brief Closes the present (TCP and UDP) socket connection.
*
* This function sends a shutdown() on the socket in order to disable send() calls
* (while recv() ones are still allowed). Then, it closes the socket.
*
* \param sock: the socket identifier of the connection that has to be closed.
*
* \param errbuf: a pointer to an user-allocated buffer that will contain the complete
* error message. This buffer has to be at least 'errbuflen' in length.
* It can be NULL; in this case the error cannot be printed.
*
* \param errbuflen: length of the buffer that will contains the error. The error message cannot be
* larger than 'errbuflen - 1' because the last char is reserved for the string terminator.
*
* \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
* in the 'errbuf' variable.
*/
int sock_close(SOCKET sock, char *errbuf, int errbuflen)
{
/*
* SHUT_WR: subsequent calls to the send function are disallowed.
* For TCP sockets, a FIN will be sent after all data is sent and
* acknowledged by the Server.
*/
if (shutdown(sock, SHUT_WR))
{
sock_geterrmsg(errbuf, errbuflen, "shutdown() feiled");
/* close the socket anyway */
closesocket(sock);
return -1;
}
closesocket(sock);
return 0;
}
/*
* gai_strerror() has some problems:
*
* 1) on Windows, Microsoft explicitly says it's not thread-safe;
* 2) on UN*X, the Single UNIX Specification doesn't say it *is*
* thread-safe, so an implementation might use a static buffer
* for unknown error codes;
* 3) the error message for the most likely error, EAI_NONAME, is
* truly horrible on several platforms ("nodename nor servname
* provided, or not known"? It's typically going to be "not
* known", not "oopsie, I passed null pointers for the host name
* and service name", not to mention they forgot the "neither");
*
* so we roll our own.
*/
static void
get_gai_errstring(char *errbuf, int errbuflen, const char *prefix, int err,
const char *hostname, const char *portname)
{
char hostport[PCAP_ERRBUF_SIZE];
if (hostname != NULL && portname != NULL)
snprintf(hostport, PCAP_ERRBUF_SIZE, "host and port %s:%s",
hostname, portname);
else if (hostname != NULL)
snprintf(hostport, PCAP_ERRBUF_SIZE, "host %s",
hostname);
else if (portname != NULL)
snprintf(hostport, PCAP_ERRBUF_SIZE, "port %s",
portname);
else
snprintf(hostport, PCAP_ERRBUF_SIZE, "<no host or port!>");
switch (err)
{
#ifdef EAI_ADDRFAMILY
case EAI_ADDRFAMILY:
snprintf(errbuf, errbuflen,
"%sAddress family for %s not supported",
prefix, hostport);
break;
#endif
case EAI_AGAIN:
snprintf(errbuf, errbuflen,
"%s%s could not be resolved at this time",
prefix, hostport);
break;
case EAI_BADFLAGS:
snprintf(errbuf, errbuflen,
"%sThe ai_flags parameter for looking up %s had an invalid value",
prefix, hostport);
break;
case EAI_FAIL:
snprintf(errbuf, errbuflen,
"%sA non-recoverable error occurred when attempting to resolve %s",
prefix, hostport);
break;
case EAI_FAMILY:
snprintf(errbuf, errbuflen,
"%sThe address family for looking up %s was not recognized",
prefix, hostport);
break;
case EAI_MEMORY:
snprintf(errbuf, errbuflen,
"%sOut of memory trying to allocate storage when looking up %s",
prefix, hostport);
break;
/*
* RFC 2553 had both EAI_NODATA and EAI_NONAME.
*
* RFC 3493 has only EAI_NONAME.
*
* Some implementations define EAI_NODATA and EAI_NONAME
* to the same value, others don't. If EAI_NODATA is
* defined and isn't the same as EAI_NONAME, we handle
* EAI_NODATA.
*/
#if defined(EAI_NODATA) && EAI_NODATA != EAI_NONAME
case EAI_NODATA:
snprintf(errbuf, errbuflen,
"%sNo address associated with %s",
prefix, hostport);
break;
#endif
case EAI_NONAME:
snprintf(errbuf, errbuflen,
"%sThe %s couldn't be resolved",
prefix, hostport);
break;
case EAI_SERVICE:
snprintf(errbuf, errbuflen,
"%sThe service value specified when looking up %s as not recognized for the socket type",
prefix, hostport);
break;
case EAI_SOCKTYPE:
snprintf(errbuf, errbuflen,
"%sThe socket type specified when looking up %s as not recognized",
prefix, hostport);
break;