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 * Match string as a candidate IPv4 address.
42 * \param address The string to match.
43 * \return True if \a address has "dot-quad" format.
45 static bool is_v4_dot_quad(const char *address)
50 assert(!regcomp(&r, "^([0-9]+\\.){3}[0-9]+$", REG_EXTENDED|REG_NOSUB));
51 result = regexec(&r, address, 0, NULL, 0) == 0;
57 * Perform basic syntax checking on the host-part of an URL:
59 * - Since ':' is invalid in IPv4 addresses and DNS names, the
60 * presence of ':' causes interpretation as IPv6 address;
61 * - next the first-match-wins algorithm from RFC 3986 is applied;
62 * - else the string is considered as DNS name, to be resolved later.
64 * \param host The host string to check.
65 * \return True if \a host passes the syntax checks.
67 * \sa RFC 3986, 3.2.2; RFC 1123, 2.1; RFC 1034, 3.5
69 static bool host_string_ok(const char *host)
71 if (host == NULL || *host == '\0')
73 if (strchr(host, ':') != NULL)
74 return is_valid_ipv6_address(host);
75 if (is_v4_dot_quad(host))
76 return is_valid_ipv4_address(host);
81 * Parse and validate URL string.
83 * The URL syntax is loosely based on RFC 3986, supporting one of
84 * - "["host"]"[:port] for native IPv6 addresses and
85 * - host[:port] for IPv4 hostnames and DNS names.
87 * Native IPv6 addresses must be enclosed in square brackets, since
88 * otherwise there is an ambiguity with the port separator `:'.
89 * The 'port' part is always considered to be a number; if absent,
90 * it is set to -1, to indicate that a default port is to be used.
92 * The following are valid examples:
100 * \param url The URL string to take apart.
101 * \param host To return the copied host part of \a url.
102 * \param hostlen The maximum length of \a host.
103 * \param port To return the port number (if any) of \a url.
105 * \return Pointer to \a host, or NULL if failed.
106 * If NULL is returned, \a host and \a portnum are undefined. If no
107 * port number was present in \a url, \a portnum is set to -1.
109 * \sa RFC 3986, 3.2.2/3.2.3
111 char *parse_url(const char *url,
112 char *host, ssize_t hostlen,
116 char *c = host, *end = c + (hostlen - 1);
120 if (o == NULL || hostlen < 1)
124 for (++o; (*c = *o == ']' ? '\0' : *o); c++, o++)
128 if (*o++ != ']' || (*o != '\0' && *o != ':'))
131 for (; (*c = *o == ':'? '\0' : *o); c++, o++)
137 if (para_atoi32(++o, port) < 0 ||
138 *port < 0 || *port > 0xffff)
141 if (host_string_ok(host))
149 * Determine the socket type for a given layer-4 protocol.
151 * \param l4type The symbolic name of the transport-layer protocol.
153 * \sa ip(7), socket(2)
155 static inline int sock_type(const unsigned l4type)
158 case IPPROTO_UDP: return SOCK_DGRAM;
159 case IPPROTO_TCP: return SOCK_STREAM;
160 case IPPROTO_DCCP: return SOCK_DCCP;
162 return -1; /* not supported here */
166 * Pretty-print transport-layer name.
168 static const char *layer4_name(const unsigned l4type)
171 case IPPROTO_UDP: return "UDP";
172 case IPPROTO_TCP: return "TCP";
173 case IPPROTO_DCCP: return "DCCP";
175 return "UNKNOWN PROTOCOL";
179 * Resolve IPv4/IPv6 address and create a ready-to-use active or passive socket.
181 * \param l3type The layer-3 type (\p AF_INET, \p AF_INET6, \p AF_UNSPEC).
182 * \param l4type The layer-4 type (\p IPPROTO_xxx).
183 * \param passive Whether this is a passive (1) or active (0) socket.
184 * \param host Remote or local hostname or IPv/6 address string.
185 * \param port_number Decimal port number.
187 * This creates a ready-made IPv4/v6 socket structure after looking up the
188 * necessary parameters. The interpretation of \a host depends on the value of
190 * - on a passive socket host is interpreted as an interface IPv4/6 address
191 * (can be left NULL);
192 * - on an active socket, \a host is the peer DNS name or IPv4/6 address
194 * - \a port_number is in either case the numeric port number (not service
197 * Furthermore, bind(2) is called on passive sockets, and connect(2) on active
198 * sockets. The algorithm tries all possible address combinations until it
201 * \return This function returns 1 on success and \a -E_ADDRESS_LOOKUP when no
202 * matching connection could be set up (with details in the error log).
204 * \sa ipv6(7), getaddrinfo(3), bind(2), connect(2).
206 int makesock(unsigned l3type, unsigned l4type, int passive,
207 const char *host, unsigned short port_number)
209 struct addrinfo *local = NULL, *src,
210 *remote = NULL, *dst, hints;
211 int rc, on = 1, sockfd = -1,
212 socktype = sock_type(l4type);
213 char port[6]; /* port number has at most 5 digits */
215 sprintf(port, "%u", port_number);
216 /* Set up address hint structure */
217 memset(&hints, 0, sizeof(hints));
218 hints.ai_family = l3type;
219 hints.ai_socktype = socktype;
221 * getaddrinfo does not support SOCK_DCCP, so for the sake of lookup
222 * (and only then) pretend to be UDP.
224 if (l4type == IPPROTO_DCCP)
225 hints.ai_socktype = SOCK_DGRAM;
227 /* only use addresses available on the host */
228 hints.ai_flags = AI_ADDRCONFIG;
229 if (l3type == AF_INET6)
230 /* use v4-mapped-v6 if no v6 addresses found */
231 hints.ai_flags |= AI_V4MAPPED | AI_ALL;
233 if (passive && host == NULL)
234 hints.ai_flags |= AI_PASSIVE;
236 /* Obtain local/remote address information */
237 if ((rc = getaddrinfo(host, port, &hints, passive ? &local : &remote))) {
238 PARA_ERROR_LOG("can not resolve %s address %s#%s: %s.\n",
240 host? host : (passive? "[loopback]" : "[localhost]"),
241 port, gai_strerror(rc));
242 return -E_ADDRESS_LOOKUP;
245 /* Iterate over all src/dst combination, exhausting dst first */
246 for (src = local, dst = remote; src != NULL || dst != NULL; /* no op */ ) {
247 if (src && dst && src->ai_family == AF_INET
248 && dst->ai_family == AF_INET6)
249 goto get_next_dst; /* v4 -> v6 is not possible */
251 sockfd = socket(src ? src->ai_family : dst->ai_family,
257 * Set those options that need to be set before establishing
258 * the connection. Reuse the address on passive (listening)
259 * sockets to avoid failure on restart.
261 if (passive && setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
262 &on, sizeof(on)) == -1) {
263 PARA_ERROR_LOG("can not set SO_REUSEADDR: %s\n",
265 return -ERRNO_TO_PARA_ERROR(errno);
269 if (bind(sockfd, src->ai_addr, src->ai_addrlen) < 0) {
273 if (!dst) /* bind-only completed successfully */
277 if (dst && connect(sockfd, dst->ai_addr, dst->ai_addrlen) == 0)
278 break; /* connection completed successfully */
281 if (dst && (dst = dst->ai_next))
284 if (src && (src = src->ai_next)) /* restart inner loop */
290 freeaddrinfo(remote);
292 if (src == NULL && dst == NULL) {
293 PARA_ERROR_LOG("can not create %s socket %s#%s.\n",
294 layer4_name(l4type), host? host : (passive?
295 "[loopback]" : "[localhost]"), port);
296 return -ERRNO_TO_PARA_ERROR(errno);
302 * Create a passive / listening socket.
304 * \param l3type The network-layer type (\p AF_xxx).
305 * \param l4type The transport-layer type (\p IPPROTO_xxx).
306 * \param port The decimal port number to listen on.
308 * \return Positive integer (socket descriptor) on success, negative value
311 * \sa makesock(), ip(7), ipv6(7), bind(2), listen(2).
313 int para_listen(unsigned l3type, unsigned l4type, unsigned short port)
315 int ret, fd = makesock(l3type, l4type, 1, NULL, port);
318 ret = listen(fd, BACKLOG);
321 return -ERRNO_TO_PARA_ERROR(errno);
323 PARA_INFO_LOG("listening on %s port %u, fd %d\n",
324 layer4_name(l4type), port, fd);
330 * Print numeric host and port number (beware - uses static char).
332 * \param sa The IPv4/IPv6 socket address to use.
333 * \param len The length of \p sa.
335 * \sa getnameinfo(3).
337 static char *host_and_port(struct sockaddr *sa, socklen_t len)
339 static char output[NI_MAXHOST + NI_MAXSERV + 2];
340 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
343 ret = getnameinfo(sa, len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
344 NI_NUMERICHOST | NI_NUMERICSERV);
346 PARA_WARNING_LOG("hostname lookup error (%s).\n",
348 sprintf(output, "(unknown)");
350 sprintf(output, "%s#%s", hbuf, sbuf);
355 * Look up the local or remote side of a connected socket structure.
357 * \param fd The socket descriptor of the connected socket.
358 * \param getname Either \p getsockname() for local, or \p getpeername() for
361 * \return A static character string identifying hostname and port of the
364 * \sa getsockname(2), getpeername(2).
366 static char *__get_sock_name(int fd, int (*getname)(int, struct sockaddr*,
369 struct sockaddr_storage ss;
370 socklen_t sslen = sizeof(ss);
372 if (getname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
373 static char *dont_know = "(don't know)";
374 PARA_ERROR_LOG("can not determine address from fd %d: %s\n",
375 fd, strerror(errno));
378 return host_and_port((struct sockaddr *)&ss, sslen);
382 * Look up the local side of a connected socket structure.
384 * \param sockfd The file descriptor of the socket.
386 * \return A pointer to a static buffer containing hostname an port. This
387 * buffer must not be freed by the caller.
391 char *local_name(int sockfd)
393 return __get_sock_name(sockfd, getsockname);
397 * Look up the remote side of a connected socket structure.
399 * \param sockfd The file descriptor of the socket.
401 * \return Analogous to the return value of \ref local_name() but for the
406 char *remote_name(int sockfd)
408 return __get_sock_name(sockfd, getpeername);
412 * Extract IPv4 or IPv6-mapped-IPv4 address from sockaddr_storage.
413 * \param ss Container of IPv4/6 address
414 * \return Extracted IPv4 address (different from 0) or 0 if unsuccessful.
418 struct in_addr extract_v4_addr(const struct sockaddr_storage *ss)
420 struct in_addr ia = {.s_addr = 0};
422 if (ss->ss_family == AF_INET)
423 ia.s_addr = ((struct sockaddr_in *)ss)->sin_addr.s_addr;
424 if (ss->ss_family == AF_INET6) {
425 const struct in6_addr v6_addr = ((struct sockaddr_in6 *)ss)->sin6_addr;
427 if (IN6_IS_ADDR_V4MAPPED(&v6_addr))
428 memcpy(&ia.s_addr, &(v6_addr.s6_addr[12]), 4);
434 * Send a binary buffer.
436 * \param fd The file descriptor.
437 * \param buf The buffer to be sent.
438 * \param len The length of \a buf.
440 * Send out the buffer and try to resend the remaining part in case of short
445 int send_bin_buffer(int fd, const char *buf, size_t len)
448 PARA_CRIT_LOG("len == 0\n");
449 return write_all(fd, buf, &len);
453 * Send a \p NULL-terminated buffer.
455 * \param fd The file descriptor.
456 * \param buf The null-terminated buffer to be send.
458 * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
462 int send_buffer(int fd, const char *buf)
464 return send_bin_buffer(fd, buf, strlen(buf));
468 * Send a buffer given by a format string.
470 * \param fd The file descriptor.
471 * \param fmt A format string.
475 __printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
480 PARA_VSPRINTF(fmt, msg);
481 ret = send_buffer(fd, msg);
487 * Receive data from a file descriptor.
489 * \param fd The file descriptor.
490 * \param buf The buffer to write the data to.
491 * \param size The size of \a buf.
493 * Receive at most \a size bytes from file descriptor \a fd.
495 * \return The number of bytes received on success, negative on errors, zero if
496 * the peer has performed an orderly shutdown.
500 __must_check int recv_bin_buffer(int fd, char *buf, size_t size)
504 n = recv(fd, buf, size, 0);
506 return -ERRNO_TO_PARA_ERROR(errno);
511 * Receive and write terminating NULL byte.
513 * \param fd The file descriptor.
514 * \param buf The buffer to write the data to.
515 * \param size The size of \a buf.
517 * Read at most \a size - 1 bytes from file descriptor \a fd and
518 * write a NULL byte at the end of the received data.
520 * \return The return value of the underlying call to \a recv_bin_buffer().
522 * \sa recv_bin_buffer()
524 int recv_buffer(int fd, char *buf, size_t size)
529 n = recv_bin_buffer(fd, buf, size - 1);
538 * Wrapper around the accept system call.
540 * \param fd The listening socket.
541 * \param addr Structure which is filled in with the address of the peer socket.
542 * \param size Should contain the size of the structure pointed to by \a addr.
544 * Accept incoming connections on \a addr. Retry if interrupted.
546 * \return The new file descriptor on success, negative on errors.
550 int para_accept(int fd, void *addr, socklen_t size)
555 new_fd = accept(fd, (struct sockaddr *) addr, &size);
556 while (new_fd < 0 && errno == EINTR);
557 return new_fd < 0? -ERRNO_TO_PARA_ERROR(errno) : new_fd;
561 * Prepare a structure for \p AF_UNIX socket addresses.
563 * \param u Pointer to the struct to be prepared.
564 * \param name The socket pathname.
566 * This just copies \a name to the sun_path component of \a u.
568 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
569 * than \p UNIX_PATH_MAX.
571 static int init_unix_addr(struct sockaddr_un *u, const char *name)
573 if (strlen(name) >= UNIX_PATH_MAX)
574 return -E_NAME_TOO_LONG;
575 memset(u->sun_path, 0, UNIX_PATH_MAX);
576 u->sun_family = PF_UNIX;
577 strcpy(u->sun_path, name);
582 * Prepare, create, and bind a socket for local communication.
584 * \param name The socket pathname.
585 * \param unix_addr Pointer to the \p AF_UNIX socket structure.
586 * \param mode The desired mode of the socket.
588 * This function creates a local socket for sequenced, reliable,
589 * two-way, connection-based byte streams.
591 * \return The file descriptor, on success, negative on errors.
597 int create_local_socket(const char *name, struct sockaddr_un *unix_addr,
602 ret = init_unix_addr(unix_addr, name);
605 ret = socket(PF_UNIX, SOCK_STREAM, 0);
607 return -ERRNO_TO_PARA_ERROR(errno);
609 ret = bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX);
611 ret = -ERRNO_TO_PARA_ERROR(errno);
615 if (chmod(name, mode) < 0)
624 * Prepare, create, and connect to a Unix domain socket for local communication.
626 * \param name The socket pathname.
628 * This function creates a local socket for sequenced, reliable, two-way,
629 * connection-based byte streams.
631 * \return The file descriptor, on success, negative on errors.
633 * \sa create_local_socket(), unix(7), connect(2).
635 int create_remote_socket(const char *name)
637 struct sockaddr_un unix_addr;
640 ret = init_unix_addr(&unix_addr, name);
643 fd = socket(PF_UNIX, SOCK_STREAM, 0);
645 return -ERRNO_TO_PARA_ERROR(errno);
646 if (connect(fd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) == -1) {
647 ret = -ERRNO_TO_PARA_ERROR(errno);
657 ssize_t send_cred_buffer(int sock, char *buf)
659 return send_buffer(sock, buf);
661 int recv_cred_buffer(int fd, char *buf, size_t size)
663 return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
665 #else /* HAVE_UCRED */
667 * Send \p NULL-terminated buffer and Unix credentials of the current process.
669 * \param sock The socket file descriptor.
670 * \param buf The buffer to be sent.
672 * \return On success, this call returns the number of characters sent. On
673 * error, \p -E_SENDMSG is returned.
675 * \sa sendmsg(2), okir's Black Hats Manual.
677 ssize_t send_cred_buffer(int sock, char *buf)
679 char control[sizeof(struct cmsghdr) + sizeof(struct ucred)];
681 struct cmsghdr *cmsg;
682 static struct iovec iov;
688 iov.iov_len = strlen(buf);
692 /* compose the message */
693 memset(&msg, 0, sizeof(msg));
696 msg.msg_control = control;
697 msg.msg_controllen = sizeof(control);
698 /* attach the ucred struct */
699 cmsg = CMSG_FIRSTHDR(&msg);
700 cmsg->cmsg_level = SOL_SOCKET;
701 cmsg->cmsg_type = SCM_CREDENTIALS;
702 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
703 *(struct ucred *)CMSG_DATA(cmsg) = c;
704 msg.msg_controllen = cmsg->cmsg_len;
705 ret = sendmsg(sock, &msg, 0);
711 static void dispose_fds(int *fds, unsigned num)
715 for (i = 0; i < num; i++)
720 * Receive a buffer and the Unix credentials of the sending process.
722 * \param fd the socket file descriptor.
723 * \param buf the buffer to store the message.
724 * \param size the size of \a buffer.
726 * \return negative on errors, the user id on success.
728 * \sa recvmsg(2), okir's Black Hats Manual.
730 int recv_cred_buffer(int fd, char *buf, size_t size)
734 struct cmsghdr *cmsg;
740 setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
741 memset(&msg, 0, sizeof(msg));
742 memset(buf, 0, size);
747 msg.msg_control = control;
748 msg.msg_controllen = sizeof(control);
749 if (recvmsg(fd, &msg, 0) < 0)
751 result = -E_SCM_CREDENTIALS;
752 cmsg = CMSG_FIRSTHDR(&msg);
754 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
755 == SCM_CREDENTIALS) {
756 memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
759 if (cmsg->cmsg_level == SOL_SOCKET
760 && cmsg->cmsg_type == SCM_RIGHTS) {
761 dispose_fds((int *) CMSG_DATA(cmsg),
762 (cmsg->cmsg_len - CMSG_LEN(0))
765 cmsg = CMSG_NXTHDR(&msg, cmsg);
769 #endif /* HAVE_UCRED */
772 * Receive a buffer and check for a pattern.
774 * \param fd The file descriptor to receive from.
775 * \param pattern The expected pattern.
776 * \param bufsize The size of the internal buffer.
778 * \return Positive if \a pattern was received, negative otherwise.
780 * This function tries to receive at most \a bufsize bytes from file descriptor
781 * \a fd. If at least \p strlen(\a pattern) bytes were received, the beginning
782 * of the received buffer is compared with \a pattern, ignoring case.
784 * \sa recv_buffer(), \sa strncasecmp(3).
786 int recv_pattern(int fd, const char *pattern, size_t bufsize)
788 size_t len = strlen(pattern);
789 char *buf = para_malloc(bufsize + 1);
790 int ret = -E_RECV_PATTERN, n = recv_buffer(fd, buf, bufsize + 1);
794 if (strncasecmp(buf, pattern, len))
799 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n,
802 PARA_NOTICE_LOG("recvd: %s\n", buf);