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