2 * Copyright (C) 2005-2011 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
39 * Parse and validate IPv4 address/netmask string.
41 * \param cidr Address in CIDR notation
42 * \param addr Copy of the IPv4 address part of \a cidr
43 * \param addrlen Size of \a addr in bytes
44 * \param netmask Value of the netmask part in \a cidr or the
45 * default of 32 if not specified.
47 * \return Pointer to \a addr if succesful, NULL on error.
50 char *parse_cidr(const char *cidr,
51 char *addr, ssize_t addrlen,
55 char *c = addr, *end = c + (addrlen - 1);
59 if (cidr == NULL || addrlen < 1)
62 for (o = cidr; (*c = *o == '/'? '\0' : *o); c++, o++)
67 if (para_atoi32(++o, netmask) < 0 ||
68 *netmask < 0 || *netmask > 0x20)
71 if (is_valid_ipv4_address(addr))
80 * Match string as a candidate IPv4 address.
82 * \param address The string to match.
83 * \return True if \a address has "dot-quad" format.
85 static bool is_v4_dot_quad(const char *address)
90 assert(para_regcomp(&r, "^([0-9]+\\.){3}[0-9]+$",
91 REG_EXTENDED | REG_NOSUB) >= 0);
92 result = regexec(&r, address, 0, NULL, 0) == 0;
98 * Perform basic syntax checking on the host-part of an URL:
100 * - Since ':' is invalid in IPv4 addresses and DNS names, the
101 * presence of ':' causes interpretation as IPv6 address;
102 * - next the first-match-wins algorithm from RFC 3986 is applied;
103 * - else the string is considered as DNS name, to be resolved later.
105 * \param host The host string to check.
106 * \return True if \a host passes the syntax checks.
108 * \sa RFC 3986, 3.2.2; RFC 1123, 2.1; RFC 1034, 3.5
110 static bool host_string_ok(const char *host)
112 if (host == NULL || *host == '\0')
114 if (strchr(host, ':') != NULL)
115 return is_valid_ipv6_address(host);
116 if (is_v4_dot_quad(host))
117 return is_valid_ipv4_address(host);
122 * Parse and validate URL string.
124 * The URL syntax is loosely based on RFC 3986, supporting one of
125 * - "["host"]"[:port] for native IPv6 addresses and
126 * - host[:port] for IPv4 hostnames and DNS names.
128 * Native IPv6 addresses must be enclosed in square brackets, since
129 * otherwise there is an ambiguity with the port separator `:'.
130 * The 'port' part is always considered to be a number; if absent,
131 * it is set to -1, to indicate that a default port is to be used.
133 * The following are valid examples:
141 * \param url The URL string to take apart.
142 * \param host To return the copied host part of \a url.
143 * \param hostlen The maximum length of \a host.
144 * \param port To return the port number (if any) of \a url.
146 * \return Pointer to \a host, or NULL if failed.
147 * If NULL is returned, \a host and \a portnum are undefined. If no
148 * port number was present in \a url, \a portnum is set to -1.
150 * \sa RFC 3986, 3.2.2/3.2.3
152 char *parse_url(const char *url,
153 char *host, ssize_t hostlen,
157 char *c = host, *end = c + (hostlen - 1);
161 if (o == NULL || hostlen < 1)
165 for (++o; (*c = *o == ']' ? '\0' : *o); c++, o++)
169 if (*o++ != ']' || (*o != '\0' && *o != ':'))
172 for (; (*c = *o == ':'? '\0' : *o); c++, o++)
178 if (para_atoi32(++o, port) < 0 ||
179 *port < 0 || *port > 0xffff)
182 if (host_string_ok(host))
190 * Stringify port number, resolve into service name where defined.
191 * \param port 2-byte port number, in host-byte-order.
192 * \param transport Transport protocol name (e.g. "udp", "tcp"), or NULL.
193 * \return Pointer to static result buffer.
195 * \sa getservent(3), services(5), nsswitch.conf(5)
197 const char *stringify_port(int port, const char *transport)
199 static char service[NI_MAXSERV];
201 if (port < 0 || port > 0xFFFF) {
202 snprintf(service, sizeof(service), "undefined (%d)", port);
204 struct servent *se = getservbyport(htons(port), transport);
207 snprintf(service, sizeof(service), "%u", port);
209 snprintf(service, sizeof(service), "%s", se->s_name);
215 * Determine the socket type for a given layer-4 protocol.
217 * \param l4type The symbolic name of the transport-layer protocol.
219 * \sa ip(7), socket(2)
221 static inline int sock_type(const unsigned l4type)
224 case IPPROTO_UDP: return SOCK_DGRAM;
225 case IPPROTO_TCP: return SOCK_STREAM;
226 case IPPROTO_DCCP: return SOCK_DCCP;
228 return -1; /* not supported here */
232 * Pretty-print transport-layer name.
234 static const char *layer4_name(const unsigned l4type)
237 case IPPROTO_UDP: return "UDP";
238 case IPPROTO_TCP: return "TCP";
239 case IPPROTO_DCCP: return "DCCP";
241 return "UNKNOWN PROTOCOL";
245 * Flowopts: Transport-layer independent encapsulation of socket options.
247 * These collect individual socket options into a queue, which is disposed of
248 * directly after makesock(). The 'pre_conn_opt' structure is for internal use
249 * only and should not be visible elsewhere.
251 * \sa setsockopt(2), makesock()
253 struct pre_conn_opt {
254 int sock_level; /**< Second argument to setsockopt() */
255 int sock_option; /**< Third argument to setsockopt() */
256 char *opt_name; /**< Stringified \a sock_option */
257 void *opt_val; /**< Fourth argument to setsockopt() */
258 socklen_t opt_len; /**< Fifth argument to setsockopt() */
260 struct list_head node; /**< FIFO, as sockopt order matters. */
263 /** FIFO list of pre-connection socket options to be set */
265 struct list_head sockopts;
268 struct flowopts *flowopt_new(void)
270 struct flowopts *new = para_malloc(sizeof(*new));
272 INIT_LIST_HEAD(&new->sockopts);
277 * Append new socket option to flowopt queue.
279 * \param fo The flowopt queue to append to.
280 * \param lev Level at which \a opt resides.
281 * \param opt New option to add.
282 * \param name Stringified name of \a opt.
283 * \param val The value to set \a opt to.
284 * \param len Length of \a val.
288 void flowopt_add(struct flowopts *fo, int lev, int opt,
289 char *name, const void *val, int len)
291 struct pre_conn_opt *new = para_malloc(sizeof(*new));
293 new->sock_option = opt;
294 new->sock_level = lev;
295 new->opt_name = para_strdup(name);
301 new->opt_val = para_malloc(len);
303 memcpy(new->opt_val, val, len);
306 list_add_tail(&new->node, &fo->sockopts);
309 void flowopt_add_bool(struct flowopts *fo, int lev, int opt,
310 char *optname, bool on_or_off)
312 int on = on_or_off; /* kernel takes 'int' */
314 flowopt_add(fo, lev, opt, optname, &on, sizeof(on));
317 /** Set the entire bunch of pre-connection options at once. */
318 static void flowopt_setopts(int sockfd, struct flowopts *fo)
320 struct pre_conn_opt *pc;
325 list_for_each_entry(pc, &fo->sockopts, node)
326 if (setsockopt(sockfd, pc->sock_level, pc->sock_option,
327 pc->opt_val, pc->opt_len) < 0) {
328 PARA_EMERG_LOG("Can not set %s socket option: %s",
329 pc->opt_name, strerror(errno));
334 static void flowopt_cleanup(struct flowopts *fo)
336 struct pre_conn_opt *cur, *next;
341 list_for_each_entry_safe(cur, next, &fo->sockopts, node) {
350 * Resolve IPv4/IPv6 address and create a ready-to-use active or passive socket.
352 * \param l4type The layer-4 type (\p IPPROTO_xxx).
353 * \param passive Whether this is a passive (1) or active (0) socket.
354 * \param host Remote or local hostname or IPv/6 address string.
355 * \param port_number Decimal port number.
356 * \param fo Socket options to be set before making the connection.
358 * This creates a ready-made IPv4/v6 socket structure after looking up the
359 * necessary parameters. The interpretation of \a host depends on the value of
361 * - on a passive socket host is interpreted as an interface IPv4/6 address
362 * (can be left NULL);
363 * - on an active socket, \a host is the peer DNS name or IPv4/6 address
365 * - \a port_number is in either case the numeric port number (not service
368 * Furthermore, bind(2) is called on passive sockets, and connect(2) on active
369 * sockets. The algorithm tries all possible address combinations until it
370 * succeeds. If \a fo is supplied, options are set and cleanup is performed.
372 * \return This function returns 1 on success and \a -E_ADDRESS_LOOKUP when no
373 * matching connection could be set up (with details in the error log).
375 * \sa ipv6(7), getaddrinfo(3), bind(2), connect(2).
377 int makesock(unsigned l4type, bool passive,
378 const char *host, uint16_t port_number,
381 struct addrinfo *local = NULL, *src = NULL, *remote = NULL,
383 unsigned int l3type = AF_UNSPEC;
384 int rc, on = 1, sockfd = -1,
385 socktype = sock_type(l4type);
386 char port[6]; /* port number has at most 5 digits */
388 sprintf(port, "%u", port_number);
389 /* Set up address hint structure */
390 memset(&hints, 0, sizeof(hints));
391 hints.ai_family = l3type;
392 hints.ai_socktype = socktype;
394 * getaddrinfo does not support SOCK_DCCP, so for the sake of lookup
395 * (and only then) pretend to be UDP.
397 if (l4type == IPPROTO_DCCP)
398 hints.ai_socktype = SOCK_DGRAM;
400 /* only use addresses available on the host */
401 hints.ai_flags = AI_ADDRCONFIG;
402 if (l3type == AF_INET6)
403 /* use v4-mapped-v6 if no v6 addresses found */
404 hints.ai_flags |= AI_V4MAPPED | AI_ALL;
406 if (passive && host == NULL)
407 hints.ai_flags |= AI_PASSIVE;
409 /* Obtain local/remote address information */
410 if ((rc = getaddrinfo(host, port, &hints, passive ? &local : &remote))) {
411 PARA_ERROR_LOG("can not resolve %s address %s#%s: %s.\n",
413 host? host : (passive? "[loopback]" : "[localhost]"),
414 port, gai_strerror(rc));
415 rc = -E_ADDRESS_LOOKUP;
419 /* Iterate over all src/dst combination, exhausting dst first */
420 for (src = local, dst = remote; src != NULL || dst != NULL; /* no op */ ) {
421 if (src && dst && src->ai_family == AF_INET
422 && dst->ai_family == AF_INET6)
423 goto get_next_dst; /* v4 -> v6 is not possible */
425 sockfd = socket(src ? src->ai_family : dst->ai_family,
431 * Reuse the address on passive sockets to avoid failure on
432 * restart (protocols using listen()) and when creating
433 * multiple listener instances (UDP multicast).
435 if (passive && setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
436 &on, sizeof(on)) == -1) {
439 PARA_ERROR_LOG("can not set SO_REUSEADDR: %s\n",
441 rc = -ERRNO_TO_PARA_ERROR(rc);
444 flowopt_setopts(sockfd, fo);
447 if (bind(sockfd, src->ai_addr, src->ai_addrlen) < 0) {
451 if (!dst) /* bind-only completed successfully */
455 if (dst && connect(sockfd, dst->ai_addr, dst->ai_addrlen) == 0)
456 break; /* connection completed successfully */
459 if (dst && (dst = dst->ai_next))
462 if (src && (src = src->ai_next)) /* restart inner loop */
469 freeaddrinfo(remote);
472 if (src == NULL && dst == NULL) {
475 PARA_ERROR_LOG("can not create %s socket %s#%s.\n",
476 layer4_name(l4type), host? host : (passive?
477 "[loopback]" : "[localhost]"), port);
484 * Create a passive / listening socket.
486 * \param l4type The transport-layer type (\p IPPROTO_xxx).
487 * \param port The decimal port number to listen on.
488 * \param fo Flowopts (if any) to set before starting to listen.
490 * \return Positive integer (socket descriptor) on success, negative value
493 * \sa makesock(), ip(7), ipv6(7), bind(2), listen(2).
495 int para_listen(unsigned l4type, uint16_t port, struct flowopts *fo)
497 int ret, fd = makesock(l4type, 1, NULL, port, fo);
500 ret = listen(fd, BACKLOG);
504 return -ERRNO_TO_PARA_ERROR(ret);
506 PARA_INFO_LOG("listening on %s port %u, fd %d\n",
507 layer4_name(l4type), port, fd);
513 * Determine IPv4/v6 socket address length.
514 * \param sa Container of IPv4 or IPv6 address.
515 * \return Address-family dependent address length.
517 static socklen_t salen(const struct sockaddr *sa)
519 assert(sa->sa_family == AF_INET || sa->sa_family == AF_INET6);
521 return sa->sa_family == AF_INET6
522 ? sizeof(struct sockaddr_in6)
523 : sizeof(struct sockaddr_in);
526 /** True if @ss holds a v6-mapped-v4 address (RFC 4291, 2.5.5.2) */
527 static bool SS_IS_ADDR_V4MAPPED(const struct sockaddr_storage *ss)
529 const struct sockaddr_in6 *ia6 = (const struct sockaddr_in6 *)ss;
531 return ss->ss_family == AF_INET6 && IN6_IS_ADDR_V4MAPPED(&ia6->sin6_addr);
535 * Process IPv4/v6 address, turn v6-mapped-v4 address into normal IPv4 address.
536 * \param ss Container of IPv4/6 address.
537 * \return Pointer to normalized address (may be static storage).
541 static const struct sockaddr *
542 normalize_ip_address(const struct sockaddr_storage *ss)
544 assert(ss->ss_family == AF_INET || ss->ss_family == AF_INET6);
546 if (SS_IS_ADDR_V4MAPPED(ss)) {
547 const struct sockaddr_in6 *ia6 = (const struct sockaddr_in6 *)ss;
548 static struct sockaddr_in ia;
550 ia.sin_family = AF_INET;
551 ia.sin_port = ia6->sin6_port;
552 memcpy(&ia.sin_addr.s_addr, &(ia6->sin6_addr.s6_addr[12]), 4);
553 return (const struct sockaddr *)&ia;
555 return (const struct sockaddr *)ss;
559 * Generic/fallback MTU values
561 * These are taken from RFC 1122, RFC 2460, and RFC 5405.
562 * - RFC 1122, 3.3.3 defines EMTU_S ("Effective MTU for sending") and recommends
563 * to use an EMTU_S size of of 576 bytes if the IPv4 path MTU is unknown;
564 * - RFC 2460, 5. requires a minimum IPv6 MTU of 1280 bytes;
565 * - RFC 5405, 3.2 recommends that if path MTU discovery is not done,
566 * UDP senders should use the respective minimum values of EMTU_S.
568 static inline int generic_mtu(const int af_type)
570 return af_type == AF_INET6 ? 1280 : 576;
573 /** Crude approximation of IP header overhead - neglecting options. */
574 static inline int estimated_header_overhead(const int af_type)
576 return af_type == AF_INET6 ? 40 : 20;
580 * Maximum transport-layer message size (MMS_S) as per RFC 1122, 3.3.3
581 * Socket must be connected.
583 int generic_max_transport_msg_size(int sockfd)
585 struct sockaddr_storage ss;
586 socklen_t sslen = sizeof(ss);
587 int af_type = AF_INET;
589 if (getpeername(sockfd, (struct sockaddr *)&ss, &sslen) < 0) {
590 PARA_ERROR_LOG("can not determine remote address type: %s\n",
592 } else if (!SS_IS_ADDR_V4MAPPED(&ss)) {
593 af_type = ss.ss_family;
595 return generic_mtu(af_type) - estimated_header_overhead(af_type);
599 * Print numeric host and port number (beware - uses static char).
601 * \param sa The IPv4/IPv6 socket address to use.
603 * \return Host string in numeric host:port format, \sa parse_url().
604 * \sa getnameinfo(3), services(5), nsswitch.conf(5)
606 static char *host_and_port(const struct sockaddr_storage *ss)
608 const struct sockaddr *sa = normalize_ip_address(ss);
609 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
610 static char output[sizeof(hbuf) + sizeof(sbuf) + 4];
613 ret = getnameinfo(sa, salen(sa),
616 NI_NUMERICHOST | NI_NUMERICSERV);
618 snprintf(output, sizeof(output), "(unknown)");
619 PARA_WARNING_LOG("hostname lookup error (%s).\n",
621 } else if (sa->sa_family == AF_INET6) {
622 snprintf(output, sizeof(output), "[%s]:%s", hbuf, sbuf);
624 snprintf(output, sizeof(output), "%s:%s", hbuf, sbuf);
630 * Look up the local or remote side of a connected socket structure.
632 * \param fd The socket descriptor of the connected socket.
633 * \param getname Either \p getsockname() for local, or \p getpeername() for
636 * \return A static character string identifying hostname and port of the
639 * \sa getsockname(2), getpeername(2).
641 static char *__get_sock_name(int fd, int (*getname)(int, struct sockaddr*,
644 struct sockaddr_storage ss;
645 socklen_t sslen = sizeof(ss);
647 if (getname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
648 static char *dont_know = "(don't know)";
649 PARA_ERROR_LOG("can not determine address from fd %d: %s\n",
650 fd, strerror(errno));
653 return host_and_port(&ss);
657 * Look up the local side of a connected socket structure.
659 * \param sockfd The file descriptor of the socket.
661 * \return A pointer to a static buffer containing hostname an port. This
662 * buffer must not be freed by the caller.
666 char *local_name(int sockfd)
668 return __get_sock_name(sockfd, getsockname);
672 * Look up the remote side of a connected socket structure.
674 * \param sockfd The file descriptor of the socket.
676 * \return Analogous to the return value of \ref local_name() but for the
681 char *remote_name(int sockfd)
683 return __get_sock_name(sockfd, getpeername);
687 * Extract IPv4 or IPv6-mapped-IPv4 address from sockaddr_storage.
688 * \param ss Container of IPv4/6 address
689 * \return Extracted IPv4 address (different from 0) or 0 if unsuccessful.
693 struct in_addr extract_v4_addr(const struct sockaddr_storage *ss)
695 struct in_addr ia = {.s_addr = 0};
696 const struct sockaddr *sa = normalize_ip_address(ss);
698 if (sa->sa_family == AF_INET)
699 ia = ((struct sockaddr_in *)sa)->sin_addr;
704 * Send a binary buffer.
706 * \param fd The file descriptor.
707 * \param buf The buffer to be sent.
708 * \param len The length of \a buf.
710 * Send out the buffer and try to resend the remaining part in case of short
715 int send_bin_buffer(int fd, const char *buf, size_t len)
718 PARA_CRIT_LOG("len == 0\n");
719 return write_all(fd, buf, &len);
723 * Send a \p NULL-terminated buffer.
725 * \param fd The file descriptor.
726 * \param buf The null-terminated buffer to be send.
728 * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
732 int send_buffer(int fd, const char *buf)
734 return send_bin_buffer(fd, buf, strlen(buf));
738 * Send a buffer given by a format string.
740 * \param fd The file descriptor.
741 * \param fmt A format string.
745 __printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
750 PARA_VSPRINTF(fmt, msg);
751 ret = send_buffer(fd, msg);
757 * Receive data from a file descriptor.
759 * \param fd The file descriptor.
760 * \param buf The buffer to write the data to.
761 * \param size The size of \a buf.
763 * Receive at most \a size bytes from file descriptor \a fd.
765 * \return The number of bytes received on success, negative on errors, zero if
766 * the peer has performed an orderly shutdown.
770 __must_check int recv_bin_buffer(int fd, char *buf, size_t size)
774 n = recv(fd, buf, size, 0);
776 return -ERRNO_TO_PARA_ERROR(errno);
781 * Receive and write terminating NULL byte.
783 * \param fd The file descriptor.
784 * \param buf The buffer to write the data to.
785 * \param size The size of \a buf.
787 * Read at most \a size - 1 bytes from file descriptor \a fd and
788 * write a NULL byte at the end of the received data.
790 * \return The return value of the underlying call to \a recv_bin_buffer().
792 * \sa recv_bin_buffer()
794 int recv_buffer(int fd, char *buf, size_t size)
799 n = recv_bin_buffer(fd, buf, size - 1);
808 * Wrapper around the accept system call.
810 * \param fd The listening socket.
811 * \param rfds An optional fd_set pointer.
812 * \param addr Structure which is filled in with the address of the peer socket.
813 * \param size Should contain the size of the structure pointed to by \a addr.
814 * \param new_fd Result pointer.
816 * Accept incoming connections on \a addr, retry if interrupted. If \a rfds is
817 * not \p NULL, return 0 if \a fd is not set in \a rfds without calling accept().
819 * \return Negative on errors, zero if no connections are present to be accepted,
824 int para_accept(int fd, fd_set *rfds, void *addr, socklen_t size, int *new_fd)
828 if (rfds && !FD_ISSET(fd, rfds))
831 ret = accept(fd, (struct sockaddr *) addr, &size);
832 while (ret < 0 && errno == EINTR);
838 if (errno == EAGAIN || errno == EWOULDBLOCK)
840 return -ERRNO_TO_PARA_ERROR(errno);
844 * Probe the list of DCCP CCIDs configured on this host.
845 * \param ccid_array Pointer to return statically allocated array in.
846 * \return Number of elements returned in \a ccid_array or error.
848 * NB: This feature is only available on Linux > 2.6.30; on older kernels
849 * ENOPROTOOPT ("Protocol not available") will be returned.
851 int dccp_available_ccids(uint8_t **ccid_array)
853 static uint8_t ccids[DCCP_MAX_HOST_CCIDS];
854 socklen_t nccids = sizeof(ccids);
857 ret = fd = makesock(IPPROTO_DCCP, 1, NULL, 0, NULL);
861 if (getsockopt(fd, SOL_DCCP, DCCP_SOCKOPT_AVAILABLE_CCIDS,
862 ccids, &nccids) < 0) {
865 PARA_ERROR_LOG("No DCCP_SOCKOPT_AVAILABLE_CCIDS: %s\n",
867 return -ERRNO_TO_PARA_ERROR(ret);
876 * Prepare a structure for \p AF_UNIX socket addresses.
878 * \param u Pointer to the struct to be prepared.
879 * \param name The socket pathname.
881 * This just copies \a name to the sun_path component of \a u.
883 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
884 * than \p UNIX_PATH_MAX.
886 static int init_unix_addr(struct sockaddr_un *u, const char *name)
888 if (strlen(name) >= UNIX_PATH_MAX)
889 return -E_NAME_TOO_LONG;
890 memset(u->sun_path, 0, UNIX_PATH_MAX);
891 u->sun_family = PF_UNIX;
892 strcpy(u->sun_path, name);
897 * Prepare, create, and bind a socket for local communication.
899 * \param name The socket pathname.
900 * \param unix_addr Pointer to the \p AF_UNIX socket structure.
901 * \param mode The desired mode of the socket.
903 * This function creates a local socket for sequenced, reliable,
904 * two-way, connection-based byte streams.
906 * \return The file descriptor, on success, negative on errors.
912 int create_local_socket(const char *name, struct sockaddr_un *unix_addr,
917 ret = init_unix_addr(unix_addr, name);
920 ret = socket(PF_UNIX, SOCK_STREAM, 0);
922 return -ERRNO_TO_PARA_ERROR(errno);
924 ret = bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX);
926 ret = -ERRNO_TO_PARA_ERROR(errno);
930 if (chmod(name, mode) < 0)
939 * Prepare, create, and connect to a Unix domain socket for local communication.
941 * \param name The socket pathname.
943 * This function creates a local socket for sequenced, reliable, two-way,
944 * connection-based byte streams.
946 * \return The file descriptor of the connected socket on success, negative on
949 * \sa create_local_socket(), unix(7), connect(2).
951 int connect_local_socket(const char *name)
953 struct sockaddr_un unix_addr;
956 PARA_DEBUG_LOG("connecting to %s\n", name);
957 ret = init_unix_addr(&unix_addr, name);
960 fd = socket(PF_UNIX, SOCK_STREAM, 0);
962 return -ERRNO_TO_PARA_ERROR(errno);
963 if (connect(fd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) == -1) {
964 ret = -ERRNO_TO_PARA_ERROR(errno);
974 ssize_t send_cred_buffer(int sock, char *buf)
976 return send_buffer(sock, buf);
978 int recv_cred_buffer(int fd, char *buf, size_t size)
980 return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
982 #else /* HAVE_UCRED */
984 * Send \p NULL-terminated buffer and Unix credentials of the current process.
986 * \param sock The socket file descriptor.
987 * \param buf The buffer to be sent.
989 * \return On success, this call returns the number of characters sent. On
990 * error, \p -E_SENDMSG is returned.
992 * \sa sendmsg(2), okir's Black Hats Manual.
994 ssize_t send_cred_buffer(int sock, char *buf)
996 char control[sizeof(struct cmsghdr) + sizeof(struct ucred)];
998 struct cmsghdr *cmsg;
999 static struct iovec iov;
1005 iov.iov_len = strlen(buf);
1009 /* compose the message */
1010 memset(&msg, 0, sizeof(msg));
1013 msg.msg_control = control;
1014 msg.msg_controllen = sizeof(control);
1015 /* attach the ucred struct */
1016 cmsg = CMSG_FIRSTHDR(&msg);
1017 cmsg->cmsg_level = SOL_SOCKET;
1018 cmsg->cmsg_type = SCM_CREDENTIALS;
1019 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
1020 *(struct ucred *)CMSG_DATA(cmsg) = c;
1021 msg.msg_controllen = cmsg->cmsg_len;
1022 ret = sendmsg(sock, &msg, 0);
1028 static void dispose_fds(int *fds, unsigned num)
1032 for (i = 0; i < num; i++)
1037 * Receive a buffer and the Unix credentials of the sending process.
1039 * \param fd the socket file descriptor.
1040 * \param buf the buffer to store the message.
1041 * \param size the size of \a buffer.
1043 * \return negative on errors, the user id on success.
1045 * \sa recvmsg(2), okir's Black Hats Manual.
1047 int recv_cred_buffer(int fd, char *buf, size_t size)
1051 struct cmsghdr *cmsg;
1057 setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
1058 memset(&msg, 0, sizeof(msg));
1059 memset(buf, 0, size);
1064 msg.msg_control = control;
1065 msg.msg_controllen = sizeof(control);
1066 if (recvmsg(fd, &msg, 0) < 0)
1068 result = -E_SCM_CREDENTIALS;
1069 cmsg = CMSG_FIRSTHDR(&msg);
1071 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
1072 == SCM_CREDENTIALS) {
1073 memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
1076 if (cmsg->cmsg_level == SOL_SOCKET
1077 && cmsg->cmsg_type == SCM_RIGHTS) {
1078 dispose_fds((int *) CMSG_DATA(cmsg),
1079 (cmsg->cmsg_len - CMSG_LEN(0))
1082 cmsg = CMSG_NXTHDR(&msg, cmsg);
1086 #endif /* HAVE_UCRED */