2 * Copyright (c) 2009-2010 The FreeBSD Foundation
3 * Copyright (c) 2011 Pawel Jakub Dawidek <pawel@dawidek.net>
6 * This software was developed by Pawel Jakub Dawidek under sponsorship from
7 * the FreeBSD Foundation.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 THE AUTHORS 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
30 * $P4: //depot/projects/trustedbsd/openbsm/bin/auditdistd/proto_tcp.c#2 $
33 #include <config/config.h>
35 #include <sys/param.h> /* MAXHOSTNAMELEN */
36 #include <sys/socket.h>
38 #include <arpa/inet.h>
40 #include <netinet/in.h>
41 #include <netinet/tcp.h>
54 #include <compat/strlcpy.h>
58 #include "proto_impl.h"
61 #define TCP_CTX_MAGIC 0x7c41c
64 struct sockaddr_storage tc_sa;
67 #define TCP_SIDE_CLIENT 0
68 #define TCP_SIDE_SERVER_LISTEN 1
69 #define TCP_SIDE_SERVER_WORK 2
73 static int tcp_connect_wait(void *ctx, int timeout);
74 static void tcp_close(void *ctx);
77 * Function converts the given string to unsigned number.
80 numfromstr(const char *str, intmax_t minnum, intmax_t maxnum, intmax_t *nump)
85 goto invalid; /* Empty string. */
87 for (; *str != '\0'; str++) {
88 if (*str < '0' || *str > '9')
89 goto invalid; /* Non-digit character. */
91 if (num > num * 10 + digit)
92 goto invalid; /* Overflow. */
93 num = num * 10 + digit;
95 goto invalid; /* Too big. */
98 goto invalid; /* Too small. */
107 tcp_addr(const char *addr, int defport, struct sockaddr_storage *sap)
109 char iporhost[MAXHOSTNAMELEN], portstr[6];
110 struct addrinfo hints;
111 struct addrinfo *res;
120 bzero(&hints, sizeof(hints));
121 hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV;
122 hints.ai_family = PF_UNSPEC;
123 hints.ai_socktype = SOCK_STREAM;
124 hints.ai_protocol = IPPROTO_TCP;
126 if (strncasecmp(addr, "tcp4://", 7) == 0) {
128 hints.ai_family = PF_INET;
129 } else if (strncasecmp(addr, "tcp6://", 7) == 0) {
131 hints.ai_family = PF_INET6;
132 } else if (strncasecmp(addr, "tcp://", 6) == 0) {
136 * Because TCP is the default assume IP or host is given without
142 * Extract optional port.
143 * There are three cases to consider.
144 * 1. hostname with port, eg. freefall.freebsd.org:8457
145 * 2. IPv4 address with port, eg. 192.168.0.101:8457
146 * 3. IPv6 address with port, eg. [fe80::1]:8457
147 * We discover IPv6 address by checking for two colons and if port is
148 * given, the address has to start with [.
151 if (strchr(addr, ':') != strrchr(addr, ':')) {
153 pp = strrchr(addr, ':');
155 pp = strrchr(addr, ':');
158 /* Port not given, use the default. */
161 if (numfromstr(pp + 1, 1, 65535, &port) < 0)
164 (void)snprintf(portstr, sizeof(portstr), "%jd", (intmax_t)port);
165 /* Extract host name or IP address. */
167 size = sizeof(iporhost);
168 if (strlcpy(iporhost, addr, size) >= size)
169 return (ENAMETOOLONG);
170 } else if (addr[0] == '[' && pp[-1] == ']') {
171 size = (size_t)(pp - addr - 2 + 1);
172 if (size > sizeof(iporhost))
173 return (ENAMETOOLONG);
174 (void)strlcpy(iporhost, addr + 1, size);
176 size = (size_t)(pp - addr + 1);
177 if (size > sizeof(iporhost))
178 return (ENAMETOOLONG);
179 (void)strlcpy(iporhost, addr, size);
182 error = getaddrinfo(iporhost, portstr, &hints, &res);
184 pjdlog_debug(1, "getaddrinfo(%s, %s) failed: %s.", iporhost,
185 portstr, gai_strerror(error));
191 memcpy(sap, res->ai_addr, res->ai_addrlen);
199 tcp_setup_new(const char *addr, int side, struct tcp_ctx **tctxp)
201 struct tcp_ctx *tctx;
204 PJDLOG_ASSERT(addr != NULL);
205 PJDLOG_ASSERT(side == TCP_SIDE_CLIENT ||
206 side == TCP_SIDE_SERVER_LISTEN);
207 PJDLOG_ASSERT(tctxp != NULL);
209 tctx = malloc(sizeof(*tctx));
213 /* Parse given address. */
214 error = tcp_addr(addr, atoi(proto_get("tcp:port")), &tctx->tc_sa);
220 PJDLOG_ASSERT(tctx->tc_sa.ss_family != AF_UNSPEC);
222 tctx->tc_fd = socket(tctx->tc_sa.ss_family, SOCK_STREAM, 0);
223 if (tctx->tc_fd == -1) {
229 PJDLOG_ASSERT(tctx->tc_sa.ss_family != AF_UNSPEC);
231 /* Socket settings. */
233 if (setsockopt(tctx->tc_fd, IPPROTO_TCP, TCP_NODELAY, &nodelay,
234 sizeof(nodelay)) == -1) {
235 pjdlog_errno(LOG_WARNING, "Unable to set TCP_NOELAY");
238 tctx->tc_wait_called = (side == TCP_SIDE_CLIENT ? false : true);
239 tctx->tc_side = side;
240 tctx->tc_magic = TCP_CTX_MAGIC;
247 sockaddr_len(const struct sockaddr_storage *ss)
250 #ifdef HAVE_SOCKADDR_STORAGE_SS_LEN
253 switch (ss->ss_family) {
255 return (sizeof(struct sockaddr_in));
257 return (sizeof(struct sockaddr_in6));
259 PJDLOG_ABORT("Unexpected family %hhu.", ss->ss_family);
265 tcp_connect(const char *srcaddr, const char *dstaddr, int timeout, void **ctxp)
267 struct tcp_ctx *tctx;
268 struct sockaddr_storage sa;
269 int error, flags, ret;
271 PJDLOG_ASSERT(srcaddr == NULL || srcaddr[0] != '\0');
272 PJDLOG_ASSERT(dstaddr != NULL);
273 PJDLOG_ASSERT(timeout >= -1);
275 error = tcp_setup_new(dstaddr, TCP_SIDE_CLIENT, &tctx);
278 if (srcaddr != NULL) {
279 error = tcp_addr(srcaddr, 0, &sa);
282 if (bind(tctx->tc_fd, (struct sockaddr *)&sa,
283 sockaddr_len(&sa)) == -1) {
289 flags = fcntl(tctx->tc_fd, F_GETFL);
292 pjdlog_common(LOG_DEBUG, 1, errno, "fcntl(F_GETFL) failed");
296 * We make socket non-blocking so we can handle connection timeout
300 if (fcntl(tctx->tc_fd, F_SETFL, flags) == -1) {
302 pjdlog_common(LOG_DEBUG, 1, errno,
303 "fcntl(F_SETFL, O_NONBLOCK) failed");
307 ret = connect(tctx->tc_fd, (struct sockaddr *)&tctx->tc_sa,
308 sockaddr_len(&tctx->tc_sa));
309 if (ret == -1 && errno != EINPROGRESS) {
311 pjdlog_common(LOG_DEBUG, 1, errno, "connect() failed");
317 /* Connection still in progress. Wait for it. */
318 error = tcp_connect_wait(tctx, timeout);
322 /* Connection already complete. */
323 flags &= ~O_NONBLOCK;
324 if (fcntl(tctx->tc_fd, F_SETFL, flags) == -1) {
326 pjdlog_common(LOG_DEBUG, 1, errno,
327 "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_wait_called);
353 PJDLOG_ASSERT(tctx->tc_fd >= 0);
354 PJDLOG_ASSERT(timeout >= 0);
360 FD_SET(tctx->tc_fd, &fdset);
361 ret = select(tctx->tc_fd + 1, NULL, &fdset, NULL, &tv);
365 } else if (ret == -1) {
369 pjdlog_common(LOG_DEBUG, 1, errno, "select() failed");
372 PJDLOG_ASSERT(ret > 0);
373 PJDLOG_ASSERT(FD_ISSET(tctx->tc_fd, &fdset));
374 esize = sizeof(error);
375 if (getsockopt(tctx->tc_fd, SOL_SOCKET, SO_ERROR, &error,
378 pjdlog_common(LOG_DEBUG, 1, errno,
379 "getsockopt(SO_ERROR) failed");
383 pjdlog_common(LOG_DEBUG, 1, error,
384 "getsockopt(SO_ERROR) returned error");
388 tctx->tc_wait_called = true;
390 flags = fcntl(tctx->tc_fd, F_GETFL);
394 pjdlog_common(LOG_DEBUG, 1, errno, "fcntl(F_GETFL) failed");
397 flags &= ~O_NONBLOCK;
398 if (fcntl(tctx->tc_fd, F_SETFL, flags) == -1) {
401 pjdlog_common(LOG_DEBUG, 1, errno,
402 "fcntl(F_SETFL, ~O_NONBLOCK) failed");
408 tcp_server(const char *addr, void **ctxp)
410 struct tcp_ctx *tctx;
413 error = tcp_setup_new(addr, TCP_SIDE_SERVER_LISTEN, &tctx);
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 sockaddr_len(&tctx->tc_sa)) == -1) {
430 if (listen(tctx->tc_fd, 8) == -1) {
442 tcp_accept(void *ctx, void **newctxp)
444 struct tcp_ctx *tctx = ctx;
445 struct tcp_ctx *newtctx;
449 PJDLOG_ASSERT(tctx != NULL);
450 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
451 PJDLOG_ASSERT(tctx->tc_side == TCP_SIDE_SERVER_LISTEN);
452 PJDLOG_ASSERT(tctx->tc_fd >= 0);
453 PJDLOG_ASSERT(tctx->tc_sa.ss_family != AF_UNSPEC);
455 newtctx = malloc(sizeof(*newtctx));
459 fromlen = sockaddr_len(&tctx->tc_sa);
460 newtctx->tc_fd = accept(tctx->tc_fd, (struct sockaddr *)&tctx->tc_sa,
462 if (newtctx->tc_fd < 0) {
468 newtctx->tc_wait_called = true;
469 newtctx->tc_side = TCP_SIDE_SERVER_WORK;
470 newtctx->tc_magic = TCP_CTX_MAGIC;
477 tcp_wrap(int fd, bool client, void **ctxp)
479 struct tcp_ctx *tctx;
481 PJDLOG_ASSERT(fd >= 0);
482 PJDLOG_ASSERT(ctxp != NULL);
484 tctx = malloc(sizeof(*tctx));
489 tctx->tc_sa.ss_family = AF_UNSPEC;
490 tctx->tc_wait_called = (client ? false : true);
491 tctx->tc_side = (client ? TCP_SIDE_CLIENT : TCP_SIDE_SERVER_WORK);
492 tctx->tc_magic = TCP_CTX_MAGIC;
499 tcp_send(void *ctx, const unsigned char *data, size_t size, int fd)
501 struct tcp_ctx *tctx = ctx;
503 PJDLOG_ASSERT(tctx != NULL);
504 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
505 PJDLOG_ASSERT(tctx->tc_side == TCP_SIDE_CLIENT ||
506 tctx->tc_side == TCP_SIDE_SERVER_WORK);
507 PJDLOG_ASSERT(tctx->tc_wait_called);
508 PJDLOG_ASSERT(tctx->tc_fd >= 0);
509 PJDLOG_ASSERT(fd == -1);
511 return (proto_common_send(tctx->tc_fd, data, size, -1));
515 tcp_recv(void *ctx, unsigned char *data, size_t size, int *fdp)
517 struct tcp_ctx *tctx = ctx;
519 PJDLOG_ASSERT(tctx != NULL);
520 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
521 PJDLOG_ASSERT(tctx->tc_side == TCP_SIDE_CLIENT ||
522 tctx->tc_side == TCP_SIDE_SERVER_WORK);
523 PJDLOG_ASSERT(tctx->tc_wait_called);
524 PJDLOG_ASSERT(tctx->tc_fd >= 0);
525 PJDLOG_ASSERT(fdp == NULL);
527 return (proto_common_recv(tctx->tc_fd, data, size, NULL));
531 tcp_descriptor(const void *ctx)
533 const struct tcp_ctx *tctx = ctx;
535 PJDLOG_ASSERT(tctx != NULL);
536 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
538 return (tctx->tc_fd);
542 tcp_address_match(const void *ctx, const char *addr)
544 const struct tcp_ctx *tctx = ctx;
545 struct sockaddr_storage sa1, sa2;
548 PJDLOG_ASSERT(tctx != NULL);
549 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
551 if (tcp_addr(addr, atoi(proto_get("tcp:port")), &sa1) != 0)
555 if (getpeername(tctx->tc_fd, (struct sockaddr *)&sa2, &salen) < 0)
558 if (sa1.ss_family != sa2.ss_family)
561 #ifdef HAVE_SOCKADDR_STORAGE_SS_LEN
562 if (sa1.ss_len != sa2.ss_len)
566 switch (sa1.ss_family) {
569 struct sockaddr_in *sin1, *sin2;
571 sin1 = (struct sockaddr_in *)&sa1;
572 sin2 = (struct sockaddr_in *)&sa2;
574 return (memcmp(&sin1->sin_addr, &sin2->sin_addr,
575 sizeof(sin1->sin_addr)) == 0);
579 struct sockaddr_in6 *sin1, *sin2;
581 sin1 = (struct sockaddr_in6 *)&sa1;
582 sin2 = (struct sockaddr_in6 *)&sa2;
584 return (memcmp(&sin1->sin6_addr, &sin2->sin6_addr,
585 sizeof(sin1->sin6_addr)) == 0);
594 sockaddr_to_string(const void *sa, char *buf, size_t size)
596 const struct sockaddr_storage *ss;
598 ss = (const struct sockaddr_storage * const *)sa;
599 switch (ss->ss_family) {
602 char addr[INET_ADDRSTRLEN];
603 const struct sockaddr_in *sin;
606 sin = (const struct sockaddr_in *)ss;
607 port = ntohs(sin->sin_port);
608 if (inet_ntop(ss->ss_family, &sin->sin_addr, addr,
609 sizeof(addr)) == NULL) {
610 PJDLOG_ABORT("inet_ntop(AF_INET) failed: %s.",
613 snprintf(buf, size, "%s:%u", addr, port);
618 char addr[INET6_ADDRSTRLEN];
619 const struct sockaddr_in6 *sin;
622 sin = (const struct sockaddr_in6 *)ss;
623 port = ntohs(sin->sin6_port);
624 if (inet_ntop(ss->ss_family, &sin->sin6_addr, addr,
625 sizeof(addr)) == NULL) {
626 PJDLOG_ABORT("inet_ntop(AF_INET6) failed: %s.",
629 snprintf(buf, size, "[%s]:%u", addr, port);
633 snprintf(buf, size, "[unsupported family %hhu]",
638 #endif /* !__FreeBSD__ */
641 tcp_local_address(const void *ctx, char *addr, size_t size)
643 const struct tcp_ctx *tctx = ctx;
644 struct sockaddr_storage sa;
647 PJDLOG_ASSERT(tctx != NULL);
648 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
651 if (getsockname(tctx->tc_fd, (struct sockaddr *)&sa, &salen) < 0) {
652 PJDLOG_VERIFY(strlcpy(addr, "N/A", size) < size);
656 PJDLOG_VERIFY(snprintf(addr, size, "tcp://%S", &sa) < (ssize_t)size);
658 strlcpy(addr, "tcp://", size);
660 sockaddr_to_string(&sa, addr + 6, size - 6);
665 tcp_remote_address(const void *ctx, char *addr, size_t size)
667 const struct tcp_ctx *tctx = ctx;
668 struct sockaddr_storage sa;
671 PJDLOG_ASSERT(tctx != NULL);
672 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
675 if (getpeername(tctx->tc_fd, (struct sockaddr *)&sa, &salen) < 0) {
676 PJDLOG_VERIFY(strlcpy(addr, "N/A", size) < size);
680 PJDLOG_VERIFY(snprintf(addr, size, "tcp://%S", &sa) < (ssize_t)size);
682 strlcpy(addr, "tcp://", size);
684 sockaddr_to_string(&sa, addr + 6, size - 6);
691 struct tcp_ctx *tctx = ctx;
693 PJDLOG_ASSERT(tctx != NULL);
694 PJDLOG_ASSERT(tctx->tc_magic == TCP_CTX_MAGIC);
696 if (tctx->tc_fd >= 0)
702 static struct proto tcp_proto = {
704 .prt_connect = tcp_connect,
705 .prt_connect_wait = tcp_connect_wait,
706 .prt_server = tcp_server,
707 .prt_accept = tcp_accept,
708 .prt_wrap = tcp_wrap,
709 .prt_send = tcp_send,
710 .prt_recv = tcp_recv,
711 .prt_descriptor = tcp_descriptor,
712 .prt_address_match = tcp_address_match,
713 .prt_local_address = tcp_local_address,
714 .prt_remote_address = tcp_remote_address,
715 .prt_close = tcp_close
718 static __constructor void
722 proto_register(&tcp_proto, true);