Merge commit 'meins/master'
[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 hints.ai_socktype = socktype;
161 /*
162 * getaddrinfo does not support SOCK_DCCP, so for the sake of lookup
163 * (and only then) pretend to be UDP.
164 */
165 if (l4type == IPPROTO_DCCP)
166 hints.ai_socktype = SOCK_DGRAM;
167
168 /* only use addresses available on the host */
169 hints.ai_flags = AI_ADDRCONFIG;
170 if (l3type == AF_INET6)
171 /* use v4-mapped-v6 if no v6 addresses found */
172 hints.ai_flags |= AI_V4MAPPED | AI_ALL;
173
174 if (passive && host == NULL)
175 hints.ai_flags |= AI_PASSIVE;
176
177 /* Obtain local/remote address information */
178 if ((rc = getaddrinfo(host, port, &hints, passive ? &local : &remote))) {
179 PARA_ERROR_LOG("can not resolve %s address %s#%s: %s.\n",
180 layer4_name(l4type),
181 host? host : (passive? "[loopback]" : "[localhost]"),
182 port, gai_strerror(rc));
183 return -E_ADDRESS_LOOKUP;
184 }
185
186 /* Iterate over all src/dst combination, exhausting dst first */
187 for (src = local, dst = remote; src != NULL || dst != NULL; /* no op */ ) {
188 if (src && dst && src->ai_family == AF_INET
189 && dst->ai_family == AF_INET6)
190 goto get_next_dst; /* v4 -> v6 is not possible */
191
192 sockfd = socket(src ? src->ai_family : dst->ai_family,
193 socktype, l4type);
194 if (sockfd < 0)
195 goto get_next_dst;
196
197 /*
198 * Set those options that need to be set before establishing
199 * the connection. Reuse the address on passive (listening)
200 * sockets to avoid failure on restart.
201 */
202 if (passive && setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
203 &on, sizeof(on)) == -1) {
204 PARA_ERROR_LOG("can not set SO_REUSEADDR: %s\n",
205 strerror(errno));
206 return -ERRNO_TO_PARA_ERROR(errno);
207 }
208
209 if (src) {
210 if (bind(sockfd, src->ai_addr, src->ai_addrlen) < 0) {
211 close(sockfd);
212 goto get_next_src;
213 }
214 if (!dst) /* bind-only completed successfully */
215 break;
216 }
217
218 if (dst && connect(sockfd, dst->ai_addr, dst->ai_addrlen) == 0)
219 break; /* connection completed successfully */
220 close(sockfd);
221 get_next_dst:
222 if (dst && (dst = dst->ai_next))
223 continue;
224 get_next_src:
225 if (src && (src = src->ai_next)) /* restart inner loop */
226 dst = remote;
227 }
228 if (local)
229 freeaddrinfo(local);
230 if (remote)
231 freeaddrinfo(remote);
232
233 if (src == NULL && dst == NULL) {
234 PARA_ERROR_LOG("can not create %s socket %s#%s.\n",
235 layer4_name(l4type), host? host : (passive?
236 "[loopback]" : "[localhost]"), port);
237 return -ERRNO_TO_PARA_ERROR(errno);
238 }
239 return sockfd;
240 }
241
242 /**
243 * Create a passive / listening socket.
244 *
245 * \param l3type The network-layer type (\p AF_xxx).
246 * \param l4type The transport-layer type (\p IPPROTO_xxx).
247 * \param port The decimal port number to listen on.
248 *
249 * \return Positive integer (socket descriptor) on success, negative value
250 * otherwise.
251 *
252 * \sa makesock(), ip(7), ipv6(7), bind(2), listen(2).
253 */
254 int para_listen(unsigned l3type, unsigned l4type, unsigned short port)
255 {
256 int ret, fd = makesock(l3type, l4type, 1, NULL, port);
257
258 if (fd > 0) {
259 ret = listen(fd, BACKLOG);
260 if (ret < 0) {
261 close(fd);
262 return -ERRNO_TO_PARA_ERROR(errno);
263 }
264 PARA_INFO_LOG("listening on %s port %u, fd %d\n",
265 layer4_name(l4type), port, fd);
266 }
267 return fd;
268 }
269
270 /**
271 * Print numeric host and port number (beware - uses static char).
272 *
273 * \param sa The IPv4/IPv6 socket address to use.
274 * \param len The length of \p sa.
275 *
276 * \sa getnameinfo(3).
277 */
278 static char *host_and_port(struct sockaddr *sa, socklen_t len)
279 {
280 static char output[NI_MAXHOST + NI_MAXSERV + 2];
281 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
282 int ret;
283
284 ret = getnameinfo(sa, len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
285 NI_NUMERICHOST | NI_NUMERICSERV);
286 if (ret) {
287 PARA_WARNING_LOG("hostname lookup error (%s).\n",
288 gai_strerror(ret));
289 sprintf(output, "(unknown)");
290 } else
291 sprintf(output, "%s#%s", hbuf, sbuf);
292 return output;
293 }
294
295 /**
296 * Look up the local or remote side of a connected socket structure.
297 *
298 * \param fd The socket descriptor of the connected socket.
299 * \param getname Either \p getsockname() for local, or \p getpeername() for
300 * remote side.
301 *
302 * \return A static character string identifying hostname and port of the
303 * chosen side.
304 *
305 * \sa getsockname(2), getpeername(2).
306 */
307 static char *__get_sock_name(int fd, int (*getname)(int, struct sockaddr*,
308 socklen_t *))
309 {
310 struct sockaddr_storage ss;
311 socklen_t sslen = sizeof(ss);
312
313 if (getname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
314 static char *dont_know = "(don't know)";
315 PARA_ERROR_LOG("can not determine address from fd %d: %s\n",
316 fd, strerror(errno));
317 return dont_know;
318 }
319 return host_and_port((struct sockaddr *)&ss, sslen);
320 }
321
322 char *local_name(int sockfd)
323 {
324 return __get_sock_name(sockfd, getsockname);
325 }
326
327 char *remote_name(int sockfd)
328 {
329 return __get_sock_name(sockfd, getpeername);
330 }
331
332 /**
333 * Extract IPv4 or IPv6-mapped-IPv4 address from sockaddr_storage.
334 * \param ss Container of IPv4/6 address
335 * \return Extracted IPv4 address (different from 0) or 0 if unsuccessful.
336 *
337 * \sa RFC 3493
338 */
339 struct in_addr extract_v4_addr(const struct sockaddr_storage *ss)
340 {
341 struct in_addr ia = {.s_addr = 0};
342
343 if (ss->ss_family == AF_INET)
344 ia.s_addr = ((struct sockaddr_in *)ss)->sin_addr.s_addr;
345 if (ss->ss_family == AF_INET6) {
346 const struct in6_addr v6_addr = ((struct sockaddr_in6 *)ss)->sin6_addr;
347
348 if (IN6_IS_ADDR_V4MAPPED(&v6_addr))
349 memcpy(&ia.s_addr, &(v6_addr.s6_addr[12]), 4);
350 }
351 return ia;
352 }
353
354 /**
355 * Encrypt and send a binary buffer.
356 *
357 * \param fd The file descriptor.
358 * \param buf The buffer to be encrypted and sent.
359 * \param len The length of \a buf.
360 *
361 * Check if encryption is available. If yes, encrypt the given buffer. Send
362 * out the buffer, encrypted or not, and try to resend the remaing part in case
363 * of short writes.
364 *
365 * \return Standard.
366 */
367 int send_bin_buffer(int fd, const char *buf, size_t len)
368 {
369 int ret;
370 crypt_function *cf = NULL;
371
372 if (!len)
373 PARA_CRIT_LOG("len == 0\n");
374 if (fd + 1 <= cda_size)
375 cf = crypt_data_array[fd].send;
376 if (cf) {
377 void *private = crypt_data_array[fd].private_data;
378 /* RC4 may write more than len to the output buffer */
379 unsigned char *outbuf = para_malloc(ROUND_UP(len, 8));
380 (*cf)(len, (unsigned char *)buf, outbuf, private);
381 ret = write_all(fd, (char *)outbuf, &len);
382 free(outbuf);
383 } else
384 ret = write_all(fd, buf, &len);
385 return ret;
386 }
387
388 /**
389 * Encrypt and send null terminated buffer.
390 *
391 * \param fd The file descriptor.
392 * \param buf The null-terminated buffer to be send.
393 *
394 * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
395 *
396 * \return Standard.
397 */
398 int send_buffer(int fd, const char *buf)
399 {
400 return send_bin_buffer(fd, buf, strlen(buf));
401 }
402
403
404 /**
405 * Send and encrypt a buffer given by a format string.
406 *
407 * \param fd The file descriptor.
408 * \param fmt A format string.
409 *
410 * \return Standard.
411 */
412 __printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
413 {
414 char *msg;
415 int ret;
416
417 PARA_VSPRINTF(fmt, msg);
418 ret = send_buffer(fd, msg);
419 free(msg);
420 return ret;
421 }
422
423 /**
424 * Receive and decrypt.
425 *
426 * \param fd The file descriptor.
427 * \param buf The buffer to write the decrypted data to.
428 * \param size The size of \a buf.
429 *
430 * Receive at most \a size bytes from file descriptor \a fd. If encryption is
431 * available, decrypt the received buffer.
432 *
433 * \return The number of bytes received on success, negative on errors.
434 *
435 * \sa recv(2)
436 */
437 __must_check int recv_bin_buffer(int fd, char *buf, size_t size)
438 {
439 ssize_t n;
440 crypt_function *cf = NULL;
441
442 if (fd + 1 <= cda_size)
443 cf = crypt_data_array[fd].recv;
444 if (cf) {
445 unsigned char *tmp = para_malloc(size);
446 void *private = crypt_data_array[fd].private_data;
447 n = recv(fd, tmp, size, 0);
448 if (n > 0) {
449 size_t numbytes = n;
450 unsigned char *b = (unsigned char *)buf;
451 (*cf)(numbytes, tmp, b, private);
452 }
453 free(tmp);
454 } else
455 n = recv(fd, buf, size, 0);
456 if (n == -1)
457 return -ERRNO_TO_PARA_ERROR(errno);
458 return n;
459 }
460
461 /**
462 * Receive, decrypt and write terminating NULL byte.
463 *
464 * \param fd The file descriptor.
465 * \param buf The buffer to write the decrypted data to.
466 * \param size The size of \a buf.
467 *
468 * Read and decrypt at most \a size - 1 bytes from file descriptor \a fd and
469 * write a NULL byte at the end of the received data.
470 *
471 * \return The return value of the underlying call to \a recv_bin_buffer().
472 *
473 * \sa recv_bin_buffer()
474 */
475 int recv_buffer(int fd, char *buf, size_t size)
476 {
477 int n;
478
479 assert(size);
480 n = recv_bin_buffer(fd, buf, size - 1);
481 if (n >= 0)
482 buf[n] = '\0';
483 else
484 *buf = '\0';
485 return n;
486 }
487
488 /**
489 * Wrapper around the accept system call.
490 *
491 * \param fd The listening socket.
492 * \param addr Structure which is filled in with the address of the peer socket.
493 * \param size Should contain the size of the structure pointed to by \a addr.
494 *
495 * Accept incoming connections on \a addr. Retry if interrupted.
496 *
497 * \return The new file descriptor on success, negative on errors.
498 *
499 * \sa accept(2).
500 */
501 int para_accept(int fd, void *addr, socklen_t size)
502 {
503 int new_fd;
504
505 do
506 new_fd = accept(fd, (struct sockaddr *) addr, &size);
507 while (new_fd < 0 && errno == EINTR);
508 return new_fd < 0? -ERRNO_TO_PARA_ERROR(errno) : new_fd;
509 }
510
511 /**
512 * Prepare a structure for \p AF_UNIX socket addresses.
513 *
514 * \param u Pointer to the struct to be prepared.
515 * \param name The socket pathname.
516 *
517 * This just copies \a name to the sun_path component of \a u.
518 *
519 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
520 * than \p UNIX_PATH_MAX.
521 */
522 static int init_unix_addr(struct sockaddr_un *u, const char *name)
523 {
524 if (strlen(name) >= UNIX_PATH_MAX)
525 return -E_NAME_TOO_LONG;
526 memset(u->sun_path, 0, UNIX_PATH_MAX);
527 u->sun_family = PF_UNIX;
528 strcpy(u->sun_path, name);
529 return 1;
530 }
531
532 /**
533 * Prepare, create, and bind a socket for local communication.
534 *
535 * \param name The socket pathname.
536 * \param unix_addr Pointer to the \p AF_UNIX socket structure.
537 * \param mode The desired mode of the socket.
538 *
539 * This function creates a local socket for sequenced, reliable,
540 * two-way, connection-based byte streams.
541 *
542 * \return The file descriptor, on success, negative on errors.
543 *
544 * \sa socket(2)
545 * \sa bind(2)
546 * \sa chmod(2)
547 */
548 int create_local_socket(const char *name, struct sockaddr_un *unix_addr,
549 mode_t mode)
550 {
551 int fd, ret;
552
553 ret = init_unix_addr(unix_addr, name);
554 if (ret < 0)
555 return ret;
556 ret = socket(PF_UNIX, SOCK_STREAM, 0);
557 if (ret < 0)
558 return -ERRNO_TO_PARA_ERROR(errno);
559 fd = ret;
560 ret = bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX);
561 if (ret < 0) {
562 ret = -ERRNO_TO_PARA_ERROR(errno);
563 goto err;
564 }
565 ret = -E_CHMOD;
566 if (chmod(name, mode) < 0)
567 goto err;
568 return fd;
569 err:
570 close(fd);
571 return ret;
572 }
573
574 /**
575 * Prepare, create, and connect to a Unix domain socket for local communication.
576 *
577 * \param name The socket pathname.
578 *
579 * This function creates a local socket for sequenced, reliable, two-way,
580 * connection-based byte streams.
581 *
582 * \return The file descriptor, on success, negative on errors.
583 *
584 * \sa create_local_socket(), unix(7), connect(2).
585 */
586 int create_remote_socket(const char *name)
587 {
588 struct sockaddr_un unix_addr;
589 int fd, ret;
590
591 ret = init_unix_addr(&unix_addr, name);
592 if (ret < 0)
593 return ret;
594 fd = socket(PF_UNIX, SOCK_STREAM, 0);
595 if (fd < 0)
596 return -ERRNO_TO_PARA_ERROR(errno);
597 if (connect(fd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) == -1) {
598 ret = -ERRNO_TO_PARA_ERROR(errno);
599 goto err;
600 }
601 return fd;
602 err:
603 close(fd);
604 return ret;
605 }
606
607 #ifndef HAVE_UCRED
608 ssize_t send_cred_buffer(int sock, char *buf)
609 {
610 return send_buffer(sock, buf);
611 }
612 int recv_cred_buffer(int fd, char *buf, size_t size)
613 {
614 return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
615 }
616 #else /* HAVE_UCRED */
617 /**
618 * Send \p NULL-terminated buffer and Unix credentials of the current process.
619 *
620 * \param sock The socket file descriptor.
621 * \param buf The buffer to be sent.
622 *
623 * \return On success, this call returns the number of characters sent. On
624 * error, \p -E_SENDMSG is returned.
625 *
626 * \sa sendmsg(2), okir's Black Hats Manual.
627 */
628 ssize_t send_cred_buffer(int sock, char *buf)
629 {
630 char control[sizeof(struct cmsghdr) + 10];
631 struct msghdr msg;
632 struct cmsghdr *cmsg;
633 static struct iovec iov;
634 struct ucred c;
635 int ret;
636
637 /* Response data */
638 iov.iov_base = buf;
639 iov.iov_len = strlen(buf);
640 c.pid = getpid();
641 c.uid = getuid();
642 c.gid = getgid();
643 /* compose the message */
644 memset(&msg, 0, sizeof(msg));
645 msg.msg_iov = &iov;
646 msg.msg_iovlen = 1;
647 msg.msg_control = control;
648 msg.msg_controllen = sizeof(control);
649 /* attach the ucred struct */
650 cmsg = CMSG_FIRSTHDR(&msg);
651 cmsg->cmsg_level = SOL_SOCKET;
652 cmsg->cmsg_type = SCM_CREDENTIALS;
653 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
654 *(struct ucred *)CMSG_DATA(cmsg) = c;
655 msg.msg_controllen = cmsg->cmsg_len;
656 ret = sendmsg(sock, &msg, 0);
657 if (ret < 0)
658 ret = -E_SENDMSG;
659 return ret;
660 }
661
662 static void dispose_fds(int *fds, unsigned num)
663 {
664 int i;
665
666 for (i = 0; i < num; i++)
667 close(fds[i]);
668 }
669
670 /**
671 * Receive a buffer and the Unix credentials of the sending process.
672 *
673 * \param fd the socket file descriptor.
674 * \param buf the buffer to store the message.
675 * \param size the size of \a buffer.
676 *
677 * \return negative on errors, the user id on success.
678 *
679 * \sa recvmsg(2), okir's Black Hats Manual.
680 */
681 int recv_cred_buffer(int fd, char *buf, size_t size)
682 {
683 char control[255];
684 struct msghdr msg;
685 struct cmsghdr *cmsg;
686 struct iovec iov;
687 int result = 0;
688 int yes = 1;
689 struct ucred cred;
690
691 setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
692 memset(&msg, 0, sizeof(msg));
693 memset(buf, 0, size);
694 iov.iov_base = buf;
695 iov.iov_len = size;
696 msg.msg_iov = &iov;
697 msg.msg_iovlen = 1;
698 msg.msg_control = control;
699 msg.msg_controllen = sizeof(control);
700 if (recvmsg(fd, &msg, 0) < 0)
701 return -E_RECVMSG;
702 result = -E_SCM_CREDENTIALS;
703 cmsg = CMSG_FIRSTHDR(&msg);
704 while (cmsg) {
705 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
706 == SCM_CREDENTIALS) {
707 memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
708 result = cred.uid;
709 } else
710 if (cmsg->cmsg_level == SOL_SOCKET
711 && cmsg->cmsg_type == SCM_RIGHTS) {
712 dispose_fds((int *) CMSG_DATA(cmsg),
713 (cmsg->cmsg_len - CMSG_LEN(0))
714 / sizeof(int));
715 }
716 cmsg = CMSG_NXTHDR(&msg, cmsg);
717 }
718 return result;
719 }
720 #endif /* HAVE_UCRED */
721
722 /**
723 * Receive a buffer and check for a pattern.
724 *
725 * \param fd The file descriptor to receive from.
726 * \param pattern The expected pattern.
727 * \param bufsize The size of the internal buffer.
728 *
729 * \return Positive if \a pattern was received, negative otherwise.
730 *
731 * This function creates a buffer of size \a bufsize and tries
732 * to receive at most \a bufsize bytes from file descriptor \a fd.
733 * If at least \p strlen(\a pattern) bytes were received, the beginning of
734 * the received buffer is compared with \a pattern, ignoring case.
735 *
736 * \sa recv_buffer(), \sa strncasecmp(3).
737 */
738 int recv_pattern(int fd, const char *pattern, size_t bufsize)
739 {
740 size_t len = strlen(pattern);
741 char *buf = para_malloc(bufsize + 1);
742 int ret = -E_RECV_PATTERN, n = recv_buffer(fd, buf, bufsize);
743
744 if (n < len)
745 goto out;
746 if (strncasecmp(buf, pattern, len))
747 goto out;
748 ret = 1;
749 out:
750 if (ret < 0) {
751 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n,
752 pattern);
753 if (n > 0)
754 PARA_NOTICE_LOG("recvd: %s\n", buf);
755 }
756 free(buf);
757 return ret;
758 }