2 * Copyright (C) 2005-2009 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file net.c Networking-related helper functions. */
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.
17 /* At least NetBSD needs these. */
25 #define AI_ADDRCONFIG 0
38 /** Information about one encrypted connection. */
40 /** Function used to decrypt received data. */
42 /** Function used to encrypt data to be sent. */
45 * Context-dependent data (crypt keys), passed verbatim to the above
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;
56 * Activate encryption for one file descriptor.
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.
63 void enable_crypt(int fd
, crypt_function
*recv_f
, crypt_function
*send_f
,
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
));
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
);
80 * Deactivate encryption for a given fd.
82 * \param fd The file descriptor.
84 * This must be called if and only if \p fd was activated via enable_crypt().
86 void disable_crypt(int fd
)
88 if (cda_size
< fd
+ 1)
90 crypt_data_array
[fd
].recv
= NULL
;
91 crypt_data_array
[fd
].send
= NULL
;
92 crypt_data_array
[fd
].private_data
= NULL
;
96 * Match string as a candidate IPv4 address.
98 * \param address The string to match.
99 * \return True if \a address has "dot-quad" format.
101 static bool is_v4_dot_quad(const char *address
)
106 assert(!regcomp(&r
, "^([0-9]+\\.){3}[0-9]+$", REG_EXTENDED
|REG_NOSUB
));
107 result
= regexec(&r
, address
, 0, NULL
, 0) == 0;
113 * Perform basic syntax checking on the host-part of an URL:
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.
120 * \param host The host string to check.
121 * \return True if \a host passes the syntax checks.
123 * \sa RFC 3986, 3.2.2; RFC 1123, 2.1; RFC 1034, 3.5
125 static bool host_string_ok(const char *host
)
127 if (host
== NULL
|| *host
== '\0')
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
);
137 * Parse and validate URL string.
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.
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.
148 * The following are valid examples:
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.
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.
165 * \sa RFC 3986, 3.2.2/3.2.3
167 char *parse_url(const char *url
,
168 char *host
, ssize_t hostlen
,
172 char *c
= host
, *end
= c
+ (hostlen
- 1);
176 if (o
== NULL
|| hostlen
< 1)
180 for (++o
; (*c
= *o
== ']' ? '\0' : *o
); c
++, o
++)
184 if (*o
++ != ']' || (*o
!= '\0' && *o
!= ':'))
187 for (; (*c
= *o
== ':'? '\0' : *o
); c
++, o
++)
193 if (para_atoi32(++o
, port
) < 0 ||
194 *port
< 0 || *port
> 0xffff)
197 if (host_string_ok(host
))
205 * Determine the socket type for a given layer-4 protocol.
207 * \param l4type The symbolic name of the transport-layer protocol.
209 * \sa ip(7), socket(2)
211 static inline int sock_type(const unsigned l4type
)
214 case IPPROTO_UDP
: return SOCK_DGRAM
;
215 case IPPROTO_TCP
: return SOCK_STREAM
;
216 case IPPROTO_DCCP
: return SOCK_DCCP
;
218 return -1; /* not supported here */
222 * Pretty-print transport-layer name.
224 static const char *layer4_name(const unsigned l4type
)
227 case IPPROTO_UDP
: return "UDP";
228 case IPPROTO_TCP
: return "TCP";
229 case IPPROTO_DCCP
: return "DCCP";
231 return "UNKNOWN PROTOCOL";
235 * Resolve IPv4/IPv6 address and create a ready-to-use active or passive socket.
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.
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
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
250 * - \a port_number is in either case the numeric port number (not service
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
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).
260 * \sa ipv6(7), getaddrinfo(3), bind(2), connect(2).
262 int makesock(unsigned l3type
, unsigned l4type
, int passive
,
263 const char *host
, unsigned short port_number
)
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 */
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
;
277 * getaddrinfo does not support SOCK_DCCP, so for the sake of lookup
278 * (and only then) pretend to be UDP.
280 if (l4type
== IPPROTO_DCCP
)
281 hints
.ai_socktype
= SOCK_DGRAM
;
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
;
289 if (passive
&& host
== NULL
)
290 hints
.ai_flags
|= AI_PASSIVE
;
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",
296 host
? host
: (passive
? "[loopback]" : "[localhost]"),
297 port
, gai_strerror(rc
));
298 return -E_ADDRESS_LOOKUP
;
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 */
307 sockfd
= socket(src
? src
->ai_family
: dst
->ai_family
,
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.
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",
321 return -ERRNO_TO_PARA_ERROR(errno
);
325 if (bind(sockfd
, src
->ai_addr
, src
->ai_addrlen
) < 0) {
329 if (!dst
) /* bind-only completed successfully */
333 if (dst
&& connect(sockfd
, dst
->ai_addr
, dst
->ai_addrlen
) == 0)
334 break; /* connection completed successfully */
337 if (dst
&& (dst
= dst
->ai_next
))
340 if (src
&& (src
= src
->ai_next
)) /* restart inner loop */
346 freeaddrinfo(remote
);
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
);
358 * Create a passive / listening socket.
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.
364 * \return Positive integer (socket descriptor) on success, negative value
367 * \sa makesock(), ip(7), ipv6(7), bind(2), listen(2).
369 int para_listen(unsigned l3type
, unsigned l4type
, unsigned short port
)
371 int ret
, fd
= makesock(l3type
, l4type
, 1, NULL
, port
);
374 ret
= listen(fd
, BACKLOG
);
377 return -ERRNO_TO_PARA_ERROR(errno
);
379 PARA_INFO_LOG("listening on %s port %u, fd %d\n",
380 layer4_name(l4type
), port
, fd
);
386 * Print numeric host and port number (beware - uses static char).
388 * \param sa The IPv4/IPv6 socket address to use.
389 * \param len The length of \p sa.
391 * \sa getnameinfo(3).
393 static char *host_and_port(struct sockaddr
*sa
, socklen_t len
)
395 static char output
[NI_MAXHOST
+ NI_MAXSERV
+ 2];
396 char hbuf
[NI_MAXHOST
], sbuf
[NI_MAXSERV
];
399 ret
= getnameinfo(sa
, len
, hbuf
, sizeof(hbuf
), sbuf
, sizeof(sbuf
),
400 NI_NUMERICHOST
| NI_NUMERICSERV
);
402 PARA_WARNING_LOG("hostname lookup error (%s).\n",
404 sprintf(output
, "(unknown)");
406 sprintf(output
, "%s#%s", hbuf
, sbuf
);
411 * Look up the local or remote side of a connected socket structure.
413 * \param fd The socket descriptor of the connected socket.
414 * \param getname Either \p getsockname() for local, or \p getpeername() for
417 * \return A static character string identifying hostname and port of the
420 * \sa getsockname(2), getpeername(2).
422 static char *__get_sock_name(int fd
, int (*getname
)(int, struct sockaddr
*,
425 struct sockaddr_storage ss
;
426 socklen_t sslen
= sizeof(ss
);
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
));
434 return host_and_port((struct sockaddr
*)&ss
, sslen
);
437 char *local_name(int sockfd
)
439 return __get_sock_name(sockfd
, getsockname
);
442 char *remote_name(int sockfd
)
444 return __get_sock_name(sockfd
, getpeername
);
448 * Extract IPv4 or IPv6-mapped-IPv4 address from sockaddr_storage.
449 * \param ss Container of IPv4/6 address
450 * \return Extracted IPv4 address (different from 0) or 0 if unsuccessful.
454 struct in_addr
extract_v4_addr(const struct sockaddr_storage
*ss
)
456 struct in_addr ia
= {.s_addr
= 0};
458 if (ss
->ss_family
== AF_INET
)
459 ia
.s_addr
= ((struct sockaddr_in
*)ss
)->sin_addr
.s_addr
;
460 if (ss
->ss_family
== AF_INET6
) {
461 const struct in6_addr v6_addr
= ((struct sockaddr_in6
*)ss
)->sin6_addr
;
463 if (IN6_IS_ADDR_V4MAPPED(&v6_addr
))
464 memcpy(&ia
.s_addr
, &(v6_addr
.s6_addr
[12]), 4);
470 * Encrypt and send a binary buffer.
472 * \param fd The file descriptor.
473 * \param buf The buffer to be encrypted and sent.
474 * \param len The length of \a buf.
476 * Check if encryption is available. If yes, encrypt the given buffer. Send
477 * out the buffer, encrypted or not, and try to resend the remaing part in case
482 int send_bin_buffer(int fd
, const char *buf
, size_t len
)
485 crypt_function
*cf
= NULL
;
488 PARA_CRIT_LOG("len == 0\n");
489 if (fd
+ 1 <= cda_size
)
490 cf
= crypt_data_array
[fd
].send
;
492 void *private = crypt_data_array
[fd
].private_data
;
493 /* RC4 may write more than len to the output buffer */
494 unsigned char *outbuf
= para_malloc(ROUND_UP(len
, 8));
495 (*cf
)(len
, (unsigned char *)buf
, outbuf
, private);
496 ret
= write_all(fd
, (char *)outbuf
, &len
);
499 ret
= write_all(fd
, buf
, &len
);
504 * Encrypt and send null terminated buffer.
506 * \param fd The file descriptor.
507 * \param buf The null-terminated buffer to be send.
509 * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
513 int send_buffer(int fd
, const char *buf
)
515 return send_bin_buffer(fd
, buf
, strlen(buf
));
520 * Send and encrypt a buffer given by a format string.
522 * \param fd The file descriptor.
523 * \param fmt A format string.
527 __printf_2_3
int send_va_buffer(int fd
, const char *fmt
, ...)
532 PARA_VSPRINTF(fmt
, msg
);
533 ret
= send_buffer(fd
, msg
);
539 * Receive and decrypt.
541 * \param fd The file descriptor.
542 * \param buf The buffer to write the decrypted data to.
543 * \param size The size of \a buf.
545 * Receive at most \a size bytes from file descriptor \a fd. If encryption is
546 * available, decrypt the received buffer.
548 * \return The number of bytes received on success, negative on errors.
552 __must_check
int recv_bin_buffer(int fd
, char *buf
, size_t size
)
555 crypt_function
*cf
= NULL
;
557 if (fd
+ 1 <= cda_size
)
558 cf
= crypt_data_array
[fd
].recv
;
560 unsigned char *tmp
= para_malloc(size
);
561 void *private = crypt_data_array
[fd
].private_data
;
562 n
= recv(fd
, tmp
, size
, 0);
565 unsigned char *b
= (unsigned char *)buf
;
566 (*cf
)(numbytes
, tmp
, b
, private);
570 n
= recv(fd
, buf
, size
, 0);
572 return -ERRNO_TO_PARA_ERROR(errno
);
577 * Receive, decrypt and write terminating NULL byte.
579 * \param fd The file descriptor.
580 * \param buf The buffer to write the decrypted data to.
581 * \param size The size of \a buf.
583 * Read and decrypt at most \a size - 1 bytes from file descriptor \a fd and
584 * write a NULL byte at the end of the received data.
586 * \return The return value of the underlying call to \a recv_bin_buffer().
588 * \sa recv_bin_buffer()
590 int recv_buffer(int fd
, char *buf
, size_t size
)
595 n
= recv_bin_buffer(fd
, buf
, size
- 1);
604 * Wrapper around the accept system call.
606 * \param fd The listening socket.
607 * \param addr Structure which is filled in with the address of the peer socket.
608 * \param size Should contain the size of the structure pointed to by \a addr.
610 * Accept incoming connections on \a addr. Retry if interrupted.
612 * \return The new file descriptor on success, negative on errors.
616 int para_accept(int fd
, void *addr
, socklen_t size
)
621 new_fd
= accept(fd
, (struct sockaddr
*) addr
, &size
);
622 while (new_fd
< 0 && errno
== EINTR
);
623 return new_fd
< 0? -ERRNO_TO_PARA_ERROR(errno
) : new_fd
;
627 * Prepare a structure for \p AF_UNIX socket addresses.
629 * \param u Pointer to the struct to be prepared.
630 * \param name The socket pathname.
632 * This just copies \a name to the sun_path component of \a u.
634 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
635 * than \p UNIX_PATH_MAX.
637 static int init_unix_addr(struct sockaddr_un
*u
, const char *name
)
639 if (strlen(name
) >= UNIX_PATH_MAX
)
640 return -E_NAME_TOO_LONG
;
641 memset(u
->sun_path
, 0, UNIX_PATH_MAX
);
642 u
->sun_family
= PF_UNIX
;
643 strcpy(u
->sun_path
, name
);
648 * Prepare, create, and bind a socket for local communication.
650 * \param name The socket pathname.
651 * \param unix_addr Pointer to the \p AF_UNIX socket structure.
652 * \param mode The desired mode of the socket.
654 * This function creates a local socket for sequenced, reliable,
655 * two-way, connection-based byte streams.
657 * \return The file descriptor, on success, negative on errors.
663 int create_local_socket(const char *name
, struct sockaddr_un
*unix_addr
,
668 ret
= init_unix_addr(unix_addr
, name
);
671 ret
= socket(PF_UNIX
, SOCK_STREAM
, 0);
673 return -ERRNO_TO_PARA_ERROR(errno
);
675 ret
= bind(fd
, (struct sockaddr
*) unix_addr
, UNIX_PATH_MAX
);
677 ret
= -ERRNO_TO_PARA_ERROR(errno
);
681 if (chmod(name
, mode
) < 0)
690 * Prepare, create, and connect to a Unix domain socket for local communication.
692 * \param name The socket pathname.
694 * This function creates a local socket for sequenced, reliable, two-way,
695 * connection-based byte streams.
697 * \return The file descriptor, on success, negative on errors.
699 * \sa create_local_socket(), unix(7), connect(2).
701 int create_remote_socket(const char *name
)
703 struct sockaddr_un unix_addr
;
706 ret
= init_unix_addr(&unix_addr
, name
);
709 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
711 return -ERRNO_TO_PARA_ERROR(errno
);
712 if (connect(fd
, (struct sockaddr
*)&unix_addr
, sizeof(unix_addr
)) == -1) {
713 ret
= -ERRNO_TO_PARA_ERROR(errno
);
723 ssize_t
send_cred_buffer(int sock
, char *buf
)
725 return send_buffer(sock
, buf
);
727 int recv_cred_buffer(int fd
, char *buf
, size_t size
)
729 return recv_buffer(fd
, buf
, size
) > 0? 1 : -E_RECVMSG
;
731 #else /* HAVE_UCRED */
733 * Send \p NULL-terminated buffer and Unix credentials of the current process.
735 * \param sock The socket file descriptor.
736 * \param buf The buffer to be sent.
738 * \return On success, this call returns the number of characters sent. On
739 * error, \p -E_SENDMSG is returned.
741 * \sa sendmsg(2), okir's Black Hats Manual.
743 ssize_t
send_cred_buffer(int sock
, char *buf
)
745 char control
[sizeof(struct cmsghdr
) + 10];
747 struct cmsghdr
*cmsg
;
748 static struct iovec iov
;
754 iov
.iov_len
= strlen(buf
);
758 /* compose the message */
759 memset(&msg
, 0, sizeof(msg
));
762 msg
.msg_control
= control
;
763 msg
.msg_controllen
= sizeof(control
);
764 /* attach the ucred struct */
765 cmsg
= CMSG_FIRSTHDR(&msg
);
766 cmsg
->cmsg_level
= SOL_SOCKET
;
767 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
768 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
769 *(struct ucred
*)CMSG_DATA(cmsg
) = c
;
770 msg
.msg_controllen
= cmsg
->cmsg_len
;
771 ret
= sendmsg(sock
, &msg
, 0);
777 static void dispose_fds(int *fds
, unsigned num
)
781 for (i
= 0; i
< num
; i
++)
786 * Receive a buffer and the Unix credentials of the sending process.
788 * \param fd the socket file descriptor.
789 * \param buf the buffer to store the message.
790 * \param size the size of \a buffer.
792 * \return negative on errors, the user id on success.
794 * \sa recvmsg(2), okir's Black Hats Manual.
796 int recv_cred_buffer(int fd
, char *buf
, size_t size
)
800 struct cmsghdr
*cmsg
;
806 setsockopt(fd
, SOL_SOCKET
, SO_PASSCRED
, &yes
, sizeof(int));
807 memset(&msg
, 0, sizeof(msg
));
808 memset(buf
, 0, size
);
813 msg
.msg_control
= control
;
814 msg
.msg_controllen
= sizeof(control
);
815 if (recvmsg(fd
, &msg
, 0) < 0)
817 result
= -E_SCM_CREDENTIALS
;
818 cmsg
= CMSG_FIRSTHDR(&msg
);
820 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
821 == SCM_CREDENTIALS
) {
822 memcpy(&cred
, CMSG_DATA(cmsg
), sizeof(struct ucred
));
825 if (cmsg
->cmsg_level
== SOL_SOCKET
826 && cmsg
->cmsg_type
== SCM_RIGHTS
) {
827 dispose_fds((int *) CMSG_DATA(cmsg
),
828 (cmsg
->cmsg_len
- CMSG_LEN(0))
831 cmsg
= CMSG_NXTHDR(&msg
, cmsg
);
835 #endif /* HAVE_UCRED */
838 * Receive a buffer and check for a pattern.
840 * \param fd The file descriptor to receive from.
841 * \param pattern The expected pattern.
842 * \param bufsize The size of the internal buffer.
844 * \return Positive if \a pattern was received, negative otherwise.
846 * This function tries to receive at most \a bufsize bytes from file descriptor
847 * \a fd. If at least \p strlen(\a pattern) bytes were received, the beginning
848 * of the received buffer is compared with \a pattern, ignoring case.
850 * \sa recv_buffer(), \sa strncasecmp(3).
852 int recv_pattern(int fd
, const char *pattern
, size_t bufsize
)
854 size_t len
= strlen(pattern
);
855 char *buf
= para_malloc(bufsize
+ 1);
856 int ret
= -E_RECV_PATTERN
, n
= recv_buffer(fd
, buf
, bufsize
+ 1);
860 if (strncasecmp(buf
, pattern
, len
))
865 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n
,
868 PARA_NOTICE_LOG("recvd: %s\n", buf
);