Rename struct rc4_context and stream cipher send/receive functions.
[paraslash.git] / net.c
1 /*
2 * Copyright (C) 2005-2011 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 "list.h"
36 #include "fd.h"
37
38 /**
39 * Parse and validate IPv4 address/netmask string.
40 *
41 * \param cidr Address in CIDR notation
42 * \param addr Copy of the IPv4 address part of \a cidr
43 * \param addrlen Size of \a addr in bytes
44 * \param netmask Value of the netmask part in \a cidr or the
45 * default of 32 if not specified.
46 *
47 * \return Pointer to \a addr if succesful, NULL on error.
48 * \sa RFC 4632
49 */
50 char *parse_cidr(const char *cidr,
51 char *addr, ssize_t addrlen,
52 int32_t *netmask)
53 {
54 const char *o = cidr;
55 char *c = addr, *end = c + (addrlen - 1);
56
57 *netmask = 0x20;
58
59 if (cidr == NULL || addrlen < 1)
60 goto failed;
61
62 for (o = cidr; (*c = *o == '/'? '\0' : *o); c++, o++)
63 if (c == end)
64 goto failed;
65
66 if (*o == '/')
67 if (para_atoi32(++o, netmask) < 0 ||
68 *netmask < 0 || *netmask > 0x20)
69 goto failed;
70
71 if (is_valid_ipv4_address(addr))
72 return addr;
73 failed:
74 *addr = '\0';
75 return NULL;
76 }
77
78
79 /**
80 * Match string as a candidate IPv4 address.
81 *
82 * \param address The string to match.
83 * \return True if \a address has "dot-quad" format.
84 */
85 static bool is_v4_dot_quad(const char *address)
86 {
87 bool result;
88 regex_t r;
89
90 assert(para_regcomp(&r, "^([0-9]+\\.){3}[0-9]+$",
91 REG_EXTENDED | REG_NOSUB) >= 0);
92 result = regexec(&r, address, 0, NULL, 0) == 0;
93 regfree(&r);
94 return result;
95 }
96
97 /**
98 * Perform basic syntax checking on the host-part of an URL:
99 *
100 * - Since ':' is invalid in IPv4 addresses and DNS names, the
101 * presence of ':' causes interpretation as IPv6 address;
102 * - next the first-match-wins algorithm from RFC 3986 is applied;
103 * - else the string is considered as DNS name, to be resolved later.
104 *
105 * \param host The host string to check.
106 * \return True if \a host passes the syntax checks.
107 *
108 * \sa RFC 3986, 3.2.2; RFC 1123, 2.1; RFC 1034, 3.5
109 */
110 static bool host_string_ok(const char *host)
111 {
112 if (host == NULL || *host == '\0')
113 return false;
114 if (strchr(host, ':') != NULL)
115 return is_valid_ipv6_address(host);
116 if (is_v4_dot_quad(host))
117 return is_valid_ipv4_address(host);
118 return true;
119 }
120
121 /**
122 * Parse and validate URL string.
123 *
124 * The URL syntax is loosely based on RFC 3986, supporting one of
125 * - "["host"]"[:port] for native IPv6 addresses and
126 * - host[:port] for IPv4 hostnames and DNS names.
127 *
128 * Native IPv6 addresses must be enclosed in square brackets, since
129 * otherwise there is an ambiguity with the port separator `:'.
130 * The 'port' part is always considered to be a number; if absent,
131 * it is set to -1, to indicate that a default port is to be used.
132 *
133 * The following are valid examples:
134 * - 10.10.1.1
135 * - 10.10.1.2:8000
136 * - localhost
137 * - localhost:8001
138 * - [::1]:8000
139 * - [badc0de::1]
140 *
141 * \param url The URL string to take apart.
142 * \param host To return the copied host part of \a url.
143 * \param hostlen The maximum length of \a host.
144 * \param port To return the port number (if any) of \a url.
145 *
146 * \return Pointer to \a host, or NULL if failed.
147 * If NULL is returned, \a host and \a portnum are undefined. If no
148 * port number was present in \a url, \a portnum is set to -1.
149 *
150 * \sa RFC 3986, 3.2.2/3.2.3
151 */
152 char *parse_url(const char *url,
153 char *host, ssize_t hostlen,
154 int32_t *port)
155 {
156 const char *o = url;
157 char *c = host, *end = c + (hostlen - 1);
158
159 *port = -1;
160
161 if (o == NULL || hostlen < 1)
162 goto failed;
163
164 if (*o == '[') {
165 for (++o; (*c = *o == ']' ? '\0' : *o); c++, o++)
166 if (c == end)
167 goto failed;
168
169 if (*o++ != ']' || (*o != '\0' && *o != ':'))
170 goto failed;
171 } else {
172 for (; (*c = *o == ':'? '\0' : *o); c++, o++)
173 if (c == end)
174 goto failed;
175 }
176
177 if (*o == ':')
178 if (para_atoi32(++o, port) < 0 ||
179 *port < 0 || *port > 0xffff)
180 goto failed;
181
182 if (host_string_ok(host))
183 return host;
184 failed:
185 *host = '\0';
186 return NULL;
187 }
188
189 /**
190 * Stringify port number, resolve into service name where defined.
191 * \param port 2-byte port number, in host-byte-order.
192 * \param transport Transport protocol name (e.g. "udp", "tcp"), or NULL.
193 * \return Pointer to static result buffer.
194 *
195 * \sa getservent(3), services(5), nsswitch.conf(5)
196 */
197 const char *stringify_port(int port, const char *transport)
198 {
199 static char service[NI_MAXSERV];
200
201 if (port < 0 || port > 0xFFFF) {
202 snprintf(service, sizeof(service), "undefined (%d)", port);
203 } else {
204 struct servent *se = getservbyport(htons(port), transport);
205
206 if (se == NULL)
207 snprintf(service, sizeof(service), "%u", port);
208 else
209 snprintf(service, sizeof(service), "%s", se->s_name);
210 }
211 return service;
212 }
213
214 /**
215 * Determine the socket type for a given layer-4 protocol.
216 *
217 * \param l4type The symbolic name of the transport-layer protocol.
218 *
219 * \sa ip(7), socket(2)
220 */
221 static inline int sock_type(const unsigned l4type)
222 {
223 switch (l4type) {
224 case IPPROTO_UDP: return SOCK_DGRAM;
225 case IPPROTO_TCP: return SOCK_STREAM;
226 case IPPROTO_DCCP: return SOCK_DCCP;
227 }
228 return -1; /* not supported here */
229 }
230
231 /**
232 * Pretty-print transport-layer name.
233 */
234 static const char *layer4_name(const unsigned l4type)
235 {
236 switch (l4type) {
237 case IPPROTO_UDP: return "UDP";
238 case IPPROTO_TCP: return "TCP";
239 case IPPROTO_DCCP: return "DCCP";
240 }
241 return "UNKNOWN PROTOCOL";
242 }
243
244 /**
245 * Flowopts: Transport-layer independent encapsulation of socket options.
246 *
247 * These collect individual socket options into a queue, which is disposed of
248 * directly after makesock(). The 'pre_conn_opt' structure is for internal use
249 * only and should not be visible elsewhere.
250 *
251 * \sa setsockopt(2), makesock()
252 */
253 struct pre_conn_opt {
254 int sock_level; /**< Second argument to setsockopt() */
255 int sock_option; /**< Third argument to setsockopt() */
256 char *opt_name; /**< Stringified \a sock_option */
257 void *opt_val; /**< Fourth argument to setsockopt() */
258 socklen_t opt_len; /**< Fifth argument to setsockopt() */
259
260 struct list_head node; /**< FIFO, as sockopt order matters. */
261 };
262
263 /** FIFO list of pre-connection socket options to be set */
264 struct flowopts {
265 struct list_head sockopts;
266 };
267
268 struct flowopts *flowopt_new(void)
269 {
270 struct flowopts *new = para_malloc(sizeof(*new));
271
272 INIT_LIST_HEAD(&new->sockopts);
273 return new;
274 }
275
276 /**
277 * Append new socket option to flowopt queue.
278 *
279 * \param fo The flowopt queue to append to.
280 * \param lev Level at which \a opt resides.
281 * \param opt New option to add.
282 * \param name Stringified name of \a opt.
283 * \param val The value to set \a opt to.
284 * \param len Length of \a val.
285 *
286 * \sa setsockopt(2)
287 */
288 void flowopt_add(struct flowopts *fo, int lev, int opt,
289 char *name, const void *val, int len)
290 {
291 struct pre_conn_opt *new = para_malloc(sizeof(*new));
292
293 new->sock_option = opt;
294 new->sock_level = lev;
295 new->opt_name = para_strdup(name);
296
297 if (val == NULL) {
298 new->opt_val = NULL;
299 new->opt_len = 0;
300 } else {
301 new->opt_val = para_malloc(len);
302 new->opt_len = len;
303 memcpy(new->opt_val, val, len);
304 }
305
306 list_add_tail(&new->node, &fo->sockopts);
307 }
308
309 void flowopt_add_bool(struct flowopts *fo, int lev, int opt,
310 char *optname, bool on_or_off)
311 {
312 int on = on_or_off; /* kernel takes 'int' */
313
314 flowopt_add(fo, lev, opt, optname, &on, sizeof(on));
315 }
316
317 /** Set the entire bunch of pre-connection options at once. */
318 static void flowopt_setopts(int sockfd, struct flowopts *fo)
319 {
320 struct pre_conn_opt *pc;
321
322 if (fo == NULL)
323 return;
324
325 list_for_each_entry(pc, &fo->sockopts, node)
326 if (setsockopt(sockfd, pc->sock_level, pc->sock_option,
327 pc->opt_val, pc->opt_len) < 0) {
328 PARA_EMERG_LOG("Can not set %s socket option: %s",
329 pc->opt_name, strerror(errno));
330 exit(EXIT_FAILURE);
331 }
332 }
333
334 static void flowopt_cleanup(struct flowopts *fo)
335 {
336 struct pre_conn_opt *cur, *next;
337
338 if (fo == NULL)
339 return;
340
341 list_for_each_entry_safe(cur, next, &fo->sockopts, node) {
342 free(cur->opt_name);
343 free(cur->opt_val);
344 free(cur);
345 }
346 free(fo);
347 }
348
349 /**
350 * Resolve IPv4/IPv6 address and create a ready-to-use active or passive socket.
351 *
352 * \param l4type The layer-4 type (\p IPPROTO_xxx).
353 * \param passive Whether this is a passive (1) or active (0) socket.
354 * \param host Remote or local hostname or IPv/6 address string.
355 * \param port_number Decimal port number.
356 * \param fo Socket options to be set before making the connection.
357 *
358 * This creates a ready-made IPv4/v6 socket structure after looking up the
359 * necessary parameters. The interpretation of \a host depends on the value of
360 * \a passive:
361 * - on a passive socket host is interpreted as an interface IPv4/6 address
362 * (can be left NULL);
363 * - on an active socket, \a host is the peer DNS name or IPv4/6 address
364 * to connect to;
365 * - \a port_number is in either case the numeric port number (not service
366 * string).
367 *
368 * Furthermore, bind(2) is called on passive sockets, and connect(2) on active
369 * sockets. The algorithm tries all possible address combinations until it
370 * succeeds. If \a fo is supplied, options are set and cleanup is performed.
371 *
372 * \return This function returns 1 on success and \a -E_ADDRESS_LOOKUP when no
373 * matching connection could be set up (with details in the error log).
374 *
375 * \sa ipv6(7), getaddrinfo(3), bind(2), connect(2).
376 */
377 int makesock(unsigned l4type, bool passive,
378 const char *host, uint16_t port_number,
379 struct flowopts *fo)
380 {
381 struct addrinfo *local = NULL, *src = NULL, *remote = NULL,
382 *dst = NULL, hints;
383 unsigned int l3type = AF_UNSPEC;
384 int rc, on = 1, sockfd = -1,
385 socktype = sock_type(l4type);
386 char port[6]; /* port number has at most 5 digits */
387
388 sprintf(port, "%u", port_number);
389 /* Set up address hint structure */
390 memset(&hints, 0, sizeof(hints));
391 hints.ai_family = l3type;
392 hints.ai_socktype = socktype;
393 /*
394 * getaddrinfo does not support SOCK_DCCP, so for the sake of lookup
395 * (and only then) pretend to be UDP.
396 */
397 if (l4type == IPPROTO_DCCP)
398 hints.ai_socktype = SOCK_DGRAM;
399
400 /* only use addresses available on the host */
401 hints.ai_flags = AI_ADDRCONFIG;
402 if (l3type == AF_INET6)
403 /* use v4-mapped-v6 if no v6 addresses found */
404 hints.ai_flags |= AI_V4MAPPED | AI_ALL;
405
406 if (passive && host == NULL)
407 hints.ai_flags |= AI_PASSIVE;
408
409 /* Obtain local/remote address information */
410 if ((rc = getaddrinfo(host, port, &hints, passive ? &local : &remote))) {
411 PARA_ERROR_LOG("can not resolve %s address %s#%s: %s.\n",
412 layer4_name(l4type),
413 host? host : (passive? "[loopback]" : "[localhost]"),
414 port, gai_strerror(rc));
415 rc = -E_ADDRESS_LOOKUP;
416 goto out;
417 }
418
419 /* Iterate over all src/dst combination, exhausting dst first */
420 for (src = local, dst = remote; src != NULL || dst != NULL; /* no op */ ) {
421 if (src && dst && src->ai_family == AF_INET
422 && dst->ai_family == AF_INET6)
423 goto get_next_dst; /* v4 -> v6 is not possible */
424
425 sockfd = socket(src ? src->ai_family : dst->ai_family,
426 socktype, l4type);
427 if (sockfd < 0)
428 goto get_next_dst;
429
430 /*
431 * Reuse the address on passive sockets to avoid failure on
432 * restart (protocols using listen()) and when creating
433 * multiple listener instances (UDP multicast).
434 */
435 if (passive && setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
436 &on, sizeof(on)) == -1) {
437 rc = errno;
438 close(sockfd);
439 PARA_ERROR_LOG("can not set SO_REUSEADDR: %s\n",
440 strerror(rc));
441 rc = -ERRNO_TO_PARA_ERROR(rc);
442 break;
443 }
444 flowopt_setopts(sockfd, fo);
445
446 if (src) {
447 if (bind(sockfd, src->ai_addr, src->ai_addrlen) < 0) {
448 close(sockfd);
449 goto get_next_src;
450 }
451 if (!dst) /* bind-only completed successfully */
452 break;
453 }
454
455 if (dst && connect(sockfd, dst->ai_addr, dst->ai_addrlen) == 0)
456 break; /* connection completed successfully */
457 close(sockfd);
458 get_next_dst:
459 if (dst && (dst = dst->ai_next))
460 continue;
461 get_next_src:
462 if (src && (src = src->ai_next)) /* restart inner loop */
463 dst = remote;
464 }
465 out:
466 if (local)
467 freeaddrinfo(local);
468 if (remote)
469 freeaddrinfo(remote);
470 flowopt_cleanup(fo);
471
472 if (src == NULL && dst == NULL) {
473 if (rc >= 0)
474 rc = -E_MAKESOCK;
475 PARA_ERROR_LOG("can not create %s socket %s#%s.\n",
476 layer4_name(l4type), host? host : (passive?
477 "[loopback]" : "[localhost]"), port);
478 return rc;
479 }
480 return sockfd;
481 }
482
483 /**
484 * Create a passive / listening socket.
485 *
486 * \param l4type The transport-layer type (\p IPPROTO_xxx).
487 * \param port The decimal port number to listen on.
488 * \param fo Flowopts (if any) to set before starting to listen.
489 *
490 * \return Positive integer (socket descriptor) on success, negative value
491 * otherwise.
492 *
493 * \sa makesock(), ip(7), ipv6(7), bind(2), listen(2).
494 */
495 int para_listen(unsigned l4type, uint16_t port, struct flowopts *fo)
496 {
497 int ret, fd = makesock(l4type, 1, NULL, port, fo);
498
499 if (fd > 0) {
500 ret = listen(fd, BACKLOG);
501 if (ret < 0) {
502 ret = errno;
503 close(fd);
504 return -ERRNO_TO_PARA_ERROR(ret);
505 }
506 PARA_INFO_LOG("listening on %s port %u, fd %d\n",
507 layer4_name(l4type), port, fd);
508 }
509 return fd;
510 }
511
512 /**
513 * Determine IPv4/v6 socket address length.
514 * \param sa Container of IPv4 or IPv6 address.
515 * \return Address-family dependent address length.
516 */
517 static socklen_t salen(const struct sockaddr *sa)
518 {
519 assert(sa->sa_family == AF_INET || sa->sa_family == AF_INET6);
520
521 return sa->sa_family == AF_INET6
522 ? sizeof(struct sockaddr_in6)
523 : sizeof(struct sockaddr_in);
524 }
525
526 /** True if @ss holds a v6-mapped-v4 address (RFC 4291, 2.5.5.2) */
527 static bool SS_IS_ADDR_V4MAPPED(const struct sockaddr_storage *ss)
528 {
529 const struct sockaddr_in6 *ia6 = (const struct sockaddr_in6 *)ss;
530
531 return ss->ss_family == AF_INET6 && IN6_IS_ADDR_V4MAPPED(&ia6->sin6_addr);
532 }
533
534 /**
535 * Process IPv4/v6 address, turn v6-mapped-v4 address into normal IPv4 address.
536 * \param ss Container of IPv4/6 address.
537 * \return Pointer to normalized address (may be static storage).
538 *
539 * \sa RFC 3493
540 */
541 static const struct sockaddr *
542 normalize_ip_address(const struct sockaddr_storage *ss)
543 {
544 assert(ss->ss_family == AF_INET || ss->ss_family == AF_INET6);
545
546 if (SS_IS_ADDR_V4MAPPED(ss)) {
547 const struct sockaddr_in6 *ia6 = (const struct sockaddr_in6 *)ss;
548 static struct sockaddr_in ia;
549
550 ia.sin_family = AF_INET;
551 ia.sin_port = ia6->sin6_port;
552 memcpy(&ia.sin_addr.s_addr, &(ia6->sin6_addr.s6_addr[12]), 4);
553 return (const struct sockaddr *)&ia;
554 }
555 return (const struct sockaddr *)ss;
556 }
557
558 /**
559 * Generic/fallback MTU values
560 *
561 * These are taken from RFC 1122, RFC 2460, and RFC 5405.
562 * - RFC 1122, 3.3.3 defines EMTU_S ("Effective MTU for sending") and recommends
563 * to use an EMTU_S size of of 576 bytes if the IPv4 path MTU is unknown;
564 * - RFC 2460, 5. requires a minimum IPv6 MTU of 1280 bytes;
565 * - RFC 5405, 3.2 recommends that if path MTU discovery is not done,
566 * UDP senders should use the respective minimum values of EMTU_S.
567 */
568 static inline int generic_mtu(const int af_type)
569 {
570 return af_type == AF_INET6 ? 1280 : 576;
571 }
572
573 /** Crude approximation of IP header overhead - neglecting options. */
574 static inline int estimated_header_overhead(const int af_type)
575 {
576 return af_type == AF_INET6 ? 40 : 20;
577 }
578
579 /**
580 * Maximum transport-layer message size (MMS_S) as per RFC 1122, 3.3.3
581 * Socket must be connected.
582 */
583 int generic_max_transport_msg_size(int sockfd)
584 {
585 struct sockaddr_storage ss;
586 socklen_t sslen = sizeof(ss);
587 int af_type = AF_INET;
588
589 if (getpeername(sockfd, (struct sockaddr *)&ss, &sslen) < 0) {
590 PARA_ERROR_LOG("can not determine remote address type: %s\n",
591 strerror(errno));
592 } else if (!SS_IS_ADDR_V4MAPPED(&ss)) {
593 af_type = ss.ss_family;
594 }
595 return generic_mtu(af_type) - estimated_header_overhead(af_type);
596 }
597
598 /**
599 * Print numeric host and port number (beware - uses static char).
600 *
601 * \param sa The IPv4/IPv6 socket address to use.
602 *
603 * \return Host string in numeric host:port format, \sa parse_url().
604 * \sa getnameinfo(3), services(5), nsswitch.conf(5)
605 */
606 static char *host_and_port(const struct sockaddr_storage *ss)
607 {
608 const struct sockaddr *sa = normalize_ip_address(ss);
609 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
610 static char output[sizeof(hbuf) + sizeof(sbuf) + 4];
611 int ret;
612
613 ret = getnameinfo(sa, salen(sa),
614 hbuf, sizeof(hbuf),
615 sbuf, sizeof(sbuf),
616 NI_NUMERICHOST | NI_NUMERICSERV);
617 if (ret) {
618 snprintf(output, sizeof(output), "(unknown)");
619 PARA_WARNING_LOG("hostname lookup error (%s).\n",
620 gai_strerror(ret));
621 } else if (sa->sa_family == AF_INET6) {
622 snprintf(output, sizeof(output), "[%s]:%s", hbuf, sbuf);
623 } else {
624 snprintf(output, sizeof(output), "%s:%s", hbuf, sbuf);
625 }
626 return output;
627 }
628
629 /**
630 * Look up the local or remote side of a connected socket structure.
631 *
632 * \param fd The socket descriptor of the connected socket.
633 * \param getname Either \p getsockname() for local, or \p getpeername() for
634 * remote side.
635 *
636 * \return A static character string identifying hostname and port of the
637 * chosen side.
638 *
639 * \sa getsockname(2), getpeername(2).
640 */
641 static char *__get_sock_name(int fd, int (*getname)(int, struct sockaddr*,
642 socklen_t *))
643 {
644 struct sockaddr_storage ss;
645 socklen_t sslen = sizeof(ss);
646
647 if (getname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
648 static char *dont_know = "(don't know)";
649 PARA_ERROR_LOG("can not determine address from fd %d: %s\n",
650 fd, strerror(errno));
651 return dont_know;
652 }
653 return host_and_port(&ss);
654 }
655
656 /**
657 * Look up the local side of a connected socket structure.
658 *
659 * \param sockfd The file descriptor of the socket.
660 *
661 * \return A pointer to a static buffer containing hostname an port. This
662 * buffer must not be freed by the caller.
663 *
664 * \sa remote_name().
665 */
666 char *local_name(int sockfd)
667 {
668 return __get_sock_name(sockfd, getsockname);
669 }
670
671 /**
672 * Look up the remote side of a connected socket structure.
673 *
674 * \param sockfd The file descriptor of the socket.
675 *
676 * \return Analogous to the return value of \ref local_name() but for the
677 * remote side.
678 *
679 * \sa local_name().
680 */
681 char *remote_name(int sockfd)
682 {
683 return __get_sock_name(sockfd, getpeername);
684 }
685
686 /**
687 * Extract IPv4 or IPv6-mapped-IPv4 address from sockaddr_storage.
688 * \param ss Container of IPv4/6 address
689 * \return Extracted IPv4 address (different from 0) or 0 if unsuccessful.
690 *
691 * \sa RFC 3493
692 */
693 struct in_addr extract_v4_addr(const struct sockaddr_storage *ss)
694 {
695 struct in_addr ia = {.s_addr = 0};
696 const struct sockaddr *sa = normalize_ip_address(ss);
697
698 if (sa->sa_family == AF_INET)
699 ia = ((struct sockaddr_in *)sa)->sin_addr;
700 return ia;
701 }
702
703 /**
704 * Send a binary buffer.
705 *
706 * \param fd The file descriptor.
707 * \param buf The buffer to be sent.
708 * \param len The length of \a buf.
709 *
710 * Send out the buffer and try to resend the remaining part in case of short
711 * writes.
712 *
713 * \return Standard.
714 */
715 int send_bin_buffer(int fd, const char *buf, size_t len)
716 {
717 if (!len)
718 PARA_CRIT_LOG("len == 0\n");
719 return write_all(fd, buf, &len);
720 }
721
722 /**
723 * Send a \p NULL-terminated buffer.
724 *
725 * \param fd The file descriptor.
726 * \param buf The null-terminated buffer to be send.
727 *
728 * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
729 *
730 * \return Standard.
731 */
732 int send_buffer(int fd, const char *buf)
733 {
734 return send_bin_buffer(fd, buf, strlen(buf));
735 }
736
737 /**
738 * Send a buffer given by a format string.
739 *
740 * \param fd The file descriptor.
741 * \param fmt A format string.
742 *
743 * \return Standard.
744 */
745 __printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
746 {
747 char *msg;
748 int ret;
749
750 PARA_VSPRINTF(fmt, msg);
751 ret = send_buffer(fd, msg);
752 free(msg);
753 return ret;
754 }
755
756 /**
757 * Receive data from a file descriptor.
758 *
759 * \param fd The file descriptor.
760 * \param buf The buffer to write the data to.
761 * \param size The size of \a buf.
762 *
763 * Receive at most \a size bytes from file descriptor \a fd.
764 *
765 * \return The number of bytes received on success, negative on errors, zero if
766 * the peer has performed an orderly shutdown.
767 *
768 * \sa recv(2).
769 */
770 __must_check int recv_bin_buffer(int fd, char *buf, size_t size)
771 {
772 ssize_t n;
773
774 n = recv(fd, buf, size, 0);
775 if (n == -1)
776 return -ERRNO_TO_PARA_ERROR(errno);
777 return n;
778 }
779
780 /**
781 * Receive and write terminating NULL byte.
782 *
783 * \param fd The file descriptor.
784 * \param buf The buffer to write the data to.
785 * \param size The size of \a buf.
786 *
787 * Read at most \a size - 1 bytes from file descriptor \a fd and
788 * write a NULL byte at the end of the received data.
789 *
790 * \return The return value of the underlying call to \a recv_bin_buffer().
791 *
792 * \sa recv_bin_buffer()
793 */
794 int recv_buffer(int fd, char *buf, size_t size)
795 {
796 int n;
797
798 assert(size);
799 n = recv_bin_buffer(fd, buf, size - 1);
800 if (n >= 0)
801 buf[n] = '\0';
802 else
803 *buf = '\0';
804 return n;
805 }
806
807 /**
808 * Wrapper around the accept system call.
809 *
810 * \param fd The listening socket.
811 * \param rfds An optional fd_set pointer.
812 * \param addr Structure which is filled in with the address of the peer socket.
813 * \param size Should contain the size of the structure pointed to by \a addr.
814 * \param new_fd Result pointer.
815 *
816 * Accept incoming connections on \a addr, retry if interrupted. If \a rfds is
817 * not \p NULL, return 0 if \a fd is not set in \a rfds without calling accept().
818 *
819 * \return Negative on errors, zero if no connections are present to be accepted,
820 * one otherwise.
821 *
822 * \sa accept(2).
823 */
824 int para_accept(int fd, fd_set *rfds, void *addr, socklen_t size, int *new_fd)
825 {
826 int ret;
827
828 if (rfds && !FD_ISSET(fd, rfds))
829 return 0;
830 do
831 ret = accept(fd, (struct sockaddr *) addr, &size);
832 while (ret < 0 && errno == EINTR);
833
834 if (ret >= 0) {
835 *new_fd = ret;
836 return 1;
837 }
838 if (errno == EAGAIN || errno == EWOULDBLOCK)
839 return 0;
840 return -ERRNO_TO_PARA_ERROR(errno);
841 }
842
843 /**
844 * Probe the list of DCCP CCIDs configured on this host.
845 * \param ccid_array Pointer to return statically allocated array in.
846 * \return Number of elements returned in \a ccid_array or error.
847 *
848 * NB: This feature is only available on Linux > 2.6.30; on older kernels
849 * ENOPROTOOPT ("Protocol not available") will be returned.
850 */
851 int dccp_available_ccids(uint8_t **ccid_array)
852 {
853 static uint8_t ccids[DCCP_MAX_HOST_CCIDS];
854 socklen_t nccids = sizeof(ccids);
855 int ret, fd;
856
857 ret = fd = makesock(IPPROTO_DCCP, 1, NULL, 0, NULL);
858 if (ret < 0)
859 return ret;
860
861 if (getsockopt(fd, SOL_DCCP, DCCP_SOCKOPT_AVAILABLE_CCIDS,
862 ccids, &nccids) < 0) {
863 ret = errno;
864 close(fd);
865 PARA_ERROR_LOG("No DCCP_SOCKOPT_AVAILABLE_CCIDS: %s\n",
866 strerror(ret));
867 return -ERRNO_TO_PARA_ERROR(ret);
868 }
869
870 close(fd);
871 *ccid_array = ccids;
872 return nccids;
873 }
874
875 /**
876 * Prepare a structure for \p AF_UNIX socket addresses.
877 *
878 * \param u Pointer to the struct to be prepared.
879 * \param name The socket pathname.
880 *
881 * This just copies \a name to the sun_path component of \a u.
882 *
883 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
884 * than \p UNIX_PATH_MAX.
885 */
886 static int init_unix_addr(struct sockaddr_un *u, const char *name)
887 {
888 if (strlen(name) >= UNIX_PATH_MAX)
889 return -E_NAME_TOO_LONG;
890 memset(u->sun_path, 0, UNIX_PATH_MAX);
891 u->sun_family = PF_UNIX;
892 strcpy(u->sun_path, name);
893 return 1;
894 }
895
896 /**
897 * Prepare, create, and bind a socket for local communication.
898 *
899 * \param name The socket pathname.
900 * \param unix_addr Pointer to the \p AF_UNIX socket structure.
901 * \param mode The desired mode of the socket.
902 *
903 * This function creates a local socket for sequenced, reliable,
904 * two-way, connection-based byte streams.
905 *
906 * \return The file descriptor, on success, negative on errors.
907 *
908 * \sa socket(2)
909 * \sa bind(2)
910 * \sa chmod(2)
911 */
912 int create_local_socket(const char *name, struct sockaddr_un *unix_addr,
913 mode_t mode)
914 {
915 int fd, ret;
916
917 ret = init_unix_addr(unix_addr, name);
918 if (ret < 0)
919 return ret;
920 ret = socket(PF_UNIX, SOCK_STREAM, 0);
921 if (ret < 0)
922 return -ERRNO_TO_PARA_ERROR(errno);
923 fd = ret;
924 ret = bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX);
925 if (ret < 0) {
926 ret = -ERRNO_TO_PARA_ERROR(errno);
927 goto err;
928 }
929 ret = -E_CHMOD;
930 if (chmod(name, mode) < 0)
931 goto err;
932 return fd;
933 err:
934 close(fd);
935 return ret;
936 }
937
938 /**
939 * Prepare, create, and connect to a Unix domain socket for local communication.
940 *
941 * \param name The socket pathname.
942 *
943 * This function creates a local socket for sequenced, reliable, two-way,
944 * connection-based byte streams.
945 *
946 * \return The file descriptor of the connected socket on success, negative on
947 * errors.
948 *
949 * \sa create_local_socket(), unix(7), connect(2).
950 */
951 int connect_local_socket(const char *name)
952 {
953 struct sockaddr_un unix_addr;
954 int fd, ret;
955
956 PARA_DEBUG_LOG("connecting to %s\n", name);
957 ret = init_unix_addr(&unix_addr, name);
958 if (ret < 0)
959 return ret;
960 fd = socket(PF_UNIX, SOCK_STREAM, 0);
961 if (fd < 0)
962 return -ERRNO_TO_PARA_ERROR(errno);
963 if (connect(fd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) == -1) {
964 ret = -ERRNO_TO_PARA_ERROR(errno);
965 goto err;
966 }
967 return fd;
968 err:
969 close(fd);
970 return ret;
971 }
972
973 #ifndef HAVE_UCRED
974 ssize_t send_cred_buffer(int sock, char *buf)
975 {
976 return send_buffer(sock, buf);
977 }
978 int recv_cred_buffer(int fd, char *buf, size_t size)
979 {
980 return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
981 }
982 #else /* HAVE_UCRED */
983 /**
984 * Send \p NULL-terminated buffer and Unix credentials of the current process.
985 *
986 * \param sock The socket file descriptor.
987 * \param buf The buffer to be sent.
988 *
989 * \return On success, this call returns the number of characters sent. On
990 * error, \p -E_SENDMSG is returned.
991 *
992 * \sa sendmsg(2), okir's Black Hats Manual.
993 */
994 ssize_t send_cred_buffer(int sock, char *buf)
995 {
996 char control[sizeof(struct cmsghdr) + sizeof(struct ucred)];
997 struct msghdr msg;
998 struct cmsghdr *cmsg;
999 static struct iovec iov;
1000 struct ucred c;
1001 int ret;
1002
1003 /* Response data */
1004 iov.iov_base = buf;
1005 iov.iov_len = strlen(buf);
1006 c.pid = getpid();
1007 c.uid = getuid();
1008 c.gid = getgid();
1009 /* compose the message */
1010 memset(&msg, 0, sizeof(msg));
1011 msg.msg_iov = &iov;
1012 msg.msg_iovlen = 1;
1013 msg.msg_control = control;
1014 msg.msg_controllen = sizeof(control);
1015 /* attach the ucred struct */
1016 cmsg = CMSG_FIRSTHDR(&msg);
1017 cmsg->cmsg_level = SOL_SOCKET;
1018 cmsg->cmsg_type = SCM_CREDENTIALS;
1019 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
1020 *(struct ucred *)CMSG_DATA(cmsg) = c;
1021 msg.msg_controllen = cmsg->cmsg_len;
1022 ret = sendmsg(sock, &msg, 0);
1023 if (ret < 0)
1024 ret = -E_SENDMSG;
1025 return ret;
1026 }
1027
1028 static void dispose_fds(int *fds, unsigned num)
1029 {
1030 int i;
1031
1032 for (i = 0; i < num; i++)
1033 close(fds[i]);
1034 }
1035
1036 /**
1037 * Receive a buffer and the Unix credentials of the sending process.
1038 *
1039 * \param fd the socket file descriptor.
1040 * \param buf the buffer to store the message.
1041 * \param size the size of \a buffer.
1042 *
1043 * \return negative on errors, the user id on success.
1044 *
1045 * \sa recvmsg(2), okir's Black Hats Manual.
1046 */
1047 int recv_cred_buffer(int fd, char *buf, size_t size)
1048 {
1049 char control[255];
1050 struct msghdr msg;
1051 struct cmsghdr *cmsg;
1052 struct iovec iov;
1053 int result = 0;
1054 int yes = 1;
1055 struct ucred cred;
1056
1057 setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
1058 memset(&msg, 0, sizeof(msg));
1059 memset(buf, 0, size);
1060 iov.iov_base = buf;
1061 iov.iov_len = size;
1062 msg.msg_iov = &iov;
1063 msg.msg_iovlen = 1;
1064 msg.msg_control = control;
1065 msg.msg_controllen = sizeof(control);
1066 if (recvmsg(fd, &msg, 0) < 0)
1067 return -E_RECVMSG;
1068 result = -E_SCM_CREDENTIALS;
1069 cmsg = CMSG_FIRSTHDR(&msg);
1070 while (cmsg) {
1071 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
1072 == SCM_CREDENTIALS) {
1073 memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
1074 result = cred.uid;
1075 } else
1076 if (cmsg->cmsg_level == SOL_SOCKET
1077 && cmsg->cmsg_type == SCM_RIGHTS) {
1078 dispose_fds((int *) CMSG_DATA(cmsg),
1079 (cmsg->cmsg_len - CMSG_LEN(0))
1080 / sizeof(int));
1081 }
1082 cmsg = CMSG_NXTHDR(&msg, cmsg);
1083 }
1084 return result;
1085 }
1086 #endif /* HAVE_UCRED */