Merge branch 'maint'
[paraslash.git] / net.c
1 /*
2  * Copyright (C) 2005-2009 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 <dirent.h>
29 #include <regex.h>
30 #include <openssl/rc4.h>
31
32 #include "para.h"
33 #include "error.h"
34 #include "crypt.h"
35 #include "net.h"
36 #include "string.h"
37 #include "fd.h"
38
39 /**
40  * Parse and validate IPv4 address/netmask string.
41  *
42  * \param cidr    Address in CIDR notation
43  * \param addr    Copy of the IPv4 address part of \a cidr
44  * \param addrlen Size of \a addr in bytes
45  * \param netmask Value of the netmask part in \a cidr or the
46  *                default of 32 if not specified.
47  *
48  * \return Pointer to \a addr if succesful, NULL on error.
49  * \sa RFC 4632
50  */
51 char *parse_cidr(const char *cidr,
52                  char    *addr, ssize_t addrlen,
53                  int32_t *netmask)
54 {
55         const char *o = cidr;
56         char *c = addr, *end = c + (addrlen - 1);
57
58         *netmask = 0x20;
59
60         if (cidr == NULL || addrlen < 1)
61                 goto failed;
62
63         for (o = cidr; (*c = *o == '/'? '\0' : *o); c++, o++)
64                 if (c == end)
65                         goto failed;
66
67         if (*o == '/')
68                 if (para_atoi32(++o, netmask) < 0 ||
69                     *netmask < 0 || *netmask > 0x20)
70                         goto failed;
71
72         if (is_valid_ipv4_address(addr))
73                 return addr;
74 failed:
75         *addr = '\0';
76         return NULL;
77 }
78
79
80 /**
81  * Match string as a candidate IPv4 address.
82  *
83  * \param address The string to match.
84  * \return True if \a address has "dot-quad" format.
85  */
86 static bool is_v4_dot_quad(const char *address)
87 {
88         bool result;
89         regex_t r;
90
91         assert(para_regcomp(&r, "^([0-9]+\\.){3}[0-9]+$",
92                 REG_EXTENDED | REG_NOSUB) >= 0);
93         result = regexec(&r, address, 0, NULL, 0) == 0;
94         regfree(&r);
95         return result;
96 }
97
98 /**
99  * Perform basic syntax checking on the host-part of an URL:
100  *
101  * - Since ':' is invalid in IPv4 addresses and DNS names, the
102  *   presence of ':' causes interpretation as IPv6 address;
103  * - next the first-match-wins algorithm from RFC 3986 is applied;
104  * - else the string is considered as DNS name, to be resolved later.
105  *
106  * \param host The host string to check.
107  * \return True if \a host passes the syntax checks.
108  *
109  * \sa RFC 3986, 3.2.2; RFC 1123, 2.1; RFC 1034, 3.5
110  */
111 static bool host_string_ok(const char *host)
112 {
113         if (host == NULL || *host == '\0')
114                 return false;
115         if (strchr(host, ':') != NULL)
116                 return is_valid_ipv6_address(host);
117         if (is_v4_dot_quad(host))
118                 return is_valid_ipv4_address(host);
119         return true;
120 }
121
122 /**
123  * Parse and validate URL string.
124  *
125  * The URL syntax is loosely based on RFC 3986, supporting one of
126  * - "["host"]"[:port] for native IPv6 addresses and
127  * - host[:port] for IPv4 hostnames and DNS names.
128  *
129  * Native IPv6 addresses must be enclosed in square brackets, since
130  * otherwise there is an ambiguity with the port separator `:'.
131  * The 'port' part is always considered to be a number; if absent,
132  * it is set to -1, to indicate that a default port is to be used.
133  *
134  * The following are valid examples:
135  * - 10.10.1.1
136  * - 10.10.1.2:8000
137  * - localhost
138  * - localhost:8001
139  * - [::1]:8000
140  * - [badc0de::1]
141  *
142  * \param url     The URL string to take apart.
143  * \param host    To return the copied host part of \a url.
144  * \param hostlen The maximum length of \a host.
145  * \param port    To return the port number (if any) of \a url.
146  *
147  * \return Pointer to \a host, or NULL if failed.
148  * If NULL is returned, \a host and \a portnum are undefined. If no
149  * port number was present in \a url, \a portnum is set to -1.
150  *
151  * \sa RFC 3986, 3.2.2/3.2.3
152  */
153 char *parse_url(const char *url,
154                 char    *host, ssize_t hostlen,
155                 int32_t *port)
156 {
157         const char *o = url;
158         char *c = host, *end = c + (hostlen - 1);
159
160         *port = -1;
161
162         if (o == NULL || hostlen < 1)
163                 goto failed;
164
165         if (*o == '[') {
166                 for (++o; (*c = *o == ']' ? '\0' : *o); c++, o++)
167                         if (c == end)
168                                 goto failed;
169
170                 if (*o++ != ']' || (*o != '\0' && *o != ':'))
171                         goto failed;
172         } else {
173                 for (; (*c = *o == ':'? '\0' : *o); c++, o++)
174                         if (c == end)
175                                 goto failed;
176         }
177
178         if (*o == ':')
179                 if (para_atoi32(++o, port) < 0 ||
180                     *port < 0 || *port > 0xffff)
181                         goto failed;
182
183         if (host_string_ok(host))
184                 return host;
185 failed:
186         *host = '\0';
187         return NULL;
188 }
189
190 /**
191  * Determine the socket type for a given layer-4 protocol.
192  *
193  * \param l4type The symbolic name of the transport-layer protocol.
194  *
195  * \sa ip(7), socket(2)
196  */
197 static inline int sock_type(const unsigned l4type)
198 {
199         switch (l4type) {
200         case IPPROTO_UDP:       return SOCK_DGRAM;
201         case IPPROTO_TCP:       return SOCK_STREAM;
202         case IPPROTO_DCCP:      return SOCK_DCCP;
203         }
204         return -1;              /* not supported here */
205 }
206
207 /**
208  * Pretty-print transport-layer name.
209  */
210 static const char *layer4_name(const unsigned l4type)
211 {
212         switch (l4type) {
213         case IPPROTO_UDP:       return "UDP";
214         case IPPROTO_TCP:       return "TCP";
215         case IPPROTO_DCCP:      return "DCCP";
216         }
217         return "UNKNOWN PROTOCOL";
218 }
219
220 /**
221  * Resolve IPv4/IPv6 address and create a ready-to-use active or passive socket.
222  *
223  * \param l3type The layer-3 type (\p AF_INET, \p AF_INET6, \p AF_UNSPEC).
224  * \param l4type The layer-4 type (\p IPPROTO_xxx).
225  * \param passive Whether this is a passive (1) or active (0) socket.
226  * \param host Remote or local hostname or IPv/6 address string.
227  * \param port_number Decimal port number.
228  *
229  * This creates a ready-made IPv4/v6 socket structure after looking up the
230  * necessary parameters. The interpretation of \a host depends on the value of
231  * \a passive:
232  *      - on a passive socket host is interpreted as an interface IPv4/6 address
233  *        (can be left NULL);
234  *      - on an active socket, \a host is the peer DNS name or IPv4/6 address
235  *        to connect to;
236  *      - \a port_number is in either case the numeric port number (not service
237  *        string).
238  *
239  * Furthermore, bind(2) is called on passive sockets, and connect(2) on active
240  * sockets. The algorithm tries all possible address combinations until it
241  * succeeds.
242  *
243  * \return This function returns 1 on success and \a -E_ADDRESS_LOOKUP when no
244  * matching connection could be set up (with details in the error log).
245  *
246  *  \sa ipv6(7), getaddrinfo(3), bind(2), connect(2).
247  */
248 int makesock(unsigned l3type, unsigned l4type, int passive,
249                 const char *host, unsigned short port_number)
250 {
251         struct addrinfo *local = NULL, *src,
252                         *remote = NULL, *dst, hints;
253         int             rc, on = 1, sockfd = -1,
254                         socktype = sock_type(l4type);
255         char port[6]; /* port number has at most 5 digits */
256
257         sprintf(port, "%u", port_number);
258         /* Set up address hint structure */
259         memset(&hints, 0, sizeof(hints));
260         hints.ai_family = l3type;
261         hints.ai_socktype = socktype;
262         /* 
263          * getaddrinfo does not support SOCK_DCCP, so for the sake of lookup
264          * (and only then) pretend to be UDP.
265          */
266         if (l4type == IPPROTO_DCCP)
267                 hints.ai_socktype = SOCK_DGRAM;
268
269         /* only use addresses available on the host */
270         hints.ai_flags = AI_ADDRCONFIG;
271         if (l3type == AF_INET6)
272                 /* use v4-mapped-v6 if no v6 addresses found */
273                 hints.ai_flags |= AI_V4MAPPED | AI_ALL;
274
275         if (passive && host == NULL)
276                 hints.ai_flags |= AI_PASSIVE;
277
278         /* Obtain local/remote address information */
279         if ((rc = getaddrinfo(host, port, &hints, passive ? &local : &remote))) {
280                 PARA_ERROR_LOG("can not resolve %s address %s#%s: %s.\n",
281                                 layer4_name(l4type),
282                                 host? host : (passive? "[loopback]" : "[localhost]"),
283                                 port, gai_strerror(rc));
284                 return -E_ADDRESS_LOOKUP;
285         }
286
287         /* Iterate over all src/dst combination, exhausting dst first */
288         for (src = local, dst = remote; src != NULL || dst != NULL; /* no op */ ) {
289                 if (src && dst && src->ai_family == AF_INET
290                                 && dst->ai_family == AF_INET6)
291                         goto get_next_dst; /* v4 -> v6 is not possible */
292
293                 sockfd = socket(src ? src->ai_family : dst->ai_family,
294                         socktype, l4type);
295                 if (sockfd < 0)
296                         goto get_next_dst;
297
298                 /*
299                  * Set those options that need to be set before establishing
300                  * the connection. Reuse the address on passive (listening)
301                  * sockets to avoid failure on restart.
302                  */
303                 if (passive && setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
304                                 &on, sizeof(on)) == -1) {
305                         PARA_ERROR_LOG("can not set SO_REUSEADDR: %s\n",
306                                 strerror(errno));
307                         return -ERRNO_TO_PARA_ERROR(errno);
308                 }
309
310                 if (src) {
311                         if (bind(sockfd, src->ai_addr, src->ai_addrlen) < 0) {
312                                 close(sockfd);
313                                 goto get_next_src;
314                         }
315                         if (!dst) /* bind-only completed successfully */
316                                 break;
317                 }
318
319                 if (dst && connect(sockfd, dst->ai_addr, dst->ai_addrlen) == 0)
320                         break; /* connection completed successfully */
321                 close(sockfd);
322 get_next_dst:
323                 if (dst && (dst = dst->ai_next))
324                         continue;
325 get_next_src:
326                 if (src && (src = src->ai_next)) /* restart inner loop */
327                         dst = remote;
328         }
329         if (local)
330                 freeaddrinfo(local);
331         if (remote)
332                 freeaddrinfo(remote);
333
334         if (src == NULL && dst == NULL) {
335                 PARA_ERROR_LOG("can not create %s socket %s#%s.\n",
336                         layer4_name(l4type), host? host : (passive?
337                         "[loopback]" : "[localhost]"), port);
338                 return -ERRNO_TO_PARA_ERROR(errno);
339         }
340         return sockfd;
341 }
342
343 /**
344  * Create a passive / listening socket.
345  *
346  * \param l3type The network-layer type (\p AF_xxx).
347  * \param l4type The transport-layer type (\p IPPROTO_xxx).
348  * \param port The decimal port number to listen on.
349  *
350  * \return Positive integer (socket descriptor) on success, negative value
351  * otherwise.
352  *
353  * \sa makesock(), ip(7), ipv6(7), bind(2), listen(2).
354  */
355 int para_listen(unsigned l3type, unsigned l4type, unsigned short port)
356 {
357         int ret, fd = makesock(l3type, l4type, 1, NULL, port);
358
359         if (fd > 0) {
360                 ret = listen(fd, BACKLOG);
361                 if (ret < 0) {
362                         close(fd);
363                         return -ERRNO_TO_PARA_ERROR(errno);
364                 }
365                 PARA_INFO_LOG("listening on %s port %u, fd %d\n",
366                         layer4_name(l4type), port, fd);
367         }
368         return fd;
369 }
370
371 /**
372  * Print numeric host and port number (beware - uses static char).
373  *
374  * \param sa The IPv4/IPv6 socket address to use.
375  * \param len The length of \p sa.
376  *
377  * \sa getnameinfo(3).
378  */
379 static char *host_and_port(struct sockaddr *sa, socklen_t len)
380 {
381         static char output[NI_MAXHOST + NI_MAXSERV + 2];
382         char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
383         int ret;
384
385         ret = getnameinfo(sa, len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
386                 NI_NUMERICHOST | NI_NUMERICSERV);
387         if (ret) {
388                 PARA_WARNING_LOG("hostname lookup error (%s).\n",
389                         gai_strerror(ret));
390                 sprintf(output, "(unknown)");
391         } else
392                 sprintf(output, "%s#%s", hbuf, sbuf);
393         return output;
394 }
395
396 /**
397  * Look up the local or remote side of a connected socket structure.
398  *
399  * \param fd The socket descriptor of the connected socket.
400  * \param getname Either \p getsockname() for local, or \p getpeername() for
401  * remote side.
402  *
403  * \return A static character string identifying hostname and port of the
404  * chosen side.
405  *
406  * \sa getsockname(2), getpeername(2).
407  */
408 static char *__get_sock_name(int fd, int (*getname)(int, struct sockaddr*,
409                 socklen_t *))
410 {
411         struct sockaddr_storage ss;
412         socklen_t sslen = sizeof(ss);
413
414         if (getname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
415                 static char *dont_know = "(don't know)";
416                 PARA_ERROR_LOG("can not determine address from fd %d: %s\n",
417                         fd, strerror(errno));
418                 return dont_know;
419         }
420         return host_and_port((struct sockaddr *)&ss, sslen);
421 }
422
423 /**
424  * Look up the local side of a connected socket structure.
425  *
426  * \param sockfd The file descriptor of the socket.
427  *
428  * \return A pointer to a static buffer containing hostname an port. This
429  * buffer must not be freed by the caller.
430  *
431  * \sa remote_name().
432  */
433 char *local_name(int sockfd)
434 {
435         return __get_sock_name(sockfd, getsockname);
436 }
437
438 /**
439  * Look up the remote side of a connected socket structure.
440  *
441  * \param sockfd The file descriptor of the socket.
442  *
443  * \return Analogous to the return value of \ref local_name() but for the
444  * remote side.
445  *
446  * \sa local_name().
447  */
448 char *remote_name(int sockfd)
449 {
450         return __get_sock_name(sockfd, getpeername);
451 }
452
453 /**
454  * Extract IPv4 or IPv6-mapped-IPv4 address from sockaddr_storage.
455  * \param ss Container of IPv4/6 address
456  * \return Extracted IPv4 address (different from 0) or 0 if unsuccessful.
457  *
458  * \sa RFC 3493
459  */
460 struct in_addr extract_v4_addr(const struct sockaddr_storage *ss)
461 {
462         struct in_addr ia = {.s_addr = 0};
463
464         if (ss->ss_family == AF_INET)
465                 ia.s_addr = ((struct sockaddr_in *)ss)->sin_addr.s_addr;
466         if (ss->ss_family == AF_INET6) {
467                 const struct in6_addr v6_addr = ((struct sockaddr_in6 *)ss)->sin6_addr;
468
469                 if (IN6_IS_ADDR_V4MAPPED(&v6_addr))
470                         memcpy(&ia.s_addr, &(v6_addr.s6_addr[12]), 4);
471         }
472         return ia;
473 }
474
475 /**
476  * Send a binary buffer.
477  *
478  * \param fd The file descriptor.
479  * \param buf The buffer to be sent.
480  * \param len The length of \a buf.
481  *
482  * Send out the buffer and try to resend the remaining part in case of short
483  * writes.
484  *
485  * \return Standard.
486  */
487 int send_bin_buffer(int fd, const char *buf, size_t len)
488 {
489         if (!len)
490                 PARA_CRIT_LOG("len == 0\n");
491         return write_all(fd, buf, &len);
492 }
493
494 /**
495  * Send a \p NULL-terminated buffer.
496  *
497  * \param fd The file descriptor.
498  * \param buf The null-terminated buffer to be send.
499  *
500  * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
501  *
502  * \return Standard.
503  */
504 int send_buffer(int fd, const char *buf)
505 {
506         return send_bin_buffer(fd, buf, strlen(buf));
507 }
508
509 /**
510  * Send a buffer given by a format string.
511  *
512  * \param fd The file descriptor.
513  * \param fmt A format string.
514  *
515  * \return Standard.
516  */
517 __printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
518 {
519         char *msg;
520         int ret;
521
522         PARA_VSPRINTF(fmt, msg);
523         ret = send_buffer(fd, msg);
524         free(msg);
525         return ret;
526 }
527
528 /**
529  * Receive data from a file descriptor.
530  *
531  * \param fd The file descriptor.
532  * \param buf The buffer to write the data to.
533  * \param size The size of \a buf.
534  *
535  * Receive at most \a size bytes from file descriptor \a fd.
536  *
537  * \return The number of bytes received on success, negative on errors, zero if
538  * the peer has performed an orderly shutdown.
539  *
540  * \sa recv(2).
541  */
542 __must_check int recv_bin_buffer(int fd, char *buf, size_t size)
543 {
544         ssize_t n;
545
546         n = recv(fd, buf, size, 0);
547         if (n == -1)
548                 return -ERRNO_TO_PARA_ERROR(errno);
549         return n;
550 }
551
552 /**
553  * Receive and write terminating NULL byte.
554  *
555  * \param fd The file descriptor.
556  * \param buf The buffer to write the data to.
557  * \param size The size of \a buf.
558  *
559  * Read at most \a size - 1 bytes from file descriptor \a fd and
560  * write a NULL byte at the end of the received data.
561  *
562  * \return The return value of the underlying call to \a recv_bin_buffer().
563  *
564  * \sa recv_bin_buffer()
565  */
566 int recv_buffer(int fd, char *buf, size_t size)
567 {
568         int n;
569
570         assert(size);
571         n = recv_bin_buffer(fd, buf, size - 1);
572         if (n >= 0)
573                 buf[n] = '\0';
574         else
575                 *buf = '\0';
576         return n;
577 }
578
579 /**
580  * Wrapper around the accept system call.
581  *
582  * \param fd The listening socket.
583  * \param addr Structure which is filled in with the address of the peer socket.
584  * \param size Should contain the size of the structure pointed to by \a addr.
585  *
586  * Accept incoming connections on \a addr. Retry if interrupted.
587  *
588  * \return The new file descriptor on success, negative on errors.
589  *
590  * \sa accept(2).
591  */
592 int para_accept(int fd, void *addr, socklen_t size)
593 {
594         int new_fd;
595
596         do
597                 new_fd = accept(fd, (struct sockaddr *) addr, &size);
598         while (new_fd < 0 && errno == EINTR);
599         return new_fd < 0? -ERRNO_TO_PARA_ERROR(errno) : new_fd;
600 }
601
602 /**
603  * Prepare a structure for \p AF_UNIX socket addresses.
604  *
605  * \param u Pointer to the struct to be prepared.
606  * \param name The socket pathname.
607  *
608  * This just copies \a name to the sun_path component of \a u.
609  *
610  * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
611  * than \p UNIX_PATH_MAX.
612  */
613 static int init_unix_addr(struct sockaddr_un *u, const char *name)
614 {
615         if (strlen(name) >= UNIX_PATH_MAX)
616                 return -E_NAME_TOO_LONG;
617         memset(u->sun_path, 0, UNIX_PATH_MAX);
618         u->sun_family = PF_UNIX;
619         strcpy(u->sun_path, name);
620         return 1;
621 }
622
623 /**
624  * Prepare, create, and bind a socket for local communication.
625  *
626  * \param name The socket pathname.
627  * \param unix_addr Pointer to the \p AF_UNIX socket structure.
628  * \param mode The desired mode of the socket.
629  *
630  * This function creates a local socket for sequenced, reliable,
631  * two-way, connection-based byte streams.
632  *
633  * \return The file descriptor, on success, negative on errors.
634  *
635  * \sa socket(2)
636  * \sa bind(2)
637  * \sa chmod(2)
638  */
639 int create_local_socket(const char *name, struct sockaddr_un *unix_addr,
640                 mode_t mode)
641 {
642         int fd, ret;
643
644         ret = init_unix_addr(unix_addr, name);
645         if (ret < 0)
646                 return ret;
647         ret = socket(PF_UNIX, SOCK_STREAM, 0);
648         if (ret < 0)
649                 return -ERRNO_TO_PARA_ERROR(errno);
650         fd = ret;
651         ret = bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX);
652         if (ret < 0) {
653                 ret = -ERRNO_TO_PARA_ERROR(errno);
654                 goto err;
655         }
656         ret = -E_CHMOD;
657         if (chmod(name, mode) < 0)
658                 goto err;
659         return fd;
660 err:
661         close(fd);
662         return ret;
663 }
664
665 /**
666  * Prepare, create, and connect to a Unix domain socket for local communication.
667  *
668  * \param name The socket pathname.
669  *
670  * This function creates a local socket for sequenced, reliable, two-way,
671  * connection-based byte streams.
672  *
673  * \return The file descriptor, on success, negative on errors.
674  *
675  * \sa create_local_socket(), unix(7), connect(2).
676  */
677 int create_remote_socket(const char *name)
678 {
679         struct sockaddr_un unix_addr;
680         int fd, ret;
681
682         ret = init_unix_addr(&unix_addr, name);
683         if (ret < 0)
684                 return ret;
685         fd = socket(PF_UNIX, SOCK_STREAM, 0);
686         if (fd < 0)
687                 return -ERRNO_TO_PARA_ERROR(errno);
688         if (connect(fd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) == -1) {
689                 ret = -ERRNO_TO_PARA_ERROR(errno);
690                 goto err;
691         }
692         return fd;
693 err:
694         close(fd);
695         return ret;
696 }
697
698 #ifndef HAVE_UCRED
699 ssize_t send_cred_buffer(int sock, char *buf)
700 {
701         return send_buffer(sock, buf);
702 }
703 int recv_cred_buffer(int fd, char *buf, size_t size)
704 {
705         return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
706 }
707 #else /* HAVE_UCRED */
708 /**
709  * Send \p NULL-terminated buffer and Unix credentials of the current process.
710  *
711  * \param sock The socket file descriptor.
712  * \param buf The buffer to be sent.
713  *
714  * \return On success, this call returns the number of characters sent.  On
715  * error, \p -E_SENDMSG is returned.
716  *
717  * \sa sendmsg(2), okir's Black Hats Manual.
718  */
719 ssize_t send_cred_buffer(int sock, char *buf)
720 {
721         char control[sizeof(struct cmsghdr) + sizeof(struct ucred)];
722         struct msghdr msg;
723         struct cmsghdr *cmsg;
724         static struct iovec iov;
725         struct ucred c;
726         int ret;
727
728         /* Response data */
729         iov.iov_base = buf;
730         iov.iov_len  = strlen(buf);
731         c.pid = getpid();
732         c.uid = getuid();
733         c.gid = getgid();
734         /* compose the message */
735         memset(&msg, 0, sizeof(msg));
736         msg.msg_iov = &iov;
737         msg.msg_iovlen = 1;
738         msg.msg_control = control;
739         msg.msg_controllen = sizeof(control);
740         /* attach the ucred struct */
741         cmsg = CMSG_FIRSTHDR(&msg);
742         cmsg->cmsg_level = SOL_SOCKET;
743         cmsg->cmsg_type = SCM_CREDENTIALS;
744         cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
745         *(struct ucred *)CMSG_DATA(cmsg) = c;
746         msg.msg_controllen = cmsg->cmsg_len;
747         ret = sendmsg(sock, &msg, 0);
748         if (ret  < 0)
749                 ret = -E_SENDMSG;
750         return ret;
751 }
752
753 static void dispose_fds(int *fds, unsigned num)
754 {
755         int i;
756
757         for (i = 0; i < num; i++)
758                 close(fds[i]);
759 }
760
761 /**
762  * Receive a buffer and the Unix credentials of the sending process.
763  *
764  * \param fd the socket file descriptor.
765  * \param buf the buffer to store the message.
766  * \param size the size of \a buffer.
767  *
768  * \return negative on errors, the user id on success.
769  *
770  * \sa recvmsg(2), okir's Black Hats Manual.
771  */
772 int recv_cred_buffer(int fd, char *buf, size_t size)
773 {
774         char control[255];
775         struct msghdr msg;
776         struct cmsghdr *cmsg;
777         struct iovec iov;
778         int result = 0;
779         int yes = 1;
780         struct ucred cred;
781
782         setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
783         memset(&msg, 0, sizeof(msg));
784         memset(buf, 0, size);
785         iov.iov_base = buf;
786         iov.iov_len = size;
787         msg.msg_iov = &iov;
788         msg.msg_iovlen = 1;
789         msg.msg_control = control;
790         msg.msg_controllen = sizeof(control);
791         if (recvmsg(fd, &msg, 0) < 0)
792                 return -E_RECVMSG;
793         result = -E_SCM_CREDENTIALS;
794         cmsg = CMSG_FIRSTHDR(&msg);
795         while (cmsg) {
796                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
797                                 == SCM_CREDENTIALS) {
798                         memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
799                         result = cred.uid;
800                 } else
801                         if (cmsg->cmsg_level == SOL_SOCKET
802                                         && cmsg->cmsg_type == SCM_RIGHTS) {
803                                 dispose_fds((int *) CMSG_DATA(cmsg),
804                                         (cmsg->cmsg_len - CMSG_LEN(0))
805                                         / sizeof(int));
806                         }
807                 cmsg = CMSG_NXTHDR(&msg, cmsg);
808         }
809         return result;
810 }
811 #endif /* HAVE_UCRED */
812
813 /**
814  * Receive a buffer and check for a pattern.
815  *
816  * \param fd The file descriptor to receive from.
817  * \param pattern The expected pattern.
818  * \param bufsize The size of the internal buffer.
819  *
820  * \return Positive if \a pattern was received, negative otherwise.
821  *
822  * This function tries to receive at most \a bufsize bytes from file descriptor
823  * \a fd. If at least \p strlen(\a pattern) bytes were received, the beginning
824  * of the received buffer is compared with \a pattern, ignoring case.
825  *
826  * \sa recv_buffer(), \sa strncasecmp(3).
827  */
828 int recv_pattern(int fd, const char *pattern, size_t bufsize)
829 {
830         size_t len = strlen(pattern);
831         char *buf = para_malloc(bufsize + 1);
832         int ret = -E_RECV_PATTERN, n = recv_buffer(fd, buf, bufsize + 1);
833
834         if (n < len)
835                 goto out;
836         if (strncasecmp(buf, pattern, len))
837                 goto out;
838         ret = 1;
839 out:
840         if (ret < 0) {
841                 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n,
842                         pattern);
843                 if (n > 0)
844                         PARA_NOTICE_LOG("recvd: %s\n", buf);
845         }
846         free(buf);
847         return ret;
848 }