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