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