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