Code Coverage: vinyl-cache/lib/libvinyl/vtcp.c
 
82217aa4fc7094b3610340078afaf78cd95a8ec9
 
0
/*-
1
 * Copyright (c) 2006 Verdens Gang AS
2
 * Copyright (c) 2006-2015 Varnish Software AS
3
 * All rights reserved.
4
 *
5
 * Author: Poul-Henning Kamp <phk@phk.freebsd.dk>
6
 *
7
 * SPDX-License-Identifier: BSD-2-Clause
8
 *
9
 * Redistribution and use in source and binary forms, with or without
10
 * modification, are permitted provided that the following conditions
11
 * are met:
12
 * 1. Redistributions of source code must retain the above copyright
13
 *    notice, this list of conditions and the following disclaimer.
14
 * 2. Redistributions in binary form must reproduce the above copyright
15
 *    notice, this list of conditions and the following disclaimer in the
16
 *    documentation and/or other materials provided with the distribution.
17
 *
18
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21
 * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
22
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28
 * SUCH DAMAGE.
29
 */
30
31
#include "config.h"
32
33
#include <sys/types.h>
34
#include <sys/socket.h>
35
#include <sys/time.h>           // for NetBSD
36
#include <sys/ioctl.h>
37
#ifdef HAVE_SYS_FILIO_H
38
#  include <sys/filio.h>
39
#endif
40
41
#include <netinet/in.h>
42
#include <netinet/tcp.h>
43
44
#include <math.h>
45
#include <netdb.h>
46
#include <poll.h>
47
#include <stdio.h>
48
#include <string.h>
49
#include <unistd.h>
50
#include <stdlib.h>
51
52
#include "vdef.h"
53
#include "miniobj.h"
54
#include "vas.h"
55
#include "vsa.h"
56
#include "vss.h"
57
#include "vtcp.h"
58
#include "vtim.h"
59
60
/*--------------------------------------------------------------------*/
61
static void
62
vtcp_sa_to_ascii(const void *sa, socklen_t l, char *abuf, unsigned alen,
63
    char *pbuf, unsigned plen)
64 30063
{
65 30063
        int i;
66
67 30063
        assert(abuf == NULL || alen > 0);
68 30063
        assert(pbuf == NULL || plen > 0);
69 30063
        i = getnameinfo(sa, l, abuf, alen, pbuf, plen,
70 30063
           NI_NUMERICHOST | NI_NUMERICSERV);
71 30063
        if (i) {
72
                /*
73
                 * XXX this printf is shitty, but we may not have space
74
                 * for the gai_strerror in the buffer :-(
75
                 */
76 0
                fprintf(stderr, "getnameinfo = %d %s\n", i, gai_strerror(i));
77 0
                if (i == EAI_SYSTEM)
78 0
                        fprintf(stderr, "errno = %d %s\n", errno, VAS_errtxt(errno));
79 0
                if (abuf != NULL)
80 0
                        (void)snprintf(abuf, alen, "Conversion");
81 0
                if (pbuf != NULL)
82 0
                        (void)snprintf(pbuf, plen, "Failed");
83 0
                return;
84 0
        }
85 30063
}
86
87
/*--------------------------------------------------------------------*/
88
89
void
90
VTCP_name(const struct suckaddr *addr, char *abuf, unsigned alen,
91
    char *pbuf, unsigned plen)
92 30064
{
93 30064
        const struct sockaddr *sa;
94 30064
        socklen_t sl;
95
96 30064
        sa = VSA_Get_Sockaddr(addr, &sl);
97 30064
        AN(sa);
98 30064
        vtcp_sa_to_ascii(sa, sl, abuf, alen, pbuf, plen);
99 30064
}
100
101
/*--------------------------------------------------------------------*/
102
103
struct suckaddr *
104
VTCP_my_suckaddr(int sock)
105 1042
{
106 1042
        struct suckaddr *r;
107
108 1042
        r = malloc(vsa_suckaddr_len);
109 1042
        AN(VSA_getsockname(sock, r, vsa_suckaddr_len));
110 1042
        return (r);
111 1042
}
112
113
/*--------------------------------------------------------------------*/
114
115
void
116
VTCP_myname(int sock, char *abuf, unsigned alen, char *pbuf, unsigned plen)
117 12633
{
118 12633
        char buf[vsa_suckaddr_len];
119
120 12633
        VTCP_name(VSA_getsockname(sock, buf, sizeof buf),
121 12633
                  abuf, alen, pbuf, plen);
122 12633
}
123
124
/*--------------------------------------------------------------------*/
125
126
void
127
VTCP_hisname(int sock, char *abuf, unsigned alen, char *pbuf, unsigned plen)
128 8683
{
129 8683
        char buf[vsa_suckaddr_len];
130 8683
        const struct suckaddr *sua;
131
132 8683
        sua = VSA_getpeername(sock, buf, sizeof buf);
133 8683
        if (sua != NULL)
134 8673
                VTCP_name(sua, abuf, alen, pbuf, plen);
135 10
        else {
136 10
                (void)snprintf(abuf, alen, "<none>");
137 10
                (void)snprintf(pbuf, plen, "<none>");
138 10
        }
139 8683
}
140
141
/*--------------------------------------------------------------------*/
142
143
#ifdef HAVE_ACCEPT_FILTERS
144
145
int
146
VTCP_filter_http(int sock)
147 1026
{
148 1026
        int retval;
149 1026
        struct accept_filter_arg afa;
150
151 1026
        memset(&afa, 0, sizeof afa);
152 1026
        bprintf(afa.af_name, "%s", "httpready");
153 1026
        retval = setsockopt(sock, SOL_SOCKET, SO_ACCEPTFILTER,
154 1026
            &afa, sizeof afa);
155 1026
        return (retval);
156 1026
}
157
158
#elif defined(__linux)
159
160
int
161
VTCP_filter_http(int sock)
162
{
163
        int retval;
164
        int defer = 1;
165
166
        retval = setsockopt(sock, SOL_TCP, TCP_DEFER_ACCEPT,
167
            &defer, sizeof defer);
168
        return (retval);
169
}
170
171
#else
172
173
int
174
VTCP_filter_http(int sock)
175
{
176
        errno = EOPNOTSUPP;
177
        (void)sock;
178
        return (-1);
179
}
180
181
#endif
182
183
/*--------------------------------------------------------------------*/
184
185
186
int
187
VTCP_fastopen(int sock, int depth)
188 0
{
189 0
#ifdef HAVE_TCP_FASTOPEN
190 0
#  ifndef SOL_TCP
191 0
#    define SOL_TCP IPPROTO_TCP
192 0
#  endif
193 0
        return (setsockopt(sock, SOL_TCP, TCP_FASTOPEN, &depth, sizeof depth));
194
#else
195
        errno = EOPNOTSUPP;
196
        (void)sock;
197
        (void)depth;
198
        return (-1);
199
#endif
200 0
}
201
202
203
/*--------------------------------------------------------------------
204
 * Functions for controlling NONBLOCK mode.
205
 *
206
 * We use FIONBIO because it is cheaper than fcntl(2), which requires
207
 * us to do two syscalls, one to get and one to set, the latter of
208
 * which mucks about a bit before it ends up calling ioctl(FIONBIO),
209
 * at least on FreeBSD.
210
 * On Solaris ioctl(FIONBIO) can fail with connection related errnos,
211
 * but as long as that is how they fail, we're fine.
212
 */
213
214
void
215
VTCP_blocking(int sock)
216 16126
{
217 16126
        int i, j;
218
219 16126
        i = 0;
220 16126
        j = ioctl(sock, FIONBIO, &i);
221 16126
        VTCP_Assert(j);
222 16126
}
223
224
void
225
VTCP_nonblocking(int sock)
226 5533
{
227 5533
        int i, j;
228
229 5533
        i = 1;
230 5533
        j = ioctl(sock, FIONBIO, &i);
231 5533
        VTCP_Assert(j);
232 5533
}
233
234
/*--------------------------------------------------------------------
235
 * On TCP a connect(2) can block for a looong time, and we don't want that.
236
 * Unfortunately, the SocketWizards back in those days were happy to wait
237
 * any amount of time for a connection, so the connect(2) syscall does not
238
 * take an argument for patience.
239
 *
240
 * There is a little used work-around, and we employ it at our peril.
241
 *
242
 */
243
244
int
245
VTCP_connected(int s)
246 4711
{
247 4711
        int k;
248 4711
        socklen_t l;
249
250
        /* Find out if we got a connection */
251 4711
        l = sizeof k;
252 4711
        AZ(getsockopt(s, SOL_SOCKET, SO_ERROR, &k, &l));
253
254
        /* An error means no connection established */
255 4711
        errno = k;
256 4711
        if (k) {
257 29
                closefd(&s);
258 29
                return (-1);
259 29
        }
260
261 4682
        VTCP_blocking(s);
262 4682
        return (s);
263 4711
}
264
265
int
266
VTCP_connect(const struct suckaddr *name, int msec)
267 4953
{
268 4953
        int s, i;
269 4953
        struct pollfd fds[1];
270 4953
        const struct sockaddr *sa;
271 4953
        socklen_t sl;
272 4953
        int val;
273
274 4953
        if (name == NULL)
275 35
                return (-1);
276
        /* Attempt the connect */
277 4918
        AN(VSA_Sane(name));
278 4918
        sa = VSA_Get_Sockaddr(name, &sl);
279 4918
        AN(sa);
280 4918
        AN(sl);
281
282 4918
        s = socket(sa->sa_family, SOCK_STREAM, 0);
283 4918
        if (s < 0)
284 0
                return (s);
285
286
        /* Set the socket non-blocking */
287 4918
        if (msec != 0)
288 4713
                VTCP_nonblocking(s);
289
290 4918
        val = 1;
291 4918
        AZ(setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &val, sizeof val));
292
293 4918
        i = connect(s, sa, sl);
294 4918
        if (i == 0 && msec > 0)
295 0
                VTCP_blocking(s);
296 4918
        if (i == 0)
297 205
                return (s);
298 4713
        if (errno != EINPROGRESS) {
299 0
                closefd(&s);
300 0
                return (-1);
301 0
        }
302
303 4713
        if (msec < 0) {
304
                /*
305
                 * Caller is responsible for waiting and
306
                 * calling VTCP_connected
307
                 */
308 1025
                return (s);
309 1025
        }
310
311 3688
        assert(msec > 0);
312
        /* Exercise our patience, polling for write */
313 3688
        fds[0].fd = s;
314 3688
        fds[0].events = POLLWRNORM;
315 3688
        fds[0].revents = 0;
316 3688
        i = poll(fds, 1, msec);
317
318 3688
        if (i == 0) {
319
                /* Timeout, close and give up */
320 2
                closefd(&s);
321 2
                errno = ETIMEDOUT;
322 2
                return (-1);
323 2
        }
324
325 3686
        return (VTCP_connected(s));
326 3688
}
327
328
/*--------------------------------------------------------------------
329
 * When closing a TCP connection, a couple of errno's are legit, we
330
 * can't be held responsible for the other end wanting to talk to us.
331
 */
332
333
void
334
VTCP_close(int *s)
335 6942
{
336 6942
        int i;
337
338 6942
        i = close(*s);
339
340 6942
        VTCP_Assert(i);
341 6942
        *s = -1;
342 6942
}
343
344
void
345
VTCP_set_read_timeout(int s, vtim_dur seconds)
346 2755
{
347 2755
        struct timeval timeout = VTIM_timeval_sock(seconds);
348
349
        /*
350
         * Solaris bug (present at least in snv_151 and older): If this fails
351
         * with EINVAL, the socket is half-closed (SS_CANTSENDMORE) and the
352
         * timeout does not get set. Needs to be fixed in Solaris, there is
353
         * nothing we can do about this.
354
         */
355 2755
        VTCP_Assert(setsockopt(s, SOL_SOCKET, SO_RCVTIMEO,
356 2755
            &timeout, sizeof timeout));
357 2755
}
358
359
/*--------------------------------------------------------------------
360
 */
361
362
struct vto_priv {
363
        unsigned                magic;
364
#define VTO_PRIV_MAGIC          0xca70b0e7
365
        int                     latest_errno;
366
        int                     fd;
367
        double                  timeout;
368
};
369
370
static int v_matchproto_(vss_resolved_f)
371
vtcp_open_callback(void *priv, const struct suckaddr *sa)
372 2381
{
373 2381
        struct vto_priv *vto;
374 2381
        int fd;
375
376 2381
        CAST_OBJ_NOTNULL(vto, priv, VTO_PRIV_MAGIC);
377
378 2381
        errno = 0;
379 2381
        fd = VTCP_connect(sa, (int)floor(vto->timeout * 1e3));
380 2381
        if (fd >= 0) {
381 2380
                vto->fd = fd;
382 2380
                vto->latest_errno = 0;
383 2380
                return (1);
384 2380
        }
385 1
        vto->latest_errno = errno;
386 1
        return (0);
387 2381
}
388
389
int
390
VTCP_open(const char *addr, const char *def_port, vtim_dur timeout,
391
    const char **errp)
392 2381
{
393 2381
        struct vto_priv vto[1];
394
395 2381
        AN(errp);
396 2381
        assert(timeout >= 0);
397 2381
        INIT_OBJ(vto, VTO_PRIV_MAGIC);
398 2381
        vto->fd = -1;
399 2381
        vto->timeout = timeout;
400
401 2381
        if (VSS_resolver(addr, def_port, vtcp_open_callback, vto, errp) < 0)
402 0
                return (-1);
403 2381
        if (vto->fd < 0)
404 1
                *errp = strerror(vto->latest_errno);
405 2381
        return (vto->fd);
406 2381
}
407
408
/*--------------------------------------------------------------------
409
 * Given a struct suckaddr, open a socket of the appropriate type, and bind
410
 * it to the requested address.
411
 *
412
 * If the address is an IPv6 address, the IPV6_V6ONLY option is set to
413
 * avoid conflicts between INADDR_ANY and IN6ADDR_ANY.
414
 */
415
416
int
417
VTCP_bind(const struct suckaddr *sa, const char **errp)
418 8574
{
419 8574
        int sd, val, e;
420 8574
        socklen_t sl;
421 8574
        const struct sockaddr *so;
422 8574
        int proto;
423
424 8574
        if (errp != NULL)
425 5435
                *errp = NULL;
426
427 8574
        proto = VSA_Get_Proto(sa);
428 8574
        sd = socket(proto, SOCK_STREAM, 0);
429 8574
        if (sd < 0) {
430 0
                if (errp != NULL)
431 0
                        *errp = "socket(2)";
432 0
                return (-1);
433 0
        }
434 8574
        val = 1;
435 8574
        if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof val) != 0) {
436 0
                if (errp != NULL)
437 0
                        *errp = "setsockopt(SO_REUSEADDR, 1)";
438 0
                e = errno;
439 0
                closefd(&sd);
440 0
                errno = e;
441 0
                return (-1);
442 0
        }
443 8574
#ifdef IPV6_V6ONLY
444
        /* forcibly use separate sockets for IPv4 and IPv6 */
445 8574
        val = 1;
446 8574
        if (proto == AF_INET6 &&
447 8574
            setsockopt(sd, IPPROTO_IPV6, IPV6_V6ONLY, &val, sizeof val) != 0) {
448 0
                if (errp != NULL)
449 0
                        *errp = "setsockopt(IPV6_V6ONLY, 1)";
450 0
                e = errno;
451 0
                closefd(&sd);
452 0
                errno = e;
453 0
                return (-1);
454 0
        }
455 8574
#endif
456 8574
        so = VSA_Get_Sockaddr(sa, &sl);
457 8574
        if (bind(sd, so, sl) != 0) {
458 1
                if (errp != NULL)
459 0
                        *errp = "bind(2)";
460 1
                e = errno;
461 1
                closefd(&sd);
462 1
                errno = e;
463 1
                return (-1);
464 1
        }
465 8573
        return (sd);
466 8574
}
467
468
/*--------------------------------------------------------------------
469
 * Given a struct suckaddr, open a socket of the appropriate type, bind it
470
 * to the requested address, and start listening.
471
 */
472
473
int
474
VTCP_listen(const struct suckaddr *sa, int depth, const char **errp)
475 5435
{
476 5435
        int sd;
477 5435
        int e;
478
479 5435
        if (errp != NULL)
480 5435
                *errp = NULL;
481 5435
        sd = VTCP_bind(sa, errp);
482 5435
        if (sd >= 0)  {
483 5435
                if (listen(sd, depth) != 0) {
484 0
                        e = errno;
485 0
                        closefd(&sd);
486 0
                        errno = e;
487 0
                        if (errp != NULL)
488 0
                                *errp = "listen(2)";
489 0
                        return (-1);
490 0
                }
491 5435
        }
492 5435
        return (sd);
493 5435
}
494
495
/*--------------------------------------------------------------------*/
496
497
struct helper {
498
        int             depth;
499
        const char      **errp;
500
};
501
502
static int v_matchproto_(vss_resolved_f)
503
vtcp_lo_cb(void *priv, const struct suckaddr *sa)
504 3359
{
505 3359
        int sock;
506 3359
        struct helper *hp = priv;
507
508 3359
        sock = VTCP_listen(sa, hp->depth, hp->errp);
509 3359
        if (sock >= 0) {
510 3359
                *hp->errp = NULL;
511 3359
                return (sock);
512 3359
        }
513 0
        AN(*hp->errp);
514 0
        return (0);
515 0
}
516
517
int
518
VTCP_listen_on(const char *addr, const char *def_port, int depth,
519
    const char **errp)
520 3359
{
521 3359
        struct helper h;
522 3359
        int sock;
523
524 3359
        AN(errp);
525 3359
        h.depth = depth;
526 3359
        h.errp = errp;
527
528 3359
        sock = VSS_resolver(addr, def_port, vtcp_lo_cb, &h, errp);
529 3359
        if (*errp != NULL)
530 0
                return (-1);
531 3359
        return (sock);
532 3359
}
533
534
/*--------------------------------------------------------------------
535
 * Set or reset SO_LINGER flag
536
 */
537
538
int
539
VTCP_linger(int sock, int linger)
540 0
{
541 0
        struct linger lin;
542 0
        int i;
543
544 0
        memset(&lin, 0, sizeof lin);
545 0
        lin.l_onoff = linger;
546 0
        i = setsockopt(sock, SOL_SOCKET, SO_LINGER, &lin, sizeof lin);
547 0
        VTCP_Assert(i);
548 0
        return (i);
549 0
}
550
551
/*--------------------------------------------------------------------
552
 * Do a poll to check for remote HUP
553
 */
554
555
int
556
VTCP_check_hup(int sock)
557 0
{
558 0
        struct pollfd pfd;
559
560 0
        assert(sock > 0);
561 0
        pfd.fd = sock;
562 0
        pfd.events = POLLOUT;
563 0
        pfd.revents = 0;
564
565 0
        if (poll(&pfd, 1, 0) == 1 && pfd.revents & POLLHUP)
566 0
                return (1);
567 0
        return (0);
568 0
}
569
570
/*--------------------------------------------------------------------
571
 * Check if a TCP syscall return value is fatal
572
 */
573
574
int
575
VTCP_Check(ssize_t a)
576 56436
{
577 56436
        if (a == 0)
578 47566
                return (1);
579 8870
        if (a > 0)
580 8842
                return (1);
581 28
        if (errno == ECONNRESET || errno == ENOTCONN || errno == EPIPE)
582 21
                return (1);
583
        /* Accept EAGAIN (and EWOULDBLOCK in case they are not the same)
584
         * as errno values. Even though our sockets are all non-blocking,
585
         * when a SO_{SND|RCV}TIMEO expires, read() or write() on the
586
         * socket will return (-1) and errno set to EAGAIN. (This is not
587
         * documented in the read(2) and write(2) manpages, but is
588
         * described in the socket(7) manpage.) */
589 7
        if (errno == EAGAIN || errno == EWOULDBLOCK)
590 9
                return (1);
591
        /* tcp(7): The other end didn't acknowledge retransmitted data after
592
         * some time. */
593 18446744073709551614
        if (errno == ETIMEDOUT)
594 0
                return (1);
595
        /* #3539 various errnos documented on linux as POSIX.1 */
596 18446744073709551614
        if (errno == ENETDOWN || errno == ENETUNREACH || errno == ENETRESET ||
597 18446744073709551614
            errno == ECONNABORTED || /* ECONNRESET see above */
598 18446744073709551614
            errno == EHOSTUNREACH || errno == EHOSTDOWN) {
599 0
                return (1);
600 0
        }
601
602
#if (defined (__SVR4) && defined (__sun))
603
        if (errno == ECONNREFUSED)      // in r02702.vtc
604
                return (1);
605
        if (errno == EPROTO)
606
                return (1);
607
#endif
608
#if (defined (__SVR4) && defined (__sun)) ||            \
609
    defined (__NetBSD__) ||                             \
610
    defined (__APPLE__)
611
        /*
612
         * Solaris and macOS returns EINVAL if the other end unexpectedly reset
613
         * the connection.
614
         *
615
         * On NetBSD it is documented behaviour.
616
         */
617
        if (errno == EINVAL)
618
                return (1);
619
#endif
620
#if defined(ENABLE_SANITIZER)
621
        if (errno == EINTR)
622
                return (1);
623
#endif
624 18446744073709551614
        return (0);
625 18446744073709551614
}
626
627
/*--------------------------------------------------------------------
628
 *
629
 */
630
631
int
632
VTCP_read(int fd, void *ptr, size_t len, vtim_dur tmo)
633 10382
{
634 10382
        struct pollfd pfd[1];
635 10382
        int i, j;
636
637 10382
        if (tmo > 0.0) {
638 10302
                pfd[0].fd = fd;
639 10302
                pfd[0].events = POLLIN;
640 10302
                pfd[0].revents = 0;
641 10302
                j = poll(pfd, 1, VTIM_poll_tmo(tmo));
642 10302
                if (j == 0)
643 292
                        return (-2);
644 10302
        }
645 10090
        i = read(fd, ptr, len);
646 10090
        VTCP_Assert(i);
647 10090
        return (i < 0 ? -1 : i);
648 10090
}