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