2 * Copyright (C) 2005-2009 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file net.c Networking-related helper functions. */
10 * Since glibc 2.8, the _GNU_SOURCE feature test macro must be defined in order
11 * to obtain the definition of the ucred structure.
17 /* At least NetBSD needs these. */
25 #define AI_ADDRCONFIG 0
30 #include <openssl/rc4.h>
40 * Parse and validate IPv4 address/netmask string.
42 * \param cidr Address in CIDR notation
43 * \param addr Copy of the IPv4 address part of \a cidr
44 * \param addrlen Size of \a addr in bytes
45 * \param netmask Value of the netmask part in \a cidr or the
46 * default of 32 if not specified.
48 * \return Pointer to \a addr if succesful, NULL on error.
51 char *parse_cidr(const char *cidr,
52 char *addr, ssize_t addrlen,
56 char *c = addr, *end = c + (addrlen - 1);
60 if (cidr == NULL || addrlen < 1)
63 for (o = cidr; (*c = *o == '/'? '\0' : *o); c++, o++)
68 if (para_atoi32(++o, netmask) < 0 ||
69 *netmask < 0 || *netmask > 0x20)
72 if (is_valid_ipv4_address(addr))
81 * Match string as a candidate IPv4 address.
83 * \param address The string to match.
84 * \return True if \a address has "dot-quad" format.
86 static bool is_v4_dot_quad(const char *address)
91 assert(para_regcomp(&r, "^([0-9]+\\.){3}[0-9]+$",
92 REG_EXTENDED | REG_NOSUB) >= 0);
93 result = regexec(&r, address, 0, NULL, 0) == 0;
99 * Perform basic syntax checking on the host-part of an URL:
101 * - Since ':' is invalid in IPv4 addresses and DNS names, the
102 * presence of ':' causes interpretation as IPv6 address;
103 * - next the first-match-wins algorithm from RFC 3986 is applied;
104 * - else the string is considered as DNS name, to be resolved later.
106 * \param host The host string to check.
107 * \return True if \a host passes the syntax checks.
109 * \sa RFC 3986, 3.2.2; RFC 1123, 2.1; RFC 1034, 3.5
111 static bool host_string_ok(const char *host)
113 if (host == NULL || *host == '\0')
115 if (strchr(host, ':') != NULL)
116 return is_valid_ipv6_address(host);
117 if (is_v4_dot_quad(host))
118 return is_valid_ipv4_address(host);
123 * Parse and validate URL string.
125 * The URL syntax is loosely based on RFC 3986, supporting one of
126 * - "["host"]"[:port] for native IPv6 addresses and
127 * - host[:port] for IPv4 hostnames and DNS names.
129 * Native IPv6 addresses must be enclosed in square brackets, since
130 * otherwise there is an ambiguity with the port separator `:'.
131 * The 'port' part is always considered to be a number; if absent,
132 * it is set to -1, to indicate that a default port is to be used.
134 * The following are valid examples:
142 * \param url The URL string to take apart.
143 * \param host To return the copied host part of \a url.
144 * \param hostlen The maximum length of \a host.
145 * \param port To return the port number (if any) of \a url.
147 * \return Pointer to \a host, or NULL if failed.
148 * If NULL is returned, \a host and \a portnum are undefined. If no
149 * port number was present in \a url, \a portnum is set to -1.
151 * \sa RFC 3986, 3.2.2/3.2.3
153 char *parse_url(const char *url,
154 char *host, ssize_t hostlen,
158 char *c = host, *end = c + (hostlen - 1);
162 if (o == NULL || hostlen < 1)
166 for (++o; (*c = *o == ']' ? '\0' : *o); c++, o++)
170 if (*o++ != ']' || (*o != '\0' && *o != ':'))
173 for (; (*c = *o == ':'? '\0' : *o); c++, o++)
179 if (para_atoi32(++o, port) < 0 ||
180 *port < 0 || *port > 0xffff)
183 if (host_string_ok(host))
191 * Determine the socket type for a given layer-4 protocol.
193 * \param l4type The symbolic name of the transport-layer protocol.
195 * \sa ip(7), socket(2)
197 static inline int sock_type(const unsigned l4type)
200 case IPPROTO_UDP: return SOCK_DGRAM;
201 case IPPROTO_TCP: return SOCK_STREAM;
202 case IPPROTO_DCCP: return SOCK_DCCP;
204 return -1; /* not supported here */
208 * Pretty-print transport-layer name.
210 static const char *layer4_name(const unsigned l4type)
213 case IPPROTO_UDP: return "UDP";
214 case IPPROTO_TCP: return "TCP";
215 case IPPROTO_DCCP: return "DCCP";
217 return "UNKNOWN PROTOCOL";
221 * Resolve IPv4/IPv6 address and create a ready-to-use active or passive socket.
223 * \param l3type The layer-3 type (\p AF_INET, \p AF_INET6, \p AF_UNSPEC).
224 * \param l4type The layer-4 type (\p IPPROTO_xxx).
225 * \param passive Whether this is a passive (1) or active (0) socket.
226 * \param host Remote or local hostname or IPv/6 address string.
227 * \param port_number Decimal port number.
229 * This creates a ready-made IPv4/v6 socket structure after looking up the
230 * necessary parameters. The interpretation of \a host depends on the value of
232 * - on a passive socket host is interpreted as an interface IPv4/6 address
233 * (can be left NULL);
234 * - on an active socket, \a host is the peer DNS name or IPv4/6 address
236 * - \a port_number is in either case the numeric port number (not service
239 * Furthermore, bind(2) is called on passive sockets, and connect(2) on active
240 * sockets. The algorithm tries all possible address combinations until it
243 * \return This function returns 1 on success and \a -E_ADDRESS_LOOKUP when no
244 * matching connection could be set up (with details in the error log).
246 * \sa ipv6(7), getaddrinfo(3), bind(2), connect(2).
248 int makesock(unsigned l3type, unsigned l4type, int passive,
249 const char *host, unsigned short port_number)
251 struct addrinfo *local = NULL, *src,
252 *remote = NULL, *dst, hints;
253 int rc, on = 1, sockfd = -1,
254 socktype = sock_type(l4type);
255 char port[6]; /* port number has at most 5 digits */
257 sprintf(port, "%u", port_number);
258 /* Set up address hint structure */
259 memset(&hints, 0, sizeof(hints));
260 hints.ai_family = l3type;
261 hints.ai_socktype = socktype;
263 * getaddrinfo does not support SOCK_DCCP, so for the sake of lookup
264 * (and only then) pretend to be UDP.
266 if (l4type == IPPROTO_DCCP)
267 hints.ai_socktype = SOCK_DGRAM;
269 /* only use addresses available on the host */
270 hints.ai_flags = AI_ADDRCONFIG;
271 if (l3type == AF_INET6)
272 /* use v4-mapped-v6 if no v6 addresses found */
273 hints.ai_flags |= AI_V4MAPPED | AI_ALL;
275 if (passive && host == NULL)
276 hints.ai_flags |= AI_PASSIVE;
278 /* Obtain local/remote address information */
279 if ((rc = getaddrinfo(host, port, &hints, passive ? &local : &remote))) {
280 PARA_ERROR_LOG("can not resolve %s address %s#%s: %s.\n",
282 host? host : (passive? "[loopback]" : "[localhost]"),
283 port, gai_strerror(rc));
284 return -E_ADDRESS_LOOKUP;
287 /* Iterate over all src/dst combination, exhausting dst first */
288 for (src = local, dst = remote; src != NULL || dst != NULL; /* no op */ ) {
289 if (src && dst && src->ai_family == AF_INET
290 && dst->ai_family == AF_INET6)
291 goto get_next_dst; /* v4 -> v6 is not possible */
293 sockfd = socket(src ? src->ai_family : dst->ai_family,
299 * Set those options that need to be set before establishing
300 * the connection. Reuse the address on passive (listening)
301 * sockets to avoid failure on restart.
303 if (passive && setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
304 &on, sizeof(on)) == -1) {
305 PARA_ERROR_LOG("can not set SO_REUSEADDR: %s\n",
307 return -ERRNO_TO_PARA_ERROR(errno);
311 if (bind(sockfd, src->ai_addr, src->ai_addrlen) < 0) {
315 if (!dst) /* bind-only completed successfully */
319 if (dst && connect(sockfd, dst->ai_addr, dst->ai_addrlen) == 0)
320 break; /* connection completed successfully */
323 if (dst && (dst = dst->ai_next))
326 if (src && (src = src->ai_next)) /* restart inner loop */
332 freeaddrinfo(remote);
334 if (src == NULL && dst == NULL) {
335 PARA_ERROR_LOG("can not create %s socket %s#%s.\n",
336 layer4_name(l4type), host? host : (passive?
337 "[loopback]" : "[localhost]"), port);
338 return -ERRNO_TO_PARA_ERROR(errno);
344 * Create a passive / listening socket.
346 * \param l3type The network-layer type (\p AF_xxx).
347 * \param l4type The transport-layer type (\p IPPROTO_xxx).
348 * \param port The decimal port number to listen on.
350 * \return Positive integer (socket descriptor) on success, negative value
353 * \sa makesock(), ip(7), ipv6(7), bind(2), listen(2).
355 int para_listen(unsigned l3type, unsigned l4type, unsigned short port)
357 int ret, fd = makesock(l3type, l4type, 1, NULL, port);
360 ret = listen(fd, BACKLOG);
363 return -ERRNO_TO_PARA_ERROR(errno);
365 PARA_INFO_LOG("listening on %s port %u, fd %d\n",
366 layer4_name(l4type), port, fd);
372 * Print numeric host and port number (beware - uses static char).
374 * \param sa The IPv4/IPv6 socket address to use.
375 * \param len The length of \p sa.
377 * \sa getnameinfo(3).
379 static char *host_and_port(struct sockaddr *sa, socklen_t len)
381 static char output[NI_MAXHOST + NI_MAXSERV + 2];
382 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
385 ret = getnameinfo(sa, len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
386 NI_NUMERICHOST | NI_NUMERICSERV);
388 PARA_WARNING_LOG("hostname lookup error (%s).\n",
390 sprintf(output, "(unknown)");
392 sprintf(output, "%s#%s", hbuf, sbuf);
397 * Look up the local or remote side of a connected socket structure.
399 * \param fd The socket descriptor of the connected socket.
400 * \param getname Either \p getsockname() for local, or \p getpeername() for
403 * \return A static character string identifying hostname and port of the
406 * \sa getsockname(2), getpeername(2).
408 static char *__get_sock_name(int fd, int (*getname)(int, struct sockaddr*,
411 struct sockaddr_storage ss;
412 socklen_t sslen = sizeof(ss);
414 if (getname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
415 static char *dont_know = "(don't know)";
416 PARA_ERROR_LOG("can not determine address from fd %d: %s\n",
417 fd, strerror(errno));
420 return host_and_port((struct sockaddr *)&ss, sslen);
424 * Look up the local side of a connected socket structure.
426 * \param sockfd The file descriptor of the socket.
428 * \return A pointer to a static buffer containing hostname an port. This
429 * buffer must not be freed by the caller.
433 char *local_name(int sockfd)
435 return __get_sock_name(sockfd, getsockname);
439 * Look up the remote side of a connected socket structure.
441 * \param sockfd The file descriptor of the socket.
443 * \return Analogous to the return value of \ref local_name() but for the
448 char *remote_name(int sockfd)
450 return __get_sock_name(sockfd, getpeername);
454 * Extract IPv4 or IPv6-mapped-IPv4 address from sockaddr_storage.
455 * \param ss Container of IPv4/6 address
456 * \return Extracted IPv4 address (different from 0) or 0 if unsuccessful.
460 struct in_addr extract_v4_addr(const struct sockaddr_storage *ss)
462 struct in_addr ia = {.s_addr = 0};
464 if (ss->ss_family == AF_INET)
465 ia.s_addr = ((struct sockaddr_in *)ss)->sin_addr.s_addr;
466 if (ss->ss_family == AF_INET6) {
467 const struct in6_addr v6_addr = ((struct sockaddr_in6 *)ss)->sin6_addr;
469 if (IN6_IS_ADDR_V4MAPPED(&v6_addr))
470 memcpy(&ia.s_addr, &(v6_addr.s6_addr[12]), 4);
476 * Send a binary buffer.
478 * \param fd The file descriptor.
479 * \param buf The buffer to be sent.
480 * \param len The length of \a buf.
482 * Send out the buffer and try to resend the remaining part in case of short
487 int send_bin_buffer(int fd, const char *buf, size_t len)
490 PARA_CRIT_LOG("len == 0\n");
491 return write_all(fd, buf, &len);
495 * Send a \p NULL-terminated buffer.
497 * \param fd The file descriptor.
498 * \param buf The null-terminated buffer to be send.
500 * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
504 int send_buffer(int fd, const char *buf)
506 return send_bin_buffer(fd, buf, strlen(buf));
510 * Send a buffer given by a format string.
512 * \param fd The file descriptor.
513 * \param fmt A format string.
517 __printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
522 PARA_VSPRINTF(fmt, msg);
523 ret = send_buffer(fd, msg);
529 * Receive data from a file descriptor.
531 * \param fd The file descriptor.
532 * \param buf The buffer to write the data to.
533 * \param size The size of \a buf.
535 * Receive at most \a size bytes from file descriptor \a fd.
537 * \return The number of bytes received on success, negative on errors, zero if
538 * the peer has performed an orderly shutdown.
542 __must_check int recv_bin_buffer(int fd, char *buf, size_t size)
546 n = recv(fd, buf, size, 0);
548 return -ERRNO_TO_PARA_ERROR(errno);
553 * Receive and write terminating NULL byte.
555 * \param fd The file descriptor.
556 * \param buf The buffer to write the data to.
557 * \param size The size of \a buf.
559 * Read at most \a size - 1 bytes from file descriptor \a fd and
560 * write a NULL byte at the end of the received data.
562 * \return The return value of the underlying call to \a recv_bin_buffer().
564 * \sa recv_bin_buffer()
566 int recv_buffer(int fd, char *buf, size_t size)
571 n = recv_bin_buffer(fd, buf, size - 1);
580 * Wrapper around the accept system call.
582 * \param fd The listening socket.
583 * \param addr Structure which is filled in with the address of the peer socket.
584 * \param size Should contain the size of the structure pointed to by \a addr.
586 * Accept incoming connections on \a addr. Retry if interrupted.
588 * \return The new file descriptor on success, negative on errors.
592 int para_accept(int fd, void *addr, socklen_t size)
597 new_fd = accept(fd, (struct sockaddr *) addr, &size);
598 while (new_fd < 0 && errno == EINTR);
599 return new_fd < 0? -ERRNO_TO_PARA_ERROR(errno) : new_fd;
603 * Prepare a structure for \p AF_UNIX socket addresses.
605 * \param u Pointer to the struct to be prepared.
606 * \param name The socket pathname.
608 * This just copies \a name to the sun_path component of \a u.
610 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
611 * than \p UNIX_PATH_MAX.
613 static int init_unix_addr(struct sockaddr_un *u, const char *name)
615 if (strlen(name) >= UNIX_PATH_MAX)
616 return -E_NAME_TOO_LONG;
617 memset(u->sun_path, 0, UNIX_PATH_MAX);
618 u->sun_family = PF_UNIX;
619 strcpy(u->sun_path, name);
624 * Prepare, create, and bind a socket for local communication.
626 * \param name The socket pathname.
627 * \param unix_addr Pointer to the \p AF_UNIX socket structure.
628 * \param mode The desired mode of the socket.
630 * This function creates a local socket for sequenced, reliable,
631 * two-way, connection-based byte streams.
633 * \return The file descriptor, on success, negative on errors.
639 int create_local_socket(const char *name, struct sockaddr_un *unix_addr,
644 ret = init_unix_addr(unix_addr, name);
647 ret = socket(PF_UNIX, SOCK_STREAM, 0);
649 return -ERRNO_TO_PARA_ERROR(errno);
651 ret = bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX);
653 ret = -ERRNO_TO_PARA_ERROR(errno);
657 if (chmod(name, mode) < 0)
666 * Prepare, create, and connect to a Unix domain socket for local communication.
668 * \param name The socket pathname.
670 * This function creates a local socket for sequenced, reliable, two-way,
671 * connection-based byte streams.
673 * \return The file descriptor, on success, negative on errors.
675 * \sa create_local_socket(), unix(7), connect(2).
677 int create_remote_socket(const char *name)
679 struct sockaddr_un unix_addr;
682 ret = init_unix_addr(&unix_addr, name);
685 fd = socket(PF_UNIX, SOCK_STREAM, 0);
687 return -ERRNO_TO_PARA_ERROR(errno);
688 if (connect(fd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) == -1) {
689 ret = -ERRNO_TO_PARA_ERROR(errno);
699 ssize_t send_cred_buffer(int sock, char *buf)
701 return send_buffer(sock, buf);
703 int recv_cred_buffer(int fd, char *buf, size_t size)
705 return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
707 #else /* HAVE_UCRED */
709 * Send \p NULL-terminated buffer and Unix credentials of the current process.
711 * \param sock The socket file descriptor.
712 * \param buf The buffer to be sent.
714 * \return On success, this call returns the number of characters sent. On
715 * error, \p -E_SENDMSG is returned.
717 * \sa sendmsg(2), okir's Black Hats Manual.
719 ssize_t send_cred_buffer(int sock, char *buf)
721 char control[sizeof(struct cmsghdr) + sizeof(struct ucred)];
723 struct cmsghdr *cmsg;
724 static struct iovec iov;
730 iov.iov_len = strlen(buf);
734 /* compose the message */
735 memset(&msg, 0, sizeof(msg));
738 msg.msg_control = control;
739 msg.msg_controllen = sizeof(control);
740 /* attach the ucred struct */
741 cmsg = CMSG_FIRSTHDR(&msg);
742 cmsg->cmsg_level = SOL_SOCKET;
743 cmsg->cmsg_type = SCM_CREDENTIALS;
744 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
745 *(struct ucred *)CMSG_DATA(cmsg) = c;
746 msg.msg_controllen = cmsg->cmsg_len;
747 ret = sendmsg(sock, &msg, 0);
753 static void dispose_fds(int *fds, unsigned num)
757 for (i = 0; i < num; i++)
762 * Receive a buffer and the Unix credentials of the sending process.
764 * \param fd the socket file descriptor.
765 * \param buf the buffer to store the message.
766 * \param size the size of \a buffer.
768 * \return negative on errors, the user id on success.
770 * \sa recvmsg(2), okir's Black Hats Manual.
772 int recv_cred_buffer(int fd, char *buf, size_t size)
776 struct cmsghdr *cmsg;
782 setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
783 memset(&msg, 0, sizeof(msg));
784 memset(buf, 0, size);
789 msg.msg_control = control;
790 msg.msg_controllen = sizeof(control);
791 if (recvmsg(fd, &msg, 0) < 0)
793 result = -E_SCM_CREDENTIALS;
794 cmsg = CMSG_FIRSTHDR(&msg);
796 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
797 == SCM_CREDENTIALS) {
798 memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
801 if (cmsg->cmsg_level == SOL_SOCKET
802 && cmsg->cmsg_type == SCM_RIGHTS) {
803 dispose_fds((int *) CMSG_DATA(cmsg),
804 (cmsg->cmsg_len - CMSG_LEN(0))
807 cmsg = CMSG_NXTHDR(&msg, cmsg);
811 #endif /* HAVE_UCRED */
814 * Receive a buffer and check for a pattern.
816 * \param fd The file descriptor to receive from.
817 * \param pattern The expected pattern.
818 * \param bufsize The size of the internal buffer.
820 * \return Positive if \a pattern was received, negative otherwise.
822 * This function tries to receive at most \a bufsize bytes from file descriptor
823 * \a fd. If at least \p strlen(\a pattern) bytes were received, the beginning
824 * of the received buffer is compared with \a pattern, ignoring case.
826 * \sa recv_buffer(), \sa strncasecmp(3).
828 int recv_pattern(int fd, const char *pattern, size_t bufsize)
830 size_t len = strlen(pattern);
831 char *buf = para_malloc(bufsize + 1);
832 int ret = -E_RECV_PATTERN, n = recv_buffer(fd, buf, bufsize + 1);
836 if (strncasecmp(buf, pattern, len))
841 PARA_NOTICE_LOG("did not receive pattern '%s'\n", pattern);
843 PARA_NOTICE_LOG("recvd %d bytes: %s\n", n, buf);
845 PARA_NOTICE_LOG("%s\n", para_strerror(-n));