2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2009-2010 The FreeBSD Foundation
5 * Copyright (c) 2011 Pawel Jakub Dawidek <pawel@dawidek.net>
8 * This software was developed by Pawel Jakub Dawidek under sponsorship from
9 * the FreeBSD Foundation.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 #include <sys/param.h> /* MAXHOSTNAMELEN */
34 #include <sys/socket.h>
36 #include <arpa/inet.h>
38 #include <netinet/in.h>
39 #include <netinet/tcp.h>
51 #include "proto_impl.h"
54 #define TCP_CTX_MAGIC 0x7c41c
57 struct sockaddr_storage tc_sa;
60 #define TCP_SIDE_CLIENT 0
61 #define TCP_SIDE_SERVER_LISTEN 1
62 #define TCP_SIDE_SERVER_WORK 2
65 static int tcp_connect_wait(void *ctx, int timeout);
66 static void tcp_close(void *ctx);
69 * Function converts the given string to unsigned number.
72 numfromstr(const char *str, intmax_t minnum, intmax_t maxnum, intmax_t *nump)
77 goto invalid; /* Empty string. */
79 for (; *str != '\0'; str++) {
80 if (*str < '0' || *str > '9')
81 goto invalid; /* Non-digit character. */
83 if (num > num * 10 + digit)
84 goto invalid; /* Overflow. */
85 num = num * 10 + digit;
87 goto invalid; /* Too big. */
90 goto invalid; /* Too small. */
99 tcp_addr(const char *addr, int defport, struct sockaddr_storage *sap)
101 char iporhost[MAXHOSTNAMELEN], portstr[6];
102 struct addrinfo hints;
103 struct addrinfo *res;
112 bzero(&hints, sizeof(hints));
113 hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV;
114 hints.ai_family = PF_UNSPEC;
115 hints.ai_socktype = SOCK_STREAM;
116 hints.ai_protocol = IPPROTO_TCP;
118 if (strncasecmp(addr, "tcp4://", 7) == 0) {
120 hints.ai_family = PF_INET;
121 } else if (strncasecmp(addr, "tcp6://", 7) == 0) {
123 hints.ai_family = PF_INET6;
124 } else if (strncasecmp(addr, "tcp://", 6) == 0) {
128 * Because TCP is the default assume IP or host is given without
134 * Extract optional port.
135 * There are three cases to consider.
136 * 1. hostname with port, eg. freefall.freebsd.org:8457
137 * 2. IPv4 address with port, eg. 192.168.0.101:8457
138 * 3. IPv6 address with port, eg. [fe80::1]:8457
139 * We discover IPv6 address by checking for two colons and if port is
140 * given, the address has to start with [.
143 if (strchr(addr, ':') != strrchr(addr, ':')) {
145 pp = strrchr(addr, ':');
147 pp = strrchr(addr, ':');
150 /* Port not given, use the default. */
153 if (numfromstr(pp + 1, 1, 65535, &port) == -1)
156 (void)snprintf(portstr, sizeof(portstr), "%jd", (intmax_t)port);
157 /* Extract host name or IP address. */
159 size = sizeof(iporhost);
160 if (strlcpy(iporhost, addr, size) >= size)
161 return (ENAMETOOLONG);
162 } else if (addr[0] == '[' && pp[-1] == ']') {
163 size = (size_t)(pp - addr - 2 + 1);
164 if (size > sizeof(iporhost))
165 return (ENAMETOOLONG);
166 (void)strlcpy(iporhost, addr + 1, size);
168 size = (size_t)(pp - addr + 1);
169 if (size > sizeof(iporhost))
170 return (ENAMETOOLONG);
171 (void)strlcpy(iporhost, addr, size);
174 error = getaddrinfo(iporhost, portstr, &hints, &res);
176 pjdlog_debug(1, "getaddrinfo(%s, %s) failed: %s.", iporhost,
177 portstr, gai_strerror(error));
183 memcpy(sap, res->ai_addr, res->ai_addrlen);
191 tcp_setup_new(const char *addr, int side, void **ctxp)
193 struct tcp_ctx *tctx;
196 PJDLOG_ASSERT(addr != NULL);
197 PJDLOG_ASSERT(side == TCP_SIDE_CLIENT ||
198 side == TCP_SIDE_SERVER_LISTEN);
199 PJDLOG_ASSERT(ctxp != NULL);
201 tctx = malloc(sizeof(*tctx));
205 /* Parse given address. */
206 if ((ret = tcp_addr(addr, PROTO_TCP_DEFAULT_PORT, &tctx->tc_sa)) != 0) {
211 PJDLOG_ASSERT(tctx->tc_sa.ss_family != AF_UNSPEC);
213 tctx->tc_fd = socket(tctx->tc_sa.ss_family, SOCK_STREAM, 0);
214 if (tctx->tc_fd == -1) {
220 PJDLOG_ASSERT(tctx->tc_sa.ss_family != AF_UNSPEC);
222 /* Socket settings. */
224 if (setsockopt(tctx->tc_fd, IPPROTO_TCP, TCP_NODELAY, &nodelay,
225 sizeof(nodelay)) == -1) {
226 pjdlog_errno(LOG_WARNING, "Unable to set TCP_NOELAY");
229 tctx->tc_side = side;
230 tctx->tc_magic = TCP_CTX_MAGIC;
237 tcp_setup_wrap(int fd, int side, void **ctxp)
239 struct tcp_ctx *tctx;
241 PJDLOG_ASSERT(fd >= 0);
242 PJDLOG_ASSERT(side == TCP_SIDE_CLIENT ||
243 side == TCP_SIDE_SERVER_WORK);
244 PJDLOG_ASSERT(ctxp != NULL);
246 tctx = malloc(sizeof(*tctx));
251 tctx->tc_sa.ss_family = AF_UNSPEC;
252 tctx->tc_side = side;
253 tctx->tc_magic = TCP_CTX_MAGIC;
260 tcp_client(const char *srcaddr, const char *dstaddr, void **ctxp)
262 struct tcp_ctx *tctx;
263 struct sockaddr_storage sa;
266 ret = tcp_setup_new(dstaddr, TCP_SIDE_CLIENT, ctxp);
272 ret = tcp_addr(srcaddr, 0, &sa);
277 if (bind(tctx->tc_fd, (struct sockaddr *)&sa, sa.ss_len) == -1) {
286 tcp_connect(void *ctx, int timeout)
288 struct tcp_ctx *tctx = ctx;
291 PJDLOG_ASSERT(tctx != NULL);
292 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
293 PJDLOG_ASSERT(tctx->tc_side == TCP_SIDE_CLIENT);
294 PJDLOG_ASSERT(tctx->tc_fd >= 0);
295 PJDLOG_ASSERT(tctx->tc_sa.ss_family != AF_UNSPEC);
296 PJDLOG_ASSERT(timeout >= -1);
298 flags = fcntl(tctx->tc_fd, F_GETFL);
300 pjdlog_common(LOG_DEBUG, 1, errno, "fcntl(F_GETFL) failed");
304 * We make socket non-blocking so we can handle connection timeout
308 if (fcntl(tctx->tc_fd, F_SETFL, flags) == -1) {
309 pjdlog_common(LOG_DEBUG, 1, errno,
310 "fcntl(F_SETFL, O_NONBLOCK) failed");
314 if (connect(tctx->tc_fd, (struct sockaddr *)&tctx->tc_sa,
315 tctx->tc_sa.ss_len) == 0) {
321 if (errno != EINPROGRESS) {
323 pjdlog_common(LOG_DEBUG, 1, errno, "connect() failed");
328 return (tcp_connect_wait(ctx, timeout));
330 flags &= ~O_NONBLOCK;
331 if (fcntl(tctx->tc_fd, F_SETFL, flags) == -1) {
334 pjdlog_common(LOG_DEBUG, 1, errno,
335 "fcntl(F_SETFL, ~O_NONBLOCK) failed");
341 tcp_connect_wait(void *ctx, int timeout)
343 struct tcp_ctx *tctx = ctx;
347 int error, flags, ret;
349 PJDLOG_ASSERT(tctx != NULL);
350 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
351 PJDLOG_ASSERT(tctx->tc_side == TCP_SIDE_CLIENT);
352 PJDLOG_ASSERT(tctx->tc_fd >= 0);
353 PJDLOG_ASSERT(timeout >= 0);
359 FD_SET(tctx->tc_fd, &fdset);
360 ret = select(tctx->tc_fd + 1, NULL, &fdset, NULL, &tv);
364 } else if (ret == -1) {
368 pjdlog_common(LOG_DEBUG, 1, errno, "select() failed");
371 PJDLOG_ASSERT(ret > 0);
372 PJDLOG_ASSERT(FD_ISSET(tctx->tc_fd, &fdset));
373 esize = sizeof(error);
374 if (getsockopt(tctx->tc_fd, SOL_SOCKET, SO_ERROR, &error,
377 pjdlog_common(LOG_DEBUG, 1, errno,
378 "getsockopt(SO_ERROR) failed");
382 pjdlog_common(LOG_DEBUG, 1, error,
383 "getsockopt(SO_ERROR) returned error");
388 flags = fcntl(tctx->tc_fd, F_GETFL);
392 pjdlog_common(LOG_DEBUG, 1, errno, "fcntl(F_GETFL) failed");
395 flags &= ~O_NONBLOCK;
396 if (fcntl(tctx->tc_fd, F_SETFL, flags) == -1) {
399 pjdlog_common(LOG_DEBUG, 1, errno,
400 "fcntl(F_SETFL, ~O_NONBLOCK) failed");
406 tcp_server(const char *addr, void **ctxp)
408 struct tcp_ctx *tctx;
411 ret = tcp_setup_new(addr, TCP_SIDE_SERVER_LISTEN, ctxp);
418 /* Ignore failure. */
419 (void)setsockopt(tctx->tc_fd, SOL_SOCKET, SO_REUSEADDR, &val,
422 PJDLOG_ASSERT(tctx->tc_sa.ss_family != AF_UNSPEC);
424 if (bind(tctx->tc_fd, (struct sockaddr *)&tctx->tc_sa,
425 tctx->tc_sa.ss_len) == -1) {
430 if (listen(tctx->tc_fd, 8) == -1) {
440 tcp_accept(void *ctx, void **newctxp)
442 struct tcp_ctx *tctx = ctx;
443 struct tcp_ctx *newtctx;
447 PJDLOG_ASSERT(tctx != NULL);
448 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
449 PJDLOG_ASSERT(tctx->tc_side == TCP_SIDE_SERVER_LISTEN);
450 PJDLOG_ASSERT(tctx->tc_fd >= 0);
451 PJDLOG_ASSERT(tctx->tc_sa.ss_family != AF_UNSPEC);
453 newtctx = malloc(sizeof(*newtctx));
457 fromlen = tctx->tc_sa.ss_len;
458 newtctx->tc_fd = accept(tctx->tc_fd, (struct sockaddr *)&tctx->tc_sa,
460 if (newtctx->tc_fd == -1) {
466 newtctx->tc_side = TCP_SIDE_SERVER_WORK;
467 newtctx->tc_magic = TCP_CTX_MAGIC;
474 tcp_wrap(int fd, bool client, void **ctxp)
477 return (tcp_setup_wrap(fd,
478 client ? TCP_SIDE_CLIENT : TCP_SIDE_SERVER_WORK, ctxp));
482 tcp_send(void *ctx, const unsigned char *data, size_t size, int fd)
484 struct tcp_ctx *tctx = ctx;
486 PJDLOG_ASSERT(tctx != NULL);
487 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
488 PJDLOG_ASSERT(tctx->tc_fd >= 0);
489 PJDLOG_ASSERT(fd == -1);
491 return (proto_common_send(tctx->tc_fd, data, size, -1));
495 tcp_recv(void *ctx, unsigned char *data, size_t size, int *fdp)
497 struct tcp_ctx *tctx = ctx;
499 PJDLOG_ASSERT(tctx != NULL);
500 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
501 PJDLOG_ASSERT(tctx->tc_fd >= 0);
502 PJDLOG_ASSERT(fdp == NULL);
504 return (proto_common_recv(tctx->tc_fd, data, size, NULL));
508 tcp_descriptor(const void *ctx)
510 const struct tcp_ctx *tctx = ctx;
512 PJDLOG_ASSERT(tctx != NULL);
513 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
515 return (tctx->tc_fd);
519 tcp_address_match(const void *ctx, const char *addr)
521 const struct tcp_ctx *tctx = ctx;
522 struct sockaddr_storage sa1, sa2;
525 PJDLOG_ASSERT(tctx != NULL);
526 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
528 if (tcp_addr(addr, PROTO_TCP_DEFAULT_PORT, &sa1) != 0)
532 if (getpeername(tctx->tc_fd, (struct sockaddr *)&sa2, &salen) == -1)
535 if (sa1.ss_family != sa2.ss_family || sa1.ss_len != sa2.ss_len)
538 switch (sa1.ss_family) {
541 struct sockaddr_in *sin1, *sin2;
543 sin1 = (struct sockaddr_in *)&sa1;
544 sin2 = (struct sockaddr_in *)&sa2;
546 return (memcmp(&sin1->sin_addr, &sin2->sin_addr,
547 sizeof(sin1->sin_addr)) == 0);
551 struct sockaddr_in6 *sin1, *sin2;
553 sin1 = (struct sockaddr_in6 *)&sa1;
554 sin2 = (struct sockaddr_in6 *)&sa2;
556 return (memcmp(&sin1->sin6_addr, &sin2->sin6_addr,
557 sizeof(sin1->sin6_addr)) == 0);
565 tcp_local_address(const void *ctx, char *addr, size_t size)
567 const struct tcp_ctx *tctx = ctx;
568 struct sockaddr_storage sa;
571 PJDLOG_ASSERT(tctx != NULL);
572 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
575 if (getsockname(tctx->tc_fd, (struct sockaddr *)&sa, &salen) == -1) {
576 PJDLOG_VERIFY(strlcpy(addr, "N/A", size) < size);
579 PJDLOG_VERIFY(snprintf(addr, size, "tcp://%S", &sa) < (ssize_t)size);
583 tcp_remote_address(const void *ctx, char *addr, size_t size)
585 const struct tcp_ctx *tctx = ctx;
586 struct sockaddr_storage sa;
589 PJDLOG_ASSERT(tctx != NULL);
590 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
593 if (getpeername(tctx->tc_fd, (struct sockaddr *)&sa, &salen) == -1) {
594 PJDLOG_VERIFY(strlcpy(addr, "N/A", size) < size);
597 PJDLOG_VERIFY(snprintf(addr, size, "tcp://%S", &sa) < (ssize_t)size);
603 struct tcp_ctx *tctx = ctx;
605 PJDLOG_ASSERT(tctx != NULL);
606 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
608 if (tctx->tc_fd >= 0)
614 static struct proto tcp_proto = {
616 .prt_client = tcp_client,
617 .prt_connect = tcp_connect,
618 .prt_connect_wait = tcp_connect_wait,
619 .prt_server = tcp_server,
620 .prt_accept = tcp_accept,
621 .prt_wrap = tcp_wrap,
622 .prt_send = tcp_send,
623 .prt_recv = tcp_recv,
624 .prt_descriptor = tcp_descriptor,
625 .prt_address_match = tcp_address_match,
626 .prt_local_address = tcp_local_address,
627 .prt_remote_address = tcp_remote_address,
628 .prt_close = tcp_close
631 static __constructor void
635 proto_register(&tcp_proto, true);