2 * Copyright (C) 2005-2007 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file net.c Networking-related helper functions. */
17 /** Information about one encrypted connection. */
19 /** Function used to decrypt received data. */
21 /** Function used to encrypt data to be sent. */
24 * Context-dependent data (crypt keys), passed verbatim to the above
29 /** Array holding per fd crypt data. */
30 static struct crypt_data *crypt_data_array;
31 /** Current size of the crypt data array. */
32 static unsigned cda_size = 0;
35 * Activate encryption for one file descriptor.
37 * \param fd The file descriptor.
38 * \param recv_f The function used for decrypting received data.
39 * \param send_f The function used for encrypting before sending.
40 * \param private_data User data supplied by the caller.
42 void enable_crypt(int fd, crypt_function *recv_f, crypt_function *send_f,
45 if (fd + 1 > cda_size) {
46 crypt_data_array = para_realloc(crypt_data_array,
47 (fd + 1) * sizeof(struct crypt_data));
48 memset(crypt_data_array + cda_size, 0,
49 (fd + 1 - cda_size) * sizeof(struct crypt_data));
52 crypt_data_array[fd].recv = recv_f;
53 crypt_data_array[fd].send = send_f;
54 crypt_data_array[fd].private_data = private_data;
55 PARA_INFO_LOG("rc4 encryption activated for fd %d\n", fd);
59 * Deactivate encryption for a given fd.
61 * \param fd The file descriptor.
63 * This must be called if and only if \p fd was activated via enable_crypt().
65 void disable_crypt(int fd)
67 if (cda_size < fd + 1)
69 crypt_data_array[fd].recv = NULL;
70 crypt_data_array[fd].send = NULL;
71 crypt_data_array[fd].private_data = NULL;
76 * Determine the socket type for a given layer-4 protocol.
78 * \param l4type The symbolic name of the transport-layer protocol.
80 * \sa ip(7), socket(2)
82 static inline int sock_type(const unsigned l4type)
85 case IPPROTO_UDP: return SOCK_DGRAM;
86 case IPPROTO_TCP: return SOCK_STREAM;
87 case IPPROTO_DCCP: return SOCK_DCCP;
89 return -1; /* not supported here */
93 * Pretty-print transport-layer name.
95 static const char *layer4_name(const unsigned l4type)
98 case IPPROTO_UDP: return "UDP";
99 case IPPROTO_TCP: return "TCP";
100 case IPPROTO_DCCP: return "DCCP";
102 return "UNKNOWN PROTOCOL";
106 * Resolve IPv4/IPv6 address and create a ready-to-use active or passive socket.
108 * @param l3type The layer-3 type (\p AF_INET, \p AF_INET6, \p AF_UNSPEC)
109 * @param l4type The layer-4 type (\p IPPROTO_xxx).
110 * @param passive Whether this is a passive (1) or active (0) socket/
111 * @param host Remote or local hostname or IPv/6 address string.
112 * @param port_number Decimal port number.
114 * This creates a ready-made IPv4/v6 socket structure after looking up the necessary
115 * parameters. The interpretation of \a host depends on the value of \a passive:
116 * - on a passive socket host is interpreted as an interface IPv4/6 address
117 * (can be left NULL);
118 * - on an active socket, \a host is the peer DNS name or IPv4/6 address to connect to;
119 * - \a port_number is in either case the numeric port number (not service string).
120 * Furthermore, bind(2) is called on passive sockets, and connect(2) on active sockets.
121 * The algorithm tries all possible address combinations until it succeeds.
123 * \return This function returns 1 on success and \a -E_ADDRESS_LOOKUP when no matching
124 * connection could be set up (with details in the error log).
126 * \sa ipv6(7), getaddrinfo(3), bind(2), connect(2)
128 int makesock(unsigned l3type, unsigned l4type, int passive,
129 const char *host, unsigned short port_number)
131 struct addrinfo *local = NULL, *src,
132 *remote = NULL, *dst, hints;
133 char *port = make_message("%u", port_number);
134 int rc, on = 1, sockfd = -1,
135 socktype = sock_type(l4type);
138 * Set up address hint structure
140 memset(&hints, 0, sizeof(hints));
141 hints.ai_family = l3type;
142 /* getaddrinfo does not really work well with SOCK_DCCP */
143 if (socktype == SOCK_DGRAM || socktype == SOCK_STREAM)
144 hints.ai_socktype = socktype;
146 /* only use addresses available on the host */
147 hints.ai_flags = AI_ADDRCONFIG;
148 if (l3type == AF_INET6)
149 /* use v4-mapped-v6 if no v6 addresses found */
150 hints.ai_flags |= AI_V4MAPPED | AI_ALL;
152 if (passive && host == NULL)
153 hints.ai_flags |= AI_PASSIVE;
156 * Obtain local/remote address information
158 if ((rc = getaddrinfo(host, port, &hints, passive ? &local : &remote))) {
159 PARA_ERROR_LOG("can not resolve %s address %s#%s: %s.\n",
161 host? : (passive? "[loopback]" : "[localhost]"),
162 port, gai_strerror(rc));
163 return -E_ADDRESS_LOOKUP;
167 * Iterate over all src/dst combination, exhausting dst first
169 for (src = local, dst = remote; src != NULL || dst != NULL; /* no op */ ) {
170 if (src && dst && src->ai_family == AF_INET
171 && dst->ai_family == AF_INET6) /* v4 -> v6 is not possible */
174 sockfd = socket(src ? src->ai_family : dst->ai_family, socktype, l4type);
179 * Set those options that need to be set before establishing the connection
181 /* Reuse the address on passive (listening) sockets to avoid failure on restart */
182 if (passive && setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
183 PARA_ERROR_LOG("can not set SO_REUSEADDR: %s\n", strerror(errno));
184 return -ERRNO_TO_PARA_ERROR(errno);
188 if (bind(sockfd, src->ai_addr, src->ai_addrlen) < 0) {
193 break; /* bind-only completed successfully */
196 if (dst && connect(sockfd, dst->ai_addr, dst->ai_addrlen) == 0)
197 break; /* connection completed successfully */
200 if (dst && (dst = dst->ai_next))
203 if (src && (src = src->ai_next))
204 dst = remote; /* restart inner loop */
209 freeaddrinfo(remote);
211 if (src == NULL && dst == NULL) {
212 PARA_ERROR_LOG("can not create %s socket %s#%s.\n", layer4_name(l4type),
213 host? : (passive? "[loopback]" : "[localhost]"), port);
214 return -ERRNO_TO_PARA_ERROR(errno);
220 * Create a passive / listening socket.
221 * \param l3type The network-layer type (\p AF_xxx)
222 * \param l4type The transport-layer type (\p IPPROTO_xxx).
223 * \param port The decimal port number to listen on.
225 * \return Positive integer (socket descriptor) on success, negative value otherwise.
226 * \sa makesock(), ip(7), ipv6(7), bind(2), listen(2).
228 int para_listen(unsigned l3type, unsigned l4type, unsigned short port)
230 int ret, fd = makesock(l3type, l4type, 1, NULL, port);
233 ret = listen(fd, BACKLOG);
236 return -ERRNO_TO_PARA_ERROR(errno);
238 PARA_INFO_LOG("listening on %s port %u, fd %d\n",
239 layer4_name(l4type), port, fd);
245 * Print numeric host and port number (beware - uses static char).
246 * \param sa The IPv4/IPv6 socket address to use.
247 * \param len The length of \p sa.
251 char *host_and_port(struct sockaddr *sa, socklen_t len)
253 static char output[NI_MAXHOST + NI_MAXSERV + 2];
254 char hbuf[NI_MAXHOST],
258 ret = getnameinfo(sa, len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
259 NI_NUMERICHOST | NI_NUMERICSERV);
261 PARA_WARNING_LOG("hostname lookup error (%s).\n", gai_strerror(ret));
262 sprintf(output, "(unknown)");
264 sprintf(output, "%s#%s", hbuf, sbuf);
270 * Look up the local or remote side of a connected socket structure.
271 * \param fd The socket descriptor of the connected socket.
272 * \param getname Either \fn getsockname() for local, or \fn getpeername() for remote side.
274 * \return A static character string identifying hostname and port of the chosen side
275 * \sa getsockname(2), getpeername(2)
277 static char *__get_sock_name(int fd, int (*getname)(int, struct sockaddr*, socklen_t *))
279 struct sockaddr_storage ss;
280 socklen_t sslen = sizeof(ss);
282 if (getname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
283 static char *dont_know = "(don't know)";
284 PARA_ERROR_LOG("can not determine address from fd %d: %s\n", fd, strerror(errno));
288 return host_and_port((struct sockaddr *)&ss, sslen);
291 char *local_name(int sockfd)
293 return __get_sock_name(sockfd, getsockname);
296 char *remote_name(int sockfd)
298 return __get_sock_name(sockfd, getpeername);
302 * Send out a buffer, resend on short writes.
304 * \param fd The file descriptor.
305 * \param buf The buffer to be sent.
306 * \param len The length of \a buf.
308 * \return Standard. In any case, the number of bytes actually sent is stored
311 static int sendall(int fd, const char *buf, size_t *len)
317 while (*len < total) {
318 int ret = send(fd, buf + *len, total - *len, 0);
320 return -ERRNO_TO_PARA_ERROR(errno);
327 * Encrypt and send a binary buffer.
329 * \param fd The file descriptor.
330 * \param buf The buffer to be encrypted and sent.
331 * \param len The length of \a buf.
333 * Check if encryption is available. If yes, encrypt the given buffer. Send
334 * out the buffer, encrypted or not, and try to resend the remaing part in case
339 int send_bin_buffer(int fd, const char *buf, size_t len)
342 crypt_function *cf = NULL;
345 PARA_CRIT_LOG("%s", "len == 0\n");
346 if (fd + 1 <= cda_size)
347 cf = crypt_data_array[fd].send;
349 void *private = crypt_data_array[fd].private_data;
350 /* RC4 may write more than len to the output buffer */
351 unsigned char *outbuf = para_malloc(ROUND_UP(len, 8));
352 (*cf)(len, (unsigned char *)buf, outbuf, private);
353 ret = sendall(fd, (char *)outbuf, &len);
356 ret = sendall(fd, buf, &len);
361 * Encrypt and send null terminated buffer.
363 * \param fd The file descriptor.
364 * \param buf The null-terminated buffer to be send.
366 * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
370 int send_buffer(int fd, const char *buf)
372 return send_bin_buffer(fd, buf, strlen(buf));
377 * Send and encrypt a buffer given by a format string.
379 * \param fd The file descriptor.
380 * \param fmt A format string.
384 __printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
389 PARA_VSPRINTF(fmt, msg);
390 ret = send_buffer(fd, msg);
396 * Receive and decrypt.
398 * \param fd The file descriptor.
399 * \param buf The buffer to write the decrypted data to.
400 * \param size The size of \a buf.
402 * Receive at most \a size bytes from file descriptor \a fd. If encryption is
403 * available, decrypt the received buffer.
405 * \return The number of bytes received on success, negative on errors.
409 __must_check int recv_bin_buffer(int fd, char *buf, size_t size)
412 crypt_function *cf = NULL;
414 if (fd + 1 <= cda_size)
415 cf = crypt_data_array[fd].recv;
417 unsigned char *tmp = para_malloc(size);
418 void *private = crypt_data_array[fd].private_data;
419 n = recv(fd, tmp, size, 0);
422 unsigned char *b = (unsigned char *)buf;
423 (*cf)(numbytes, tmp, b, private);
427 n = recv(fd, buf, size, 0);
429 return -ERRNO_TO_PARA_ERROR(errno);
434 * Receive, decrypt and write terminating NULL byte.
436 * \param fd The file descriptor.
437 * \param buf The buffer to write the decrypted data to.
438 * \param size The size of \a buf.
440 * Read and decrypt at most \a size - 1 bytes from file descriptor \a fd and
441 * write a NULL byte at the end of the received data.
443 * \return The return value of the underlying call to \a recv_bin_buffer().
445 * \sa recv_bin_buffer()
447 int recv_buffer(int fd, char *buf, size_t size)
452 n = recv_bin_buffer(fd, buf, size - 1);
461 * A wrapper around socket(2).
463 * \param domain The communication domain that selects the protocol family.
465 * Create an IPv4 socket for sequenced, reliable, two-way, connection-based
468 * \return The socket fd on success, negative on errors.
472 int get_stream_socket(int domain)
474 int fd = socket(domain, SOCK_STREAM, 0);
477 return -ERRNO_TO_PARA_ERROR(errno);
482 * Wrapper around the accept system call.
484 * \param fd The listening socket.
485 * \param addr Structure which is filled in with the address of the peer socket.
486 * \param size Should contain the size of the structure pointed to by \a addr.
488 * Accept incoming connections on \a addr. Retry if interrupted.
490 * \return The new file descriptor on success, negative on errors.
494 int para_accept(int fd, void *addr, socklen_t size)
499 new_fd = accept(fd, (struct sockaddr *) addr, &size);
500 while (new_fd < 0 && errno == EINTR);
501 return new_fd < 0? -ERRNO_TO_PARA_ERROR(errno) : new_fd;
505 * prepare a structure for \p AF_UNIX socket addresses
507 * \param u pointer to the struct to be prepared
508 * \param name the socket pathname
510 * This just copies \a name to the sun_path component of \a u.
512 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
513 * than \p UNIX_PATH_MAX.
515 int init_unix_addr(struct sockaddr_un *u, const char *name)
517 if (strlen(name) >= UNIX_PATH_MAX)
518 return -E_NAME_TOO_LONG;
519 memset(u->sun_path, 0, UNIX_PATH_MAX);
520 u->sun_family = PF_UNIX;
521 strcpy(u->sun_path, name);
526 * Prepare, create, and bind a socket for local communication.
528 * \param name The socket pathname.
529 * \param unix_addr Pointer to the \p AF_UNIX socket structure.
530 * \param mode The desired mode of the socket.
532 * This functions creates a local socket for sequenced, reliable,
533 * two-way, connection-based byte streams.
535 * \return The file descriptor, on success, negative on errors.
541 int create_local_socket(const char *name, struct sockaddr_un *unix_addr,
546 ret = init_unix_addr(unix_addr, name);
549 ret = socket(PF_UNIX, SOCK_STREAM, 0);
551 return -ERRNO_TO_PARA_ERROR(errno);
553 ret = bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX);
555 ret = -ERRNO_TO_PARA_ERROR(errno);
559 if (chmod(name, mode) < 0)
568 ssize_t send_cred_buffer(int sock, char *buf)
570 return send_buffer(sock, buf);
572 int recv_cred_buffer(int fd, char *buf, size_t size)
574 return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
576 #else /* HAVE_UCRED */
578 * send NULL terminated buffer and Unix credentials of the current process
580 * \param sock the socket file descriptor
581 * \param buf the buffer to be sent
583 * \return On success, this call returns the number of characters sent. On
584 * error, \p -E_SENDMSG is returned.
586 * \sa okir's Black Hats Manual
589 ssize_t send_cred_buffer(int sock, char *buf)
591 char control[sizeof(struct cmsghdr) + 10];
593 struct cmsghdr *cmsg;
594 static struct iovec iov;
600 iov.iov_len = strlen(buf);
604 /* compose the message */
605 memset(&msg, 0, sizeof(msg));
608 msg.msg_control = control;
609 msg.msg_controllen = sizeof(control);
610 /* attach the ucred struct */
611 cmsg = CMSG_FIRSTHDR(&msg);
612 cmsg->cmsg_level = SOL_SOCKET;
613 cmsg->cmsg_type = SCM_CREDENTIALS;
614 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
615 *(struct ucred *)CMSG_DATA(cmsg) = c;
616 msg.msg_controllen = cmsg->cmsg_len;
617 ret = sendmsg(sock, &msg, 0);
623 static void dispose_fds(int *fds, unsigned num)
627 for (i = 0; i < num; i++)
632 * receive a buffer and the Unix credentials of the sending process
634 * \param fd the socket file descriptor
635 * \param buf the buffer to store the message
636 * \param size the size of \a buffer
638 * \return negative on errors, the user id on success.
640 * \sa okir's Black Hats Manual
643 int recv_cred_buffer(int fd, char *buf, size_t size)
647 struct cmsghdr *cmsg;
653 setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
654 memset(&msg, 0, sizeof(msg));
655 memset(buf, 0, size);
660 msg.msg_control = control;
661 msg.msg_controllen = sizeof(control);
662 if (recvmsg(fd, &msg, 0) < 0)
664 result = -E_SCM_CREDENTIALS;
665 cmsg = CMSG_FIRSTHDR(&msg);
667 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
668 == SCM_CREDENTIALS) {
669 memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
672 if (cmsg->cmsg_level == SOL_SOCKET
673 && cmsg->cmsg_type == SCM_RIGHTS) {
674 dispose_fds((int *) CMSG_DATA(cmsg),
675 (cmsg->cmsg_len - CMSG_LEN(0))
678 cmsg = CMSG_NXTHDR(&msg, cmsg);
682 #endif /* HAVE_UCRED */
685 * receive a buffer and check for a pattern
687 * \param fd the file descriptor to receive from
688 * \param pattern the expected pattern
689 * \param bufsize the size of the internal buffer
691 * \return Positive if \a pattern was received, negative otherwise.
693 * This function creates a buffer of size \a bufsize and tries
694 * to receive at most \a bufsize bytes from file descriptor \a fd.
695 * If at least \p strlen(\a pattern) bytes were received, the beginning of
696 * the received buffer is compared with \a pattern, ignoring case.
701 int recv_pattern(int fd, const char *pattern, size_t bufsize)
703 size_t len = strlen(pattern);
704 char *buf = para_malloc(bufsize + 1);
705 int ret = -E_RECV_PATTERN, n = recv_buffer(fd, buf, bufsize);
709 if (strncasecmp(buf, pattern, len))
714 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n, pattern);
716 PARA_NOTICE_LOG("recvd: %s\n", buf);