]> git.tuebingen.mpg.de Git - paraslash.git/blob - net.c
net: Refer to correct man page in stringify_port().
[paraslash.git] / net.c
1 /* Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file net.c Networking-related helper functions. */
4
5 #include "para.h"
6
7 #include <netinet/in.h>
8 #include <arpa/inet.h>
9 #include <sys/un.h>
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <netdb.h>
13 #include <regex.h>
14
15 #include "error.h"
16 #include "net.h"
17 #include "string.h"
18 #include "list.h"
19 #include "fd.h"
20
21 /* Whether the given address conforms to the IPv4 address format. */
22 static inline bool is_valid_ipv4_address(const char *address)
23 {
24         struct in_addr test_it;
25         return inet_pton(AF_INET, address, &test_it) != 0;
26 }
27
28 /**
29  * Parse and validate IPv4 address/netmask string.
30  *
31  * \param cidr    Address in CIDR notation
32  * \param addr    Copy of the IPv4 address part of \a cidr
33  * \param addrlen Size of \a addr in bytes
34  * \param netmask Value of the netmask part in \a cidr or the
35  *                default of 32 if not specified.
36  *
37  * \return Pointer to \a addr if successful, NULL on error.
38  * \sa RFC 4632.
39  */
40 char *parse_cidr(const char *cidr,
41                  char    *addr, ssize_t addrlen,
42                  int32_t *netmask)
43 {
44         const char *o = cidr;
45         char *c = addr, *end = c + (addrlen - 1);
46
47         *netmask = 0x20;
48
49         if (cidr == NULL || addrlen < 1)
50                 goto failed;
51
52         for (o = cidr; (*c = *o == '/'? '\0' : *o); c++, o++)
53                 if (c == end)
54                         goto failed;
55
56         if (*o == '/')
57                 if (para_atoi32(++o, netmask) < 0 ||
58                     *netmask < 0 || *netmask > 0x20)
59                         goto failed;
60
61         if (is_valid_ipv4_address(addr))
62                 return addr;
63 failed:
64         *addr = '\0';
65         return NULL;
66 }
67
68
69 /**
70  * Match string as a candidate IPv4 address.
71  *
72  * \param address The string to match.
73  * \return True if \a address has "dot-quad" format.
74  */
75 static bool is_v4_dot_quad(const char *address)
76 {
77         bool result;
78         regex_t r;
79
80         assert(para_regcomp(&r, "^([0-9]+\\.){3}[0-9]+$",
81                 REG_EXTENDED | REG_NOSUB) >= 0);
82         result = regexec(&r, address, 0, NULL, 0) == 0;
83         regfree(&r);
84         return result;
85 }
86
87 /* Whether a string conforms to IPv6 address format (RFC 4291). */
88 static inline bool is_valid_ipv6_address(const char *address)
89 {
90         struct in6_addr test_it;
91         return inet_pton(AF_INET6, address, &test_it) != 0;
92 }
93
94 /**
95  * Perform basic syntax checking on the host-part of an URL:
96  *
97  * - Since ':' is invalid in IPv4 addresses and DNS names, the
98  *   presence of ':' causes interpretation as IPv6 address;
99  * - next the first-match-wins algorithm from RFC 3986 is applied;
100  * - else the string is considered as DNS name, to be resolved later.
101  *
102  * \param host The host string to check.
103  * \return True if \a host passes the syntax checks.
104  *
105  * \sa RFC 3986, 3.2.2; RFC 1123, 2.1; RFC 1034, 3.5.
106  */
107 static bool host_string_ok(const char *host)
108 {
109         if (host == NULL || *host == '\0')
110                 return false;
111         if (strchr(host, ':') != NULL)
112                 return is_valid_ipv6_address(host);
113         if (is_v4_dot_quad(host))
114                 return is_valid_ipv4_address(host);
115         return true;
116 }
117
118 /**
119  * Parse and validate URL string.
120  *
121  * The URL syntax is loosely based on RFC 3986, supporting one of
122  * - "["host"]"[:port] for native IPv6 addresses and
123  * - host[:port] for IPv4 hostnames and DNS names.
124  *
125  * Native IPv6 addresses must be enclosed in square brackets, since
126  * otherwise there is an ambiguity with the port separator `:'.
127  * The 'port' part is always considered to be a number; if absent,
128  * it is set to -1, to indicate that a default port is to be used.
129  *
130  * The following are valid examples:
131  * - 10.10.1.1
132  * - 10.10.1.2:8000
133  * - localhost
134  * - localhost:8001
135  * - [::1]:8000
136  * - [badc0de::1]
137  *
138  * \param url     The URL string to take apart.
139  * \param host    To return the copied host part of \a url.
140  * \param hostlen The maximum length of \a host.
141  * \param port    To return the port number (if any) of \a url.
142  *
143  * \return Pointer to \a host, or \p NULL if failed.  If \p NULL is returned,
144  * \a host and \a port are undefined. If no port number was present in \a url,
145  * \a port is set to -1.
146  *
147  * \sa RFC 3986, 3.2.2/3.2.3.
148  */
149 char *parse_url(const char *url,
150                 char    *host, ssize_t hostlen,
151                 int32_t *port)
152 {
153         const char *o = url;
154         char *c = host, *end = c + (hostlen - 1);
155
156         *port = -1;
157
158         if (o == NULL || hostlen < 1)
159                 goto failed;
160
161         if (*o == '[') {
162                 for (++o; (*c = *o == ']' ? '\0' : *o); c++, o++)
163                         if (c == end)
164                                 goto failed;
165
166                 if (*o++ != ']' || (*o != '\0' && *o != ':'))
167                         goto failed;
168         } else {
169                 for (; (*c = *o == ':'? '\0' : *o); c++, o++) {
170                         if (c == end && o[1])
171                                 goto failed;
172                 }
173         }
174
175         if (*o == ':')
176                 if (para_atoi32(++o, port) < 0 || *port < 0 || *port > 0xffff)
177                         goto failed;
178         if (host_string_ok(host))
179                 return host;
180 failed:
181         *host = '\0';
182         return NULL;
183 }
184
185 /**
186  * Pretty-print a host/port pair.
187  *
188  * \param url NULL, or any string accepted by \ref parse_url().
189  * \param default_port Applies if url has no port.
190  *
191  * If the url argument is NULL, the function returns the string
192  * 0.0.0.0:default_port. Otherwise it calls \ref parse_url() to check the
193  * syntax of the input string given by url. On errors the string "?" is
194  * returned. Otherwise, if url contains a port, a copy of url is returned. If
195  * no port was supplied, a colon and the default port are appended to url.
196  *
197  * \return In all cases the returned string is a allocated with malloc(3) and
198  * has to be freed by the caller.
199  */
200 char *format_url(const char *url, int default_port)
201 {
202         char host[MAX_HOSTLEN];
203         int url_port;
204
205         if (!url)
206                 return make_message("0.0.0.0:%d", default_port);
207         if (!parse_url(url, host, sizeof(host), &url_port))
208                 return make_message("?");
209         if (url_port < 0)
210                 return make_message("%s:%d", url, default_port);
211         else
212                 return para_strdup(url);
213 }
214
215 /**
216  * Stringify port number, resolve into service name where defined.
217  *
218  * \param port 2-byte port number, in host-byte-order.
219  * \param transport Transport protocol name (e.g. "udp", "tcp"), or NULL.
220  * \return Pointer to static result buffer.
221  *
222  * \sa getservbyport(3), services(5), nsswitch.conf(5).
223  */
224 const char *stringify_port(int port, const char *transport)
225 {
226         static char service[NI_MAXSERV];
227
228         if (port < 0 || port > 0xFFFF) {
229                 snprintf(service, sizeof(service), "undefined (%d)", port);
230         } else {
231                 struct servent *se = getservbyport(htons(port), transport);
232
233                 if (se == NULL)
234                         snprintf(service, sizeof(service), "%d", port);
235                 else
236                         snprintf(service, sizeof(service), "%s", se->s_name);
237         }
238         return service;
239 }
240
241 #ifndef SOCK_DCCP
242 #define SOCK_DCCP 6 /**< Linux socket type. */
243 #endif
244
245 /**
246  * Determine the socket type for a given layer-4 protocol.
247  *
248  * \param l4type The symbolic name of the transport-layer protocol.
249  *
250  * \sa ip(7), socket(2).
251  */
252 static inline int sock_type(const unsigned l4type)
253 {
254         switch (l4type) {
255         case IPPROTO_UDP:       return SOCK_DGRAM;
256         case IPPROTO_TCP:       return SOCK_STREAM;
257         case IPPROTO_DCCP:      return SOCK_DCCP;
258         }
259         return -1;              /* not supported here */
260 }
261
262 /**
263  * Pretty-print transport-layer name.
264  */
265 static const char *layer4_name(const unsigned l4type)
266 {
267         switch (l4type) {
268         case IPPROTO_UDP:       return "UDP";
269         case IPPROTO_TCP:       return "TCP";
270         case IPPROTO_DCCP:      return "DCCP";
271         }
272         return "UNKNOWN PROTOCOL";
273 }
274
275 /**
276  * Flowopts: Transport-layer independent encapsulation of socket options.
277  *
278  * These collect individual socket options into a queue, which is disposed of
279  * directly after makesock(). The 'pre_conn_opt' structure is for internal use
280  * only and should not be visible elsewhere.
281  *
282  * \sa setsockopt(2), \ref makesock().
283  */
284 struct pre_conn_opt {
285         int             sock_level;     /**< Second argument to setsockopt() */
286         int             sock_option;    /**< Third argument to setsockopt()  */
287         char            *opt_name;      /**< Stringified \a sock_option      */
288         void            *opt_val;       /**< Fourth argument to setsockopt() */
289         socklen_t       opt_len;        /**< Fifth argument to setsockopt()  */
290
291         struct list_head node;          /**< FIFO, as sockopt order matters. */
292 };
293
294 /**
295  * List of pre-connection socket options to be set.
296  *
297  * This list contains transport-layer independent encapsulation of socket
298  * options that need to be registered prior to setting up a connection.
299  */
300 struct flowopts {
301         struct list_head sockopts;
302 };
303
304 /**
305  * Allocate and initialize a flowopt queue.
306  *
307  * \return A new structure to be passed to \ref flowopt_add(). It is
308  * automatically deallocated in \ref makesock().
309  */
310 struct flowopts *flowopt_new(void)
311 {
312         struct flowopts *new = alloc(sizeof(*new));
313
314         init_list_head(&new->sockopts);
315         return new;
316 }
317
318 /**
319  * Append new socket option to flowopt queue.
320  *
321  * \param fo   The flowopt queue to append to.
322  * \param lev  Level at which \a opt resides.
323  * \param opt  New option to add.
324  * \param name Stringified name of \a opt.
325  * \param val  The value to set \a opt to.
326  * \param len  Length of \a val.
327  *
328  *  \sa setsockopt(2).
329  */
330 void flowopt_add(struct flowopts *fo, int lev, int opt,
331                 const char *name, const void *val, int len)
332 {
333         struct pre_conn_opt *new = alloc(sizeof(*new));
334
335         new->sock_option = opt;
336         new->sock_level  = lev;
337         new->opt_name    = para_strdup(name);
338
339         if (val == NULL) {
340                 new->opt_val = NULL;
341                 new->opt_len = 0;
342         } else {
343                 new->opt_val = alloc(len);
344                 new->opt_len = len;
345                 memcpy(new->opt_val, val, len);
346         }
347
348         list_add_tail(&new->node, &fo->sockopts);
349 }
350
351 /** Set the entire bunch of pre-connection options at once. */
352 static void flowopt_setopts(int sockfd, struct flowopts *fo)
353 {
354         struct pre_conn_opt *pc;
355
356         if (fo == NULL)
357                 return;
358
359         list_for_each_entry(pc, &fo->sockopts, node)
360                 if (setsockopt(sockfd, pc->sock_level, pc->sock_option,
361                                        pc->opt_val, pc->opt_len) < 0) {
362                         PARA_EMERG_LOG("Can not set %s socket option: %s",
363                                        pc->opt_name, strerror(errno));
364                         exit(EXIT_FAILURE);
365                 }
366 }
367
368 /**
369  * Deallocate all resources of a flowopts structure.
370  *
371  * \param fo A pointer as returned from flowopt_new().
372  *
373  * It's OK to pass \p NULL here in which case the function does nothing.
374  */
375 void flowopt_cleanup(struct flowopts *fo)
376 {
377         struct pre_conn_opt *cur, *next;
378
379         if (fo == NULL)
380                 return;
381
382         list_for_each_entry_safe(cur, next, &fo->sockopts, node) {
383                 free(cur->opt_name);
384                 free(cur->opt_val);
385                 free(cur);
386         }
387         free(fo);
388 }
389
390 /**
391  * Resolve an IPv4/IPv6 address.
392  *
393  * \param l4type The layer-4 type (\p IPPROTO_xxx).
394  * \param passive Whether \p AI_PASSIVE should be included as hint.
395  * \param host Remote or local hostname or IPv/6 address string.
396  * \param port_number Used to set the port in each returned address structure.
397  * \param result addrinfo structures are returned here.
398  *
399  * The interpretation of \a host depends on the value of \a passive. On a
400  * passive socket host is interpreted as an interface IPv4/6 address (can be
401  * left NULL). On an active socket, \a host is the peer DNS name or IPv4/6
402  * address to connect to.
403  *
404  * \return Standard.
405  *
406  * \sa getaddrinfo(3).
407  */
408 int lookup_address(unsigned l4type, bool passive, const char *host,
409                 int port_number, struct addrinfo **result)
410 {
411         int ret;
412         char port[6]; /* port number has at most 5 digits */
413         struct addrinfo *addr = NULL, hints;
414
415         *result = NULL;
416         sprintf(port, "%d", port_number & 0xffff);
417         /* Set up address hint structure */
418         memset(&hints, 0, sizeof(hints));
419         hints.ai_family = AF_UNSPEC;
420         hints.ai_socktype = sock_type(l4type);
421         /*
422          * getaddrinfo does not support SOCK_DCCP, so for the sake of lookup
423          * (and only then) pretend to be UDP.
424          */
425         if (l4type == IPPROTO_DCCP)
426                 hints.ai_socktype = SOCK_DGRAM;
427         /* only use addresses available on the host */
428         hints.ai_flags = AI_ADDRCONFIG;
429         if (passive && host == NULL)
430                 hints.ai_flags |= AI_PASSIVE;
431         /* Obtain local/remote address information */
432         ret = getaddrinfo(host, port, &hints, &addr);
433         if (ret != 0) {
434                 PARA_ERROR_LOG("can not resolve %s address %s#%s: %s\n",
435                         layer4_name(l4type),
436                         host? host : (passive? "[loopback]" : "[localhost]"),
437                         port, gai_strerror(ret));
438                 return -E_ADDRESS_LOOKUP;
439         }
440         *result = addr;
441         return 1;
442 }
443
444 /**
445  * Create an active or passive socket.
446  *
447  * \param l4type \p IPPROTO_TCP, \p IPPROTO_UDP, or \p IPPROTO_DCCP.
448  * \param passive Whether to call bind(2) or connect(2).
449  * \param ai Address information as obtained from \ref lookup_address().
450  * \param fo Socket options to be set before making the connection.
451  *
452  * bind(2) is called on passive sockets, and connect(2) on active sockets. The
453  * algorithm tries all possible address combinations until it succeeds. If \a
454  * fo is supplied, options are set but cleanup must be performed in the caller.
455  *
456  * \return File descriptor on success, \p E_MAKESOCK on errors.
457  *
458  * \sa \ref lookup_address(), \ref makesock(), ip(7), ipv6(7), bind(2),
459  * connect(2).
460  */
461 int makesock_addrinfo(unsigned l4type, bool passive, struct addrinfo *ai,
462                 struct flowopts *fo)
463 {
464         int ret = -E_MAKESOCK, on = 1;
465
466         for (; ai; ai = ai->ai_next) {
467                 int fd;
468                 ret = socket(ai->ai_family, sock_type(l4type), l4type);
469                 if (ret < 0) {
470                         PARA_NOTICE_LOG("socket(): %s\n", strerror(errno));
471                         continue;
472                 }
473                 fd = ret;
474                 flowopt_setopts(fd, fo);
475                 if (!passive) {
476                         if (connect(fd, ai->ai_addr, ai->ai_addrlen) < 0) {
477                                 PARA_NOTICE_LOG("connect(): %s\n",
478                                         strerror(errno));
479                                 close(fd);
480                                 continue;
481                         }
482                         return fd;
483                 }
484                 /*
485                  * Reuse the address on passive sockets to avoid failure on
486                  * restart (protocols using listen()) and when creating
487                  * multiple listener instances (UDP multicast).
488                  */
489                 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on,
490                                 sizeof(on)) == -1) {
491                         PARA_NOTICE_LOG("setsockopt(): %s\n", strerror(errno));
492                         close(fd);
493                         continue;
494                 }
495                 if (bind(fd, ai->ai_addr, ai->ai_addrlen) < 0) {
496                         PARA_NOTICE_LOG("bind(): %s\n", strerror(errno));
497                         close(fd);
498                         continue;
499                 }
500                 return fd;
501         }
502         return -E_MAKESOCK;
503 }
504
505 /**
506  * Resolve IPv4/IPv6 address and create a ready-to-use active or passive socket.
507  *
508  * \param l4type The layer-4 type (\p IPPROTO_xxx).
509  * \param passive Whether this is a passive or active socket.
510  * \param host Passed to \ref lookup_address().
511  * \param port_number Passed to \ref lookup_address().
512  * \param fo Passed to \ref makesock_addrinfo().
513  *
514  * This creates a ready-made IPv4/v6 socket structure after looking up the
515  * necessary parameters. The function first calls \ref lookup_address() and
516  * passes the address information to makesock_addrinfo() to create and
517  * initialize the socket.
518  *
519  * \return The newly created file descriptor on success, a negative error code
520  * on failure.
521  *
522  * \sa \ref lookup_address(), \ref makesock_addrinfo().
523  */
524 int makesock(unsigned l4type, bool passive, const char *host, uint16_t port_number,
525                 struct flowopts *fo)
526 {
527         struct addrinfo *ai;
528         int ret = lookup_address(l4type, passive, host, port_number, &ai);
529
530         if (ret >= 0)
531                 ret = makesock_addrinfo(l4type, passive, ai, fo);
532         if (ai)
533                 freeaddrinfo(ai);
534         if (ret < 0) {
535                 PARA_NOTICE_LOG("can not create %s socket %s#%d.\n",
536                 layer4_name(l4type), host? host : (passive?
537                 "[loopback]" : "[localhost]"), port_number);
538         }
539         return ret;
540 }
541
542 /**
543  * Create a passive / listening socket.
544  *
545  * \param l4type The transport-layer type (\p IPPROTO_xxx).
546  * \param addr Passed to \ref parse_url() if not NULL.
547  * \param port Ignored if addr contains a port number.
548  *
549  * \return Positive integer (socket descriptor) on success, negative value
550  * otherwise.
551  *
552  * \sa \ref makesock(), ip(7), ipv6(7), bind(2), listen(2).
553  */
554 int para_listen(unsigned l4type, const char *addr, uint16_t port)
555 {
556         char host[MAX_HOSTLEN];
557         int ret, fd, addr_port;
558
559         if (addr) {
560                 if (!parse_url(addr, host, sizeof(host), &addr_port))
561                         return -ERRNO_TO_PARA_ERROR(EINVAL);
562                 if (addr_port > 0)
563                         port = addr_port;
564                 addr = host;
565         }
566         fd = makesock(l4type, true /* passive */, addr, port,
567                 NULL /* no flowopts */);
568         if (fd > 0) {
569                 ret = listen(fd, BACKLOG);
570                 if (ret < 0) {
571                         ret = errno;
572                         close(fd);
573                         return -ERRNO_TO_PARA_ERROR(ret);
574                 }
575                 PARA_INFO_LOG("listening on %s port %u, fd %d\n",
576                         layer4_name(l4type), port, fd);
577         }
578         return fd;
579 }
580
581 /**
582  * Create a socket which listens on all network addresses.
583  *
584  * \param l4type See \ref para_listen().
585  * \param port See \ref para_listen().
586  *
587  * This is a simple wrapper for \ref para_listen() which passes a NULL pointer
588  * as the address information.
589  *
590  * \return See \ref para_listen().
591  */
592 int para_listen_simple(unsigned l4type, uint16_t port)
593 {
594         return para_listen(l4type, NULL, port);
595 }
596
597 /**
598  * Determine IPv4/v6 socket address length.
599  * \param sa Container of IPv4 or IPv6 address.
600  * \return Address-family dependent address length.
601  */
602 static socklen_t salen(const struct sockaddr *sa)
603 {
604         assert(sa->sa_family == AF_INET || sa->sa_family == AF_INET6);
605
606         return sa->sa_family == AF_INET6
607                 ? sizeof(struct sockaddr_in6)
608                 : sizeof(struct sockaddr_in);
609 }
610
611 /** True if @ss holds a v6-mapped-v4 address (RFC 4291, 2.5.5.2) */
612 static bool SS_IS_ADDR_V4MAPPED(const struct sockaddr_storage *ss)
613 {
614         const struct sockaddr_in6 *ia6 = (const struct sockaddr_in6 *)ss;
615
616         return ss->ss_family == AF_INET6 && IN6_IS_ADDR_V4MAPPED(&ia6->sin6_addr);
617 }
618
619 /**
620  * Process IPv4/v6 address, turn v6-mapped-v4 address into normal IPv4 address.
621  * \param ss Container of IPv4/6 address.
622  * \return Pointer to normalized address (may be static storage).
623  *
624  * \sa RFC 3493.
625  */
626 static const struct sockaddr *
627 normalize_ip_address(const struct sockaddr_storage *ss)
628 {
629         assert(ss->ss_family == AF_INET || ss->ss_family == AF_INET6);
630
631         if (SS_IS_ADDR_V4MAPPED(ss)) {
632                 const struct sockaddr_in6 *ia6 = (const struct sockaddr_in6 *)ss;
633                 static struct sockaddr_in ia;
634
635                 ia.sin_family = AF_INET;
636                 ia.sin_port   = ia6->sin6_port;
637                 memcpy(&ia.sin_addr.s_addr, &(ia6->sin6_addr.s6_addr[12]), 4);
638                 return (const struct sockaddr *)&ia;
639         }
640         return (const struct sockaddr *)ss;
641 }
642
643 /**
644  * Generic/fallback MTU values
645  *
646  * These are taken from RFC 1122, RFC 2460, and RFC 5405.
647  * - RFC 1122, 3.3.3 defines EMTU_S ("Effective MTU for sending") and recommends
648  *   to use an EMTU_S size of of 576 bytes if the IPv4 path MTU is unknown;
649  * - RFC 2460, 5. requires a minimum IPv6 MTU of 1280 bytes;
650  * - RFC 5405, 3.2 recommends that if path MTU discovery is not done,
651  *   UDP senders should use the respective minimum values of EMTU_S.
652  */
653 static inline int generic_mtu(const int af_type)
654 {
655         return af_type == AF_INET6 ? 1280 : 576;
656 }
657
658 /** Crude approximation of IP header overhead - neglecting options. */
659 static inline int estimated_header_overhead(const int af_type)
660 {
661         return af_type == AF_INET6 ? 40 : 20;
662 }
663
664 /**
665  * Get the maximum transport-layer message size (MMS_S).
666  *
667  * \param sockfd The socket file descriptor.
668  *
669  * The socket must be connected. See RFC 1122, 3.3.3. If the protocol family
670  * could not be determined, \p AF_INET is assumed.
671  *
672  * \return The maximum message size of the address family type.
673  */
674 int generic_max_transport_msg_size(int sockfd)
675 {
676         struct sockaddr_storage ss = {.ss_family = 0};
677         socklen_t sslen = sizeof(ss);
678         int af_type = AF_INET;
679
680         if (getpeername(sockfd, (struct sockaddr *)&ss, &sslen) < 0) {
681                 PARA_ERROR_LOG("can not determine remote address type: %s\n",
682                                 strerror(errno));
683         } else if (!SS_IS_ADDR_V4MAPPED(&ss)) {
684                 af_type = ss.ss_family;
685         }
686         return generic_mtu(af_type) - estimated_header_overhead(af_type);
687 }
688
689 /**
690  * Look up the remote side of a connected socket structure.
691  *
692  * \param fd The socket descriptor of the connected socket.
693  *
694  * \return A static character string identifying hostname and port of the
695  * chosen side in numeric host:port format.
696  *
697  * \sa getsockname(2), getpeername(2), \ref parse_url(), getnameinfo(3),
698  * services(5), nsswitch.conf(5).
699  */
700 char *remote_name(int fd)
701 {
702         struct sockaddr_storage ss = {.ss_family = 0};
703         const struct sockaddr *sa;
704         socklen_t sslen = sizeof(ss);
705         char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
706         static char output[sizeof(hbuf) + sizeof(sbuf) + 4];
707         int ret;
708
709         if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {
710                 PARA_ERROR_LOG("can not determine address from fd %d: %s\n",
711                         fd, strerror(errno));
712                 snprintf(output, sizeof(output), "(unknown)");
713                 return output;
714         }
715         sa = normalize_ip_address(&ss);
716         ret = getnameinfo(sa, salen(sa), hbuf, sizeof(hbuf), sbuf,
717                 sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV);
718         if (ret) {
719                 PARA_WARNING_LOG("hostname lookup error (%s).\n",
720                         gai_strerror(ret));
721                 snprintf(output, sizeof(output), "(lookup error)");
722         } else if (sa->sa_family == AF_INET6)
723                 snprintf(output, sizeof(output), "[%s]:%s", hbuf, sbuf);
724         else
725                 snprintf(output, sizeof(output), "%s:%s", hbuf, sbuf);
726         return output;
727 }
728
729 /**
730  * Extract IPv4 or IPv6-mapped-IPv4 address from sockaddr_storage.
731  *
732  * \param ss Container of IPv4/6 address.
733  * \param ia Extracted IPv4 address (different from 0) or 0 if unsuccessful.
734  *
735  * \sa RFC 3493.
736  */
737 void extract_v4_addr(const struct sockaddr_storage *ss, struct in_addr *ia)
738 {
739         const struct sockaddr *sa = normalize_ip_address(ss);
740
741         memset(ia, 0, sizeof(*ia));
742         if (sa->sa_family == AF_INET)
743                 *ia = ((struct sockaddr_in *)sa)->sin_addr;
744 }
745
746 /**
747  * Compare the address part of IPv4/6 addresses.
748  *
749  * \param sa1 First address.
750  * \param sa2 Second address.
751  *
752  * \return True iff the IP address of \a sa1 and \a sa2 match.
753  */
754 bool sockaddr_equal(const struct sockaddr *sa1, const struct sockaddr *sa2)
755 {
756         if (!sa1 || !sa2)
757                 return false;
758         if (sa1->sa_family != sa2->sa_family)
759                 return false;
760         if (sa1->sa_family == AF_INET) {
761                 struct sockaddr_in *a1 = (typeof(a1))sa1,
762                         *a2 = (typeof (a2))sa2;
763                 return a1->sin_addr.s_addr == a2->sin_addr.s_addr;
764         } else if (sa1->sa_family == AF_INET6) {
765                 struct sockaddr_in6 *a1 = (typeof(a1))sa1,
766                         *a2 = (typeof (a2))sa2;
767                 return !memcmp(a1, a2, sizeof(*a1));
768         } else
769                 return false;
770 }
771
772 /**
773  * Receive data from a file descriptor.
774  *
775  * \param fd The file descriptor.
776  * \param buf The buffer to write the data to.
777  * \param size The size of \a buf.
778  *
779  * Receive at most \a size bytes from file descriptor \a fd.
780  *
781  * \return The number of bytes received on success, negative on errors, zero if
782  * the peer has performed an orderly shutdown.
783  *
784  * \sa recv(2).
785  */
786 __must_check int recv_bin_buffer(int fd, char *buf, size_t size)
787 {
788         ssize_t n;
789
790         n = recv(fd, buf, size, 0);
791         if (n == -1)
792                 return -ERRNO_TO_PARA_ERROR(errno);
793         return n;
794 }
795
796 /**
797  * Receive and write terminating NULL byte.
798  *
799  * \param fd The file descriptor.
800  * \param buf The buffer to write the data to.
801  * \param size The size of \a buf.
802  *
803  * Read at most \a size - 1 bytes from file descriptor \a fd and
804  * write a NULL byte at the end of the received data.
805  *
806  * \return The return value of the underlying call to \a recv_bin_buffer().
807  *
808  * \sa \ref recv_bin_buffer()
809  */
810 int recv_buffer(int fd, char *buf, size_t size)
811 {
812         int n;
813
814         assert(size);
815         n = recv_bin_buffer(fd, buf, size - 1);
816         if (n >= 0)
817                 buf[n] = '\0';
818         else
819                 *buf = '\0';
820         return n;
821 }
822
823 /**
824  * Wrapper around the accept system call.
825  *
826  * \param fd The listening socket.
827  * \param addr Structure which is filled in with the address of the peer socket.
828  * \param size Should contain the size of the structure pointed to by \a addr.
829  * \param new_fd Result pointer.
830  *
831  * Accept incoming connections on addr, retry if interrupted.
832  *
833  * \return Negative on errors, zero if no connections are present to be accepted,
834  * one otherwise.
835  *
836  * \sa accept(2).
837  */
838 int para_accept(int fd, void *addr, socklen_t size, int *new_fd)
839 {
840         int ret;
841
842         do
843                 ret = accept(fd, (struct sockaddr *) addr, &size);
844         while (ret < 0 && errno == EINTR);
845
846         if (ret >= 0) {
847                 *new_fd = ret;
848                 return 1;
849         }
850         if (errno == EAGAIN || errno == EWOULDBLOCK)
851                 return 0;
852         return -ERRNO_TO_PARA_ERROR(errno);
853 }
854
855 #ifndef DCCP_SOCKOPT_AVAILABLE_CCIDS
856 #define DCCP_SOCKOPT_AVAILABLE_CCIDS 12 /**< List of supported CCIDs. */
857 #endif
858
859 /**
860  * Probe the list of DCCP CCIDs configured on this host.
861  * \param ccid_array Pointer to return statically allocated array in.
862  * \return Number of elements returned in \a ccid_array or error.
863  *
864  * NB: This feature is only available on Linux > 2.6.30; on older kernels
865  * ENOPROTOOPT ("Protocol not available") will be returned.
866  */
867 int dccp_available_ccids(uint8_t **ccid_array)
868 {
869         static uint8_t ccids[DCCP_MAX_HOST_CCIDS];
870         socklen_t nccids = sizeof(ccids);
871         int ret, fd;
872
873         ret = fd = makesock(IPPROTO_DCCP, true /* passive */, NULL, 0, NULL);
874         if (ret < 0)
875                 return ret;
876
877         if (getsockopt(fd, SOL_DCCP, DCCP_SOCKOPT_AVAILABLE_CCIDS,
878                                                 ccids, &nccids) < 0) {
879                 ret = errno;
880                 close(fd);
881                 PARA_ERROR_LOG("No DCCP_SOCKOPT_AVAILABLE_CCIDS: %s\n",
882                                 strerror(ret));
883                 return -ERRNO_TO_PARA_ERROR(ret);
884         }
885
886         close(fd);
887         *ccid_array = ccids;
888         return nccids;
889 }
890
891 /**
892  * The buffer size of the sun_path component of struct sockaddr_un.
893  *
894  * While glibc doesn't define UNIX_PATH_MAX, it documents it has being limited
895  * to 108 bytes. On NetBSD it is only 104 bytes though. We trust UNIX_PATH_MAX
896  * if it is defined and use the size of the ->sun_path member otherwise. This
897  * should be safe everywhere.
898  */
899 #ifndef UNIX_PATH_MAX
900 #define UNIX_PATH_MAX (sizeof(((struct sockaddr_un *)0)->sun_path))
901 #endif
902
903 /*
904  * Prepare a structure for AF_UNIX socket addresses.
905  *
906  * This just copies name to the sun_path component of u, prepending a zero byte
907  * if abstract sockets are supported.
908  *
909  * The first call to this function tries to bind a socket to the abstract name
910  * space. The result of this test is stored in a static variable. Subsequent
911  * calls read this variable and create abstract sockets on systems that support
912  * them. If a NULL pointer is passed as the name, the function only
913  * initializes the static variable.
914  */
915 static int init_unix_addr(struct sockaddr_un *u, const char *name)
916 {
917         static int use_abstract;
918
919         memset(u->sun_path, 0, UNIX_PATH_MAX);
920         u->sun_family = PF_UNIX;
921         if (use_abstract == 0) { /* executed only once */
922                 int fd = socket(PF_UNIX, SOCK_STREAM, 0);
923                 memcpy(u->sun_path, "\0x\0", 3);
924                 if (bind(fd, (struct sockaddr *)u, sizeof(*u)) == 0)
925                         use_abstract = 1; /* yes */
926                 else
927                         use_abstract = -1; /* no */
928                 close(fd);
929                 PARA_NOTICE_LOG("%susing abstract socket namespace\n",
930                         use_abstract == 1? "" : "not ");
931         }
932         if (!name)
933                 return 0;
934         if (strlen(name) + 1 >= UNIX_PATH_MAX)
935                 return -E_NAME_TOO_LONG;
936         strcpy(u->sun_path + (use_abstract == 1? 1 : 0), name);
937         return 1;
938 }
939
940 /**
941  * Create a socket for local communication and listen on it.
942  *
943  * \param name The socket pathname.
944  *
945  * This function creates a passive local socket for sequenced, reliable,
946  * two-way, connection-based byte streams. The socket file descriptor is set to
947  * nonblocking mode and listen(2) is called to prepare the socket for
948  * accepting incoming connection requests.
949  *
950  * \return The file descriptor on success, negative error code on failure.
951  *
952  * \sa socket(2), \sa bind(2), \sa chmod(2), listen(2), unix(7).
953  */
954 int create_local_socket(const char *name)
955 {
956         struct sockaddr_un unix_addr;
957         int fd, ret;
958
959         ret = init_unix_addr(&unix_addr, name);
960         if (ret <= 0) /* error, or name was NULL */
961                 return ret;
962         ret = socket(PF_UNIX, SOCK_STREAM, 0);
963         if (ret < 0)
964                 return -ERRNO_TO_PARA_ERROR(errno);
965         fd = ret;
966         ret = mark_fd_nonblocking(fd);
967         if (ret < 0)
968                 goto err;
969         ret = bind(fd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
970         if (ret < 0) {
971                 ret = -ERRNO_TO_PARA_ERROR(errno);
972                 goto err;
973         }
974         if (unix_addr.sun_path[0] != 0) { /* pathname socket */
975                 mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP
976                         | S_IROTH | S_IWOTH;
977                 ret = -E_CHMOD;
978                 if (chmod(name, mode) < 0)
979                         goto err;
980         }
981         if (listen(fd , 5) < 0) {
982                 ret = -ERRNO_TO_PARA_ERROR(errno);
983                 goto err;
984         }
985         return fd;
986 err:
987         close(fd);
988         return ret;
989 }
990
991 /**
992  * Prepare, create, and connect to a Unix domain socket for local communication.
993  *
994  * \param name The socket pathname.
995  *
996  * This function creates a local socket for sequenced, reliable, two-way,
997  * connection-based byte streams.
998  *
999  * \return The file descriptor of the connected socket on success, negative on
1000  * errors.
1001  *
1002  * \sa \ref create_local_socket(), unix(7), connect(2).
1003  */
1004 int connect_local_socket(const char *name)
1005 {
1006         struct sockaddr_un unix_addr;
1007         int fd, ret;
1008
1009         PARA_DEBUG_LOG("connecting to %s\n", name);
1010         fd = socket(PF_UNIX, SOCK_STREAM, 0);
1011         if (fd < 0)
1012                 return -ERRNO_TO_PARA_ERROR(errno);
1013         ret = init_unix_addr(&unix_addr, name);
1014         if (ret < 0)
1015                 goto err;
1016         if (connect(fd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) != -1)
1017                 return fd;
1018         ret = -ERRNO_TO_PARA_ERROR(errno);
1019 err:
1020         close(fd);
1021         return ret;
1022 }
1023
1024 #ifndef HAVE_UCRED
1025 ssize_t send_cred_buffer(int sock, char *buf)
1026 {
1027         return write_buffer(sock, buf);
1028 }
1029 int recv_cred_buffer(int fd, char *buf, size_t size)
1030 {
1031         return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
1032 }
1033 #else /* HAVE_UCRED */
1034
1035 /**
1036  * Send a buffer and the credentials of the current process to a socket.
1037  *
1038  * \param sock The file descriptor of the sending socket.
1039  * \param buf The zero-terminated buffer to send.
1040  *
1041  * \return On success, this call returns the number of bytes sent. On errors,
1042  * \p -E_SENDMSG is returned.
1043  *
1044  * \sa \ref recv_cred_buffer, sendmsg(2), socket(7), unix(7).
1045  */
1046 ssize_t send_cred_buffer(int sock, char *buf)
1047 {
1048         char control[sizeof(struct cmsghdr) + sizeof(struct ucred)];
1049         struct msghdr msg;
1050         struct cmsghdr *cmsg;
1051         static struct iovec iov;
1052         struct ucred c;
1053         int ret;
1054
1055         /* Response data */
1056         iov.iov_base = buf;
1057         iov.iov_len = strlen(buf);
1058         c.pid = getpid();
1059         c.uid = getuid();
1060         c.gid = getgid();
1061         /* compose the message */
1062         memset(&msg, 0, sizeof(msg));
1063         msg.msg_iov = &iov;
1064         msg.msg_iovlen = 1;
1065         msg.msg_control = control;
1066         msg.msg_controllen = sizeof(control);
1067         /* attach the ucred struct */
1068         cmsg = CMSG_FIRSTHDR(&msg);
1069         cmsg->cmsg_level = SOL_SOCKET;
1070         cmsg->cmsg_type = SCM_CREDENTIALS;
1071         cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
1072         *(struct ucred *)CMSG_DATA(cmsg) = c;
1073         msg.msg_controllen = cmsg->cmsg_len;
1074         ret = sendmsg(sock, &msg, 0);
1075         if (ret < 0)
1076                 ret = -E_SENDMSG;
1077         return ret;
1078 }
1079
1080 static void dispose_fds(int *fds, unsigned num)
1081 {
1082         int i;
1083
1084         for (i = 0; i < num; i++)
1085                 close(fds[i]);
1086 }
1087
1088 /**
1089  * Receive a buffer and the Unix credentials of the sending process.
1090  *
1091  * \param fd The file descriptor of the receiving socket.
1092  * \param buf The buffer to store the received message.
1093  * \param size The length of \a buf in bytes.
1094  *
1095  * \return Negative on errors, the user id of the sending process on success.
1096  *
1097  * \sa \ref send_cred_buffer and the references given there.
1098  */
1099 int recv_cred_buffer(int fd, char *buf, size_t size)
1100 {
1101         char control[255] __a_aligned(8);
1102         struct msghdr msg;
1103         struct cmsghdr *cmsg;
1104         struct iovec iov;
1105         int result = 0;
1106         int yes = 1;
1107         struct ucred cred;
1108
1109         setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
1110         memset(&msg, 0, sizeof(msg));
1111         memset(buf, 0, size);
1112         iov.iov_base = buf;
1113         iov.iov_len = size;
1114         msg.msg_iov = &iov;
1115         msg.msg_iovlen = 1;
1116         msg.msg_control = control;
1117         msg.msg_controllen = sizeof(control);
1118         if (recvmsg(fd, &msg, 0) < 0)
1119                 return -E_RECVMSG;
1120         result = -E_SCM_CREDENTIALS;
1121         cmsg = CMSG_FIRSTHDR(&msg);
1122         while (cmsg) {
1123                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
1124                                 == SCM_CREDENTIALS) {
1125                         memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
1126                         result = cred.uid;
1127                 } else
1128                         if (cmsg->cmsg_level == SOL_SOCKET
1129                                         && cmsg->cmsg_type == SCM_RIGHTS) {
1130                                 dispose_fds((int *)CMSG_DATA(cmsg),
1131                                         (cmsg->cmsg_len - CMSG_LEN(0))
1132                                         / sizeof(int));
1133                         }
1134                 cmsg = CMSG_NXTHDR(&msg, cmsg);
1135         }
1136         return result;
1137 }
1138 #endif /* HAVE_UCRED */