Coverage Report

Created: 2026-10-16 07:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/crypto/bio/bio_sock.c
Line
Count
Source
1
/*
2
 * Copyright 1995-2026 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
#include <stdio.h>
11
#include <stdlib.h>
12
#include "bio_local.h"
13
14
#ifndef OPENSSL_NO_SOCK
15
#define SOCKET_PROTOCOL IPPROTO_TCP
16
#ifdef SO_MAXCONN
17
#define MAX_LISTEN SO_MAXCONN
18
#elif defined(SOMAXCONN)
19
#define MAX_LISTEN SOMAXCONN
20
#else
21
#define MAX_LISTEN 32
22
#endif
23
#if defined(OPENSSL_SYS_WINDOWS)
24
static int wsa_init_done = 0;
25
#endif
26
27
#if defined __TANDEM
28
#include <unistd.h>
29
#include <sys/time.h> /* select */
30
#elif defined _WIN32
31
#include <winsock.h> /* for type fd_set */
32
#else
33
#include <unistd.h>
34
#if defined __VMS
35
#include <sys/socket.h>
36
#elif defined _HPUX_SOURCE
37
#include <sys/time.h>
38
#else
39
#include <sys/select.h>
40
#endif
41
#endif
42
#include "internal/sockets.h" /* for openssl_fdset() */
43
44
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
45
int BIO_get_host_ip(const char *str, unsigned char *ip)
46
0
{
47
0
    BIO_ADDRINFO *res = NULL;
48
0
    int ret = 0;
49
50
0
    if (BIO_sock_init() != 1)
51
0
        return 0; /* don't generate another error code here */
52
53
0
    if (BIO_lookup(str, NULL, BIO_LOOKUP_CLIENT, AF_INET, SOCK_STREAM, &res)) {
54
0
        size_t l;
55
56
0
        if (BIO_ADDRINFO_family(res) != AF_INET) {
57
0
            ERR_raise(ERR_LIB_BIO, BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET);
58
0
        } else if (BIO_ADDR_rawaddress(BIO_ADDRINFO_address(res), NULL, &l)) {
59
            /*
60
             * Because only AF_INET addresses will reach this far, we can assert
61
             * that l should be 4
62
             */
63
0
            if (ossl_assert(l == 4))
64
0
                ret = BIO_ADDR_rawaddress(BIO_ADDRINFO_address(res), ip, &l);
65
0
        }
66
0
        BIO_ADDRINFO_free(res);
67
0
    } else {
68
0
        ERR_add_error_data(2, "host=", str);
69
0
    }
70
71
0
    return ret;
72
0
}
73
74
int BIO_get_port(const char *str, unsigned short *port_ptr)
75
0
{
76
0
    BIO_ADDRINFO *res = NULL;
77
0
    int ret = 0;
78
79
0
    if (str == NULL) {
80
0
        ERR_raise(ERR_LIB_BIO, BIO_R_NO_PORT_DEFINED);
81
0
        return 0;
82
0
    }
83
84
0
    if (BIO_sock_init() != 1)
85
0
        return 0; /* don't generate another error code here */
86
87
0
    if (BIO_lookup(NULL, str, BIO_LOOKUP_CLIENT, AF_INET, SOCK_STREAM, &res)) {
88
0
        if (BIO_ADDRINFO_family(res) != AF_INET) {
89
0
            ERR_raise(ERR_LIB_BIO, BIO_R_ADDRINFO_ADDR_IS_NOT_AF_INET);
90
0
        } else {
91
0
            *port_ptr = ntohs(BIO_ADDR_rawport(BIO_ADDRINFO_address(res)));
92
0
            ret = 1;
93
0
        }
94
0
        BIO_ADDRINFO_free(res);
95
0
    } else {
96
0
        ERR_add_error_data(2, "host=", str);
97
0
    }
98
99
0
    return ret;
100
0
}
101
#endif
102
103
int BIO_sock_error(int sock)
104
0
{
105
0
    int j = 0, i;
106
0
    socklen_t size = sizeof(j);
107
108
    /*
109
     * Note: under Windows the third parameter is of type (char *) whereas
110
     * under other systems it is (void *) if you don't have a cast it will
111
     * choke the compiler: if you do have a cast then you can either go for
112
     * (char *) or (void *).
113
     */
114
0
    i = getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *)&j, &size);
115
0
    if (i < 0)
116
0
        return get_last_socket_error();
117
0
    else
118
0
        return j;
119
0
}
120
121
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
122
struct hostent *BIO_gethostbyname(const char *name)
123
0
{
124
    /*
125
     * Caching gethostbyname() results forever is wrong, so we have to let
126
     * the true gethostbyname() worry about this
127
     */
128
0
    return gethostbyname(name);
129
0
}
130
#endif
131
132
#ifdef BIO_HAVE_WSAMSG
133
LPFN_WSARECVMSG bio_WSARecvMsg;
134
LPFN_WSASENDMSG bio_WSASendMsg;
135
#endif
136
137
int BIO_sock_init(void)
138
0
{
139
#ifdef OPENSSL_SYS_WINDOWS
140
    static struct WSAData wsa_state;
141
142
    if (!wsa_init_done) {
143
        wsa_init_done = 1;
144
        memset(&wsa_state, 0, sizeof(wsa_state));
145
        /*
146
         * Not making wsa_state available to the rest of the code is formally
147
         * wrong. But the structures we use are [believed to be] invariable
148
         * among Winsock DLLs, while API availability is [expected to be]
149
         * probed at run-time with DSO_global_lookup.
150
         */
151
        if (WSAStartup(0x0202, &wsa_state) != 0) {
152
            ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
153
                "calling wsastartup()");
154
            ERR_raise(ERR_LIB_BIO, BIO_R_WSASTARTUP);
155
            return -1;
156
        }
157
158
        /*
159
         * On Windows, some socket functions are not exposed as a prototype.
160
         * Instead, their function pointers must be loaded via this elaborate
161
         * process...
162
         */
163
#ifdef BIO_HAVE_WSAMSG
164
        {
165
            GUID id_WSARecvMsg = WSAID_WSARECVMSG;
166
            GUID id_WSASendMsg = WSAID_WSASENDMSG;
167
            DWORD len_out = 0;
168
            SOCKET s;
169
170
            s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
171
            if (s != INVALID_SOCKET) {
172
                if (WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER,
173
                        &id_WSARecvMsg, sizeof(id_WSARecvMsg),
174
                        &bio_WSARecvMsg, sizeof(bio_WSARecvMsg),
175
                        &len_out, NULL, NULL)
176
                        != 0
177
                    || len_out != sizeof(bio_WSARecvMsg))
178
                    bio_WSARecvMsg = NULL;
179
180
                if (WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER,
181
                        &id_WSASendMsg, sizeof(id_WSASendMsg),
182
                        &bio_WSASendMsg, sizeof(bio_WSASendMsg),
183
                        &len_out, NULL, NULL)
184
                        != 0
185
                    || len_out != sizeof(bio_WSASendMsg))
186
                    bio_WSASendMsg = NULL;
187
188
                closesocket(s);
189
            }
190
        }
191
#endif
192
    }
193
#endif /* OPENSSL_SYS_WINDOWS */
194
#ifdef WATT32
195
    extern int _watt_do_exit;
196
    _watt_do_exit = 0; /* don't make sock_init() call exit() */
197
    if (sock_init())
198
        return -1;
199
#endif
200
201
0
    return 1;
202
0
}
203
204
void bio_sock_cleanup_int(void)
205
0
{
206
#ifdef OPENSSL_SYS_WINDOWS
207
    if (wsa_init_done) {
208
        wsa_init_done = 0;
209
        WSACleanup();
210
    }
211
#endif
212
0
}
213
214
int BIO_socket_ioctl(int fd, long type, void *arg)
215
0
{
216
0
    int i;
217
218
#ifdef __DJGPP__
219
    i = ioctlsocket(fd, type, (char *)arg);
220
#else
221
#if defined(OPENSSL_SYS_VMS)
222
    /*-
223
     * 2011-02-18 SMS.
224
     * VMS ioctl() can't tolerate a 64-bit "void *arg", but we
225
     * observe that all the consumers pass in an "unsigned long *",
226
     * so we arrange a local copy with a short pointer, and use
227
     * that, instead.
228
     */
229
#if __INITIAL_POINTER_SIZE == 64
230
#define ARG arg_32p
231
#pragma pointer_size save
232
#pragma pointer_size 32
233
    unsigned long arg_32;
234
    unsigned long *arg_32p;
235
#pragma pointer_size restore
236
    arg_32p = &arg_32;
237
    arg_32 = *((unsigned long *)arg);
238
#else /* __INITIAL_POINTER_SIZE == 64 */
239
#define ARG arg
240
#endif /* __INITIAL_POINTER_SIZE == 64 [else] */
241
#else /* defined(OPENSSL_SYS_VMS) */
242
0
#define ARG arg
243
0
#endif /* defined(OPENSSL_SYS_VMS) [else] */
244
245
0
    i = ioctlsocket(fd, type, ARG);
246
0
#endif /* __DJGPP__ */
247
0
    if (i < 0)
248
0
        ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
249
0
            "calling ioctlsocket()");
250
0
    return i;
251
0
}
252
253
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
254
int BIO_get_accept_socket(char *host, int bind_mode)
255
0
{
256
0
    int s = INVALID_SOCKET;
257
0
    char *h = NULL, *p = NULL;
258
0
    BIO_ADDRINFO *res = NULL;
259
260
0
    if (!BIO_parse_hostserv(host, &h, &p, BIO_PARSE_PRIO_SERV))
261
0
        return INVALID_SOCKET;
262
263
0
    if (BIO_sock_init() != 1)
264
0
        goto err;
265
266
0
    if (BIO_lookup(h, p, BIO_LOOKUP_SERVER, AF_UNSPEC, SOCK_STREAM, &res) == 0)
267
0
        goto err;
268
269
0
    if ((s = BIO_socket(BIO_ADDRINFO_family(res), BIO_ADDRINFO_socktype(res),
270
0
             BIO_ADDRINFO_protocol(res), 0))
271
0
        == INVALID_SOCKET) {
272
0
        s = INVALID_SOCKET;
273
0
        goto err;
274
0
    }
275
276
0
    if (!BIO_listen(s, BIO_ADDRINFO_address(res),
277
0
            bind_mode ? BIO_SOCK_REUSEADDR : 0)) {
278
0
        BIO_closesocket(s);
279
0
        s = INVALID_SOCKET;
280
0
    }
281
282
0
err:
283
0
    BIO_ADDRINFO_free(res);
284
0
    OPENSSL_free(h);
285
0
    OPENSSL_free(p);
286
287
0
    return s;
288
0
}
289
290
int BIO_accept(int sock, char **ip_port)
291
0
{
292
0
    BIO_ADDR res;
293
0
    int ret = -1;
294
295
0
    ret = BIO_accept_ex(sock, &res, 0);
296
0
    if (ret == (int)INVALID_SOCKET) {
297
0
        if (BIO_sock_should_retry(ret)) {
298
0
            ret = -2;
299
0
            goto end;
300
0
        }
301
0
        ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
302
0
            "calling accept()");
303
0
        ERR_raise(ERR_LIB_BIO, BIO_R_ACCEPT_ERROR);
304
0
        goto end;
305
0
    }
306
307
0
    if (ip_port != NULL) {
308
0
        char *host = BIO_ADDR_hostname_string(&res, 1);
309
0
        char *port = BIO_ADDR_service_string(&res, 1);
310
311
0
        if (host == NULL || port == NULL
312
0
            || ossl_asprintf(ip_port, "%s:%s", host, port) < 0) {
313
0
            *ip_port = NULL;
314
0
            ERR_raise(ERR_LIB_BIO, ERR_R_BIO_LIB);
315
0
            BIO_closesocket(ret);
316
0
            ret = (int)INVALID_SOCKET;
317
0
        }
318
0
        OPENSSL_free(host);
319
0
        OPENSSL_free(port);
320
0
    }
321
322
0
end:
323
0
    return ret;
324
0
}
325
#endif
326
327
int BIO_set_tcp_ndelay(int s, int on)
328
0
{
329
0
    int ret = 0;
330
0
#if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP))
331
0
    int opt;
332
333
0
#ifdef SOL_TCP
334
0
    opt = SOL_TCP;
335
#else
336
#ifdef IPPROTO_TCP
337
    opt = IPPROTO_TCP;
338
#endif
339
#endif
340
341
0
    ret = setsockopt(s, opt, TCP_NODELAY, (char *)&on, sizeof(on));
342
0
#endif
343
0
    return (ret == 0);
344
0
}
345
346
int BIO_socket_nbio(int s, int mode)
347
0
{
348
0
    int ret = -1;
349
0
    int l;
350
351
0
    l = mode;
352
0
#ifdef FIONBIO
353
0
    l = mode;
354
355
0
    ret = BIO_socket_ioctl(s, FIONBIO, &l);
356
#elif defined(F_GETFL) && defined(F_SETFL) && (defined(O_NONBLOCK) || defined(FNDELAY))
357
    /* make sure this call always pushes an error level; BIO_socket_ioctl() does so, so we do too. */
358
359
    l = fcntl(s, F_GETFL, 0);
360
    if (l == -1) {
361
        ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(),
362
            "calling fcntl()");
363
        ret = -1;
364
    } else {
365
#if defined(O_NONBLOCK)
366
        l &= ~O_NONBLOCK;
367
#else
368
        l &= ~FNDELAY; /* BSD4.x */
369
#endif
370
        if (mode) {
371
#if defined(O_NONBLOCK)
372
            l |= O_NONBLOCK;
373
#else
374
            l |= FNDELAY; /* BSD4.x */
375
#endif
376
        }
377
        ret = fcntl(s, F_SETFL, l);
378
379
        if (ret < 0) {
380
            ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(),
381
                "calling fcntl()");
382
        }
383
    }
384
#else
385
    /* make sure this call always pushes an error level; BIO_socket_ioctl() does so, so we do too. */
386
    ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_INVALID_ARGUMENT);
387
#endif
388
389
0
    return (ret == 0);
390
0
}
391
392
int BIO_sock_info(int sock,
393
    enum BIO_sock_info_type type, union BIO_sock_info_u *info)
394
0
{
395
0
    switch (type) {
396
0
    case BIO_SOCK_INFO_ADDRESS: {
397
0
        socklen_t addr_len;
398
0
        int ret = 0;
399
0
        addr_len = sizeof(*info->addr);
400
0
        ret = getsockname(sock, BIO_ADDR_sockaddr_noconst(info->addr),
401
0
            &addr_len);
402
0
        if (ret == -1) {
403
0
            ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
404
0
                "calling getsockname()");
405
0
            ERR_raise(ERR_LIB_BIO, BIO_R_GETSOCKNAME_ERROR);
406
0
            return 0;
407
0
        }
408
0
        if ((size_t)addr_len > sizeof(*info->addr)) {
409
0
            ERR_raise(ERR_LIB_BIO, BIO_R_GETSOCKNAME_TRUNCATED_ADDRESS);
410
0
            return 0;
411
0
        }
412
0
    } break;
413
0
    default:
414
0
        ERR_raise(ERR_LIB_BIO, BIO_R_UNKNOWN_INFO_TYPE);
415
0
        return 0;
416
0
    }
417
0
    return 1;
418
0
}
419
420
/*
421
 * Wait on fd at most until max_time; succeed immediately if max_time == 0.
422
 * If for_read == 0 then assume to wait for writing, else wait for reading.
423
 * Returns -1 on error, 0 on timeout, and 1 on success.
424
 */
425
int BIO_socket_wait(int fd, int for_read, time_t max_time)
426
0
{
427
#if defined(OPENSSL_SYS_WINDOWS) || !defined(POLLIN)
428
    fd_set confds;
429
    struct timeval tv;
430
    time_t now;
431
432
#ifdef _WIN32
433
    if (fd == (int)INVALID_SOCKET)
434
#else
435
    if (fd < 0 || fd >= FD_SETSIZE)
436
#endif
437
        return -1;
438
    if (max_time == 0)
439
        return 1;
440
441
    now = time(NULL);
442
    if (max_time < now)
443
        return 0;
444
445
    FD_ZERO(&confds);
446
    openssl_fdset(fd, &confds);
447
    tv.tv_usec = 0;
448
    tv.tv_sec = (long)(max_time - now); /* might overflow */
449
    return select(fd + 1, for_read ? &confds : NULL,
450
        for_read ? NULL : &confds, NULL, &tv);
451
#else
452
0
    struct pollfd confds;
453
0
    time_t now;
454
455
0
    if (fd < 0)
456
0
        return -1;
457
0
    if (max_time == 0)
458
0
        return 1;
459
460
0
    now = time(NULL);
461
0
    if (max_time < now)
462
0
        return 0;
463
464
0
    confds.fd = fd;
465
0
    confds.events = for_read ? POLLIN : POLLOUT;
466
0
    return poll(&confds, 1, (int)(max_time - now) * 1000);
467
0
#endif
468
0
}
469
470
/*
471
 * Check if fd is ready for reading or writing without blocking.
472
 * If for_read == 0 then check for writing, else check for reading.
473
 * Returns -1 on error, 0 if not ready, and 1 if ready.
474
 */
475
int BIO_socket_ready(int fd, int for_read)
476
0
{
477
#if defined(OPENSSL_SYS_WINDOWS) || !defined(POLLIN)
478
    fd_set confds;
479
    struct timeval tv;
480
481
#ifdef _WIN32
482
    if (fd == (int)INVALID_SOCKET)
483
#else
484
    if (fd < 0 || fd >= FD_SETSIZE)
485
#endif
486
        return -1;
487
488
    FD_ZERO(&confds);
489
    openssl_fdset(fd, &confds);
490
    tv.tv_sec = 0;
491
    tv.tv_usec = 0;
492
    return select(fd + 1, for_read ? &confds : NULL,
493
        for_read ? NULL : &confds, NULL, &tv);
494
#else
495
0
    struct pollfd confds;
496
497
0
    if (fd < 0)
498
0
        return -1;
499
500
0
    confds.fd = fd;
501
0
    confds.events = for_read ? POLLIN : POLLOUT;
502
0
    confds.revents = 0;
503
0
    return poll(&confds, 1, 0);
504
0
#endif
505
0
}
506
#endif /* !defined(OPENSSL_NO_SOCK) */