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