2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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/cdefs.h>
34 __FBSDID("$FreeBSD$");
36 #include <sys/param.h> /* MAXHOSTNAMELEN */
37 #include <sys/socket.h>
39 #include <arpa/inet.h>
41 #include <netinet/in.h>
42 #include <netinet/tcp.h>
54 #include "proto_impl.h"
57 #define TCP_CTX_MAGIC 0x7c41c
60 struct sockaddr_storage tc_sa;
63 #define TCP_SIDE_CLIENT 0
64 #define TCP_SIDE_SERVER_LISTEN 1
65 #define TCP_SIDE_SERVER_WORK 2
68 static int tcp_connect_wait(void *ctx, int timeout);
69 static void tcp_close(void *ctx);
72 * Function converts the given string to unsigned number.
75 numfromstr(const char *str, intmax_t minnum, intmax_t maxnum, intmax_t *nump)
80 goto invalid; /* Empty string. */
82 for (; *str != '\0'; str++) {
83 if (*str < '0' || *str > '9')
84 goto invalid; /* Non-digit character. */
86 if (num > num * 10 + digit)
87 goto invalid; /* Overflow. */
88 num = num * 10 + digit;
90 goto invalid; /* Too big. */
93 goto invalid; /* Too small. */
102 tcp_addr(const char *addr, int defport, struct sockaddr_storage *sap)
104 char iporhost[MAXHOSTNAMELEN], portstr[6];
105 struct addrinfo hints;
106 struct addrinfo *res;
115 bzero(&hints, sizeof(hints));
116 hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV;
117 hints.ai_family = PF_UNSPEC;
118 hints.ai_socktype = SOCK_STREAM;
119 hints.ai_protocol = IPPROTO_TCP;
121 if (strncasecmp(addr, "tcp4://", 7) == 0) {
123 hints.ai_family = PF_INET;
124 } else if (strncasecmp(addr, "tcp6://", 7) == 0) {
126 hints.ai_family = PF_INET6;
127 } else if (strncasecmp(addr, "tcp://", 6) == 0) {
131 * Because TCP is the default assume IP or host is given without
137 * Extract optional port.
138 * There are three cases to consider.
139 * 1. hostname with port, eg. freefall.freebsd.org:8457
140 * 2. IPv4 address with port, eg. 192.168.0.101:8457
141 * 3. IPv6 address with port, eg. [fe80::1]:8457
142 * We discover IPv6 address by checking for two colons and if port is
143 * given, the address has to start with [.
146 if (strchr(addr, ':') != strrchr(addr, ':')) {
148 pp = strrchr(addr, ':');
150 pp = strrchr(addr, ':');
153 /* Port not given, use the default. */
156 if (numfromstr(pp + 1, 1, 65535, &port) == -1)
159 (void)snprintf(portstr, sizeof(portstr), "%jd", (intmax_t)port);
160 /* Extract host name or IP address. */
162 size = sizeof(iporhost);
163 if (strlcpy(iporhost, addr, size) >= size)
164 return (ENAMETOOLONG);
165 } else if (addr[0] == '[' && pp[-1] == ']') {
166 size = (size_t)(pp - addr - 2 + 1);
167 if (size > sizeof(iporhost))
168 return (ENAMETOOLONG);
169 (void)strlcpy(iporhost, addr + 1, size);
171 size = (size_t)(pp - addr + 1);
172 if (size > sizeof(iporhost))
173 return (ENAMETOOLONG);
174 (void)strlcpy(iporhost, addr, size);
177 error = getaddrinfo(iporhost, portstr, &hints, &res);
179 pjdlog_debug(1, "getaddrinfo(%s, %s) failed: %s.", iporhost,
180 portstr, gai_strerror(error));
186 memcpy(sap, res->ai_addr, res->ai_addrlen);
194 tcp_setup_new(const char *addr, int side, void **ctxp)
196 struct tcp_ctx *tctx;
199 PJDLOG_ASSERT(addr != NULL);
200 PJDLOG_ASSERT(side == TCP_SIDE_CLIENT ||
201 side == TCP_SIDE_SERVER_LISTEN);
202 PJDLOG_ASSERT(ctxp != NULL);
204 tctx = malloc(sizeof(*tctx));
208 /* Parse given address. */
209 if ((ret = tcp_addr(addr, PROTO_TCP_DEFAULT_PORT, &tctx->tc_sa)) != 0) {
214 PJDLOG_ASSERT(tctx->tc_sa.ss_family != AF_UNSPEC);
216 tctx->tc_fd = socket(tctx->tc_sa.ss_family, SOCK_STREAM, 0);
217 if (tctx->tc_fd == -1) {
223 PJDLOG_ASSERT(tctx->tc_sa.ss_family != AF_UNSPEC);
225 /* Socket settings. */
227 if (setsockopt(tctx->tc_fd, IPPROTO_TCP, TCP_NODELAY, &nodelay,
228 sizeof(nodelay)) == -1) {
229 pjdlog_errno(LOG_WARNING, "Unable to set TCP_NOELAY");
232 tctx->tc_side = side;
233 tctx->tc_magic = TCP_CTX_MAGIC;
240 tcp_setup_wrap(int fd, int side, void **ctxp)
242 struct tcp_ctx *tctx;
244 PJDLOG_ASSERT(fd >= 0);
245 PJDLOG_ASSERT(side == TCP_SIDE_CLIENT ||
246 side == TCP_SIDE_SERVER_WORK);
247 PJDLOG_ASSERT(ctxp != NULL);
249 tctx = malloc(sizeof(*tctx));
254 tctx->tc_sa.ss_family = AF_UNSPEC;
255 tctx->tc_side = side;
256 tctx->tc_magic = TCP_CTX_MAGIC;
263 tcp_client(const char *srcaddr, const char *dstaddr, void **ctxp)
265 struct tcp_ctx *tctx;
266 struct sockaddr_storage sa;
269 ret = tcp_setup_new(dstaddr, TCP_SIDE_CLIENT, ctxp);
275 ret = tcp_addr(srcaddr, 0, &sa);
280 if (bind(tctx->tc_fd, (struct sockaddr *)&sa, sa.ss_len) == -1) {
289 tcp_connect(void *ctx, int timeout)
291 struct tcp_ctx *tctx = ctx;
294 PJDLOG_ASSERT(tctx != NULL);
295 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
296 PJDLOG_ASSERT(tctx->tc_side == TCP_SIDE_CLIENT);
297 PJDLOG_ASSERT(tctx->tc_fd >= 0);
298 PJDLOG_ASSERT(tctx->tc_sa.ss_family != AF_UNSPEC);
299 PJDLOG_ASSERT(timeout >= -1);
301 flags = fcntl(tctx->tc_fd, F_GETFL);
303 pjdlog_common(LOG_DEBUG, 1, errno, "fcntl(F_GETFL) failed");
307 * We make socket non-blocking so we can handle connection timeout
311 if (fcntl(tctx->tc_fd, F_SETFL, flags) == -1) {
312 pjdlog_common(LOG_DEBUG, 1, errno,
313 "fcntl(F_SETFL, O_NONBLOCK) failed");
317 if (connect(tctx->tc_fd, (struct sockaddr *)&tctx->tc_sa,
318 tctx->tc_sa.ss_len) == 0) {
324 if (errno != EINPROGRESS) {
326 pjdlog_common(LOG_DEBUG, 1, errno, "connect() failed");
331 return (tcp_connect_wait(ctx, timeout));
333 flags &= ~O_NONBLOCK;
334 if (fcntl(tctx->tc_fd, F_SETFL, flags) == -1) {
337 pjdlog_common(LOG_DEBUG, 1, errno,
338 "fcntl(F_SETFL, ~O_NONBLOCK) failed");
344 tcp_connect_wait(void *ctx, int timeout)
346 struct tcp_ctx *tctx = ctx;
350 int error, flags, ret;
352 PJDLOG_ASSERT(tctx != NULL);
353 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
354 PJDLOG_ASSERT(tctx->tc_side == TCP_SIDE_CLIENT);
355 PJDLOG_ASSERT(tctx->tc_fd >= 0);
356 PJDLOG_ASSERT(timeout >= 0);
362 FD_SET(tctx->tc_fd, &fdset);
363 ret = select(tctx->tc_fd + 1, NULL, &fdset, NULL, &tv);
367 } else if (ret == -1) {
371 pjdlog_common(LOG_DEBUG, 1, errno, "select() failed");
374 PJDLOG_ASSERT(ret > 0);
375 PJDLOG_ASSERT(FD_ISSET(tctx->tc_fd, &fdset));
376 esize = sizeof(error);
377 if (getsockopt(tctx->tc_fd, SOL_SOCKET, SO_ERROR, &error,
380 pjdlog_common(LOG_DEBUG, 1, errno,
381 "getsockopt(SO_ERROR) failed");
385 pjdlog_common(LOG_DEBUG, 1, error,
386 "getsockopt(SO_ERROR) returned error");
391 flags = fcntl(tctx->tc_fd, F_GETFL);
395 pjdlog_common(LOG_DEBUG, 1, errno, "fcntl(F_GETFL) failed");
398 flags &= ~O_NONBLOCK;
399 if (fcntl(tctx->tc_fd, F_SETFL, flags) == -1) {
402 pjdlog_common(LOG_DEBUG, 1, errno,
403 "fcntl(F_SETFL, ~O_NONBLOCK) failed");
409 tcp_server(const char *addr, void **ctxp)
411 struct tcp_ctx *tctx;
414 ret = tcp_setup_new(addr, TCP_SIDE_SERVER_LISTEN, ctxp);
421 /* Ignore failure. */
422 (void)setsockopt(tctx->tc_fd, SOL_SOCKET, SO_REUSEADDR, &val,
425 PJDLOG_ASSERT(tctx->tc_sa.ss_family != AF_UNSPEC);
427 if (bind(tctx->tc_fd, (struct sockaddr *)&tctx->tc_sa,
428 tctx->tc_sa.ss_len) == -1) {
433 if (listen(tctx->tc_fd, 8) == -1) {
443 tcp_accept(void *ctx, void **newctxp)
445 struct tcp_ctx *tctx = ctx;
446 struct tcp_ctx *newtctx;
450 PJDLOG_ASSERT(tctx != NULL);
451 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
452 PJDLOG_ASSERT(tctx->tc_side == TCP_SIDE_SERVER_LISTEN);
453 PJDLOG_ASSERT(tctx->tc_fd >= 0);
454 PJDLOG_ASSERT(tctx->tc_sa.ss_family != AF_UNSPEC);
456 newtctx = malloc(sizeof(*newtctx));
460 fromlen = tctx->tc_sa.ss_len;
461 newtctx->tc_fd = accept(tctx->tc_fd, (struct sockaddr *)&tctx->tc_sa,
463 if (newtctx->tc_fd == -1) {
469 newtctx->tc_side = TCP_SIDE_SERVER_WORK;
470 newtctx->tc_magic = TCP_CTX_MAGIC;
477 tcp_wrap(int fd, bool client, void **ctxp)
480 return (tcp_setup_wrap(fd,
481 client ? TCP_SIDE_CLIENT : TCP_SIDE_SERVER_WORK, ctxp));
485 tcp_send(void *ctx, const unsigned char *data, size_t size, int fd)
487 struct tcp_ctx *tctx = ctx;
489 PJDLOG_ASSERT(tctx != NULL);
490 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
491 PJDLOG_ASSERT(tctx->tc_fd >= 0);
492 PJDLOG_ASSERT(fd == -1);
494 return (proto_common_send(tctx->tc_fd, data, size, -1));
498 tcp_recv(void *ctx, unsigned char *data, size_t size, int *fdp)
500 struct tcp_ctx *tctx = ctx;
502 PJDLOG_ASSERT(tctx != NULL);
503 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
504 PJDLOG_ASSERT(tctx->tc_fd >= 0);
505 PJDLOG_ASSERT(fdp == NULL);
507 return (proto_common_recv(tctx->tc_fd, data, size, NULL));
511 tcp_descriptor(const void *ctx)
513 const struct tcp_ctx *tctx = ctx;
515 PJDLOG_ASSERT(tctx != NULL);
516 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
518 return (tctx->tc_fd);
522 tcp_address_match(const void *ctx, const char *addr)
524 const struct tcp_ctx *tctx = ctx;
525 struct sockaddr_storage sa1, sa2;
528 PJDLOG_ASSERT(tctx != NULL);
529 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
531 if (tcp_addr(addr, PROTO_TCP_DEFAULT_PORT, &sa1) != 0)
535 if (getpeername(tctx->tc_fd, (struct sockaddr *)&sa2, &salen) == -1)
538 if (sa1.ss_family != sa2.ss_family || sa1.ss_len != sa2.ss_len)
541 switch (sa1.ss_family) {
544 struct sockaddr_in *sin1, *sin2;
546 sin1 = (struct sockaddr_in *)&sa1;
547 sin2 = (struct sockaddr_in *)&sa2;
549 return (memcmp(&sin1->sin_addr, &sin2->sin_addr,
550 sizeof(sin1->sin_addr)) == 0);
554 struct sockaddr_in6 *sin1, *sin2;
556 sin1 = (struct sockaddr_in6 *)&sa1;
557 sin2 = (struct sockaddr_in6 *)&sa2;
559 return (memcmp(&sin1->sin6_addr, &sin2->sin6_addr,
560 sizeof(sin1->sin6_addr)) == 0);
568 tcp_local_address(const void *ctx, char *addr, size_t size)
570 const struct tcp_ctx *tctx = ctx;
571 struct sockaddr_storage sa;
574 PJDLOG_ASSERT(tctx != NULL);
575 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
578 if (getsockname(tctx->tc_fd, (struct sockaddr *)&sa, &salen) == -1) {
579 PJDLOG_VERIFY(strlcpy(addr, "N/A", size) < size);
582 PJDLOG_VERIFY(snprintf(addr, size, "tcp://%S", &sa) < (ssize_t)size);
586 tcp_remote_address(const void *ctx, char *addr, size_t size)
588 const struct tcp_ctx *tctx = ctx;
589 struct sockaddr_storage sa;
592 PJDLOG_ASSERT(tctx != NULL);
593 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
596 if (getpeername(tctx->tc_fd, (struct sockaddr *)&sa, &salen) == -1) {
597 PJDLOG_VERIFY(strlcpy(addr, "N/A", size) < size);
600 PJDLOG_VERIFY(snprintf(addr, size, "tcp://%S", &sa) < (ssize_t)size);
606 struct tcp_ctx *tctx = ctx;
608 PJDLOG_ASSERT(tctx != NULL);
609 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
611 if (tctx->tc_fd >= 0)
617 static struct proto tcp_proto = {
619 .prt_client = tcp_client,
620 .prt_connect = tcp_connect,
621 .prt_connect_wait = tcp_connect_wait,
622 .prt_server = tcp_server,
623 .prt_accept = tcp_accept,
624 .prt_wrap = tcp_wrap,
625 .prt_send = tcp_send,
626 .prt_recv = tcp_recv,
627 .prt_descriptor = tcp_descriptor,
628 .prt_address_match = tcp_address_match,
629 .prt_local_address = tcp_local_address,
630 .prt_remote_address = tcp_remote_address,
631 .prt_close = tcp_close
634 static __constructor void
638 proto_register(&tcp_proto, true);