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. */
11 /* At least NetBSD needs these. */
19 #define AI_ADDRCONFIG 0
29 /** Information about one encrypted connection. */
31 /** Function used to decrypt received data. */
33 /** Function used to encrypt data to be sent. */
36 * Context-dependent data (crypt keys), passed verbatim to the above
41 /** Array holding per fd crypt data. */
42 static struct crypt_data *crypt_data_array;
43 /** Current size of the crypt data array. */
44 static unsigned cda_size = 0;
47 * Activate encryption for one file descriptor.
49 * \param fd The file descriptor.
50 * \param recv_f The function used for decrypting received data.
51 * \param send_f The function used for encrypting before sending.
52 * \param private_data User data supplied by the caller.
54 void enable_crypt(int fd, crypt_function *recv_f, crypt_function *send_f,
57 if (fd + 1 > cda_size) {
58 crypt_data_array = para_realloc(crypt_data_array,
59 (fd + 1) * sizeof(struct crypt_data));
60 memset(crypt_data_array + cda_size, 0,
61 (fd + 1 - cda_size) * sizeof(struct crypt_data));
64 crypt_data_array[fd].recv = recv_f;
65 crypt_data_array[fd].send = send_f;
66 crypt_data_array[fd].private_data = private_data;
67 PARA_INFO_LOG("rc4 encryption activated for fd %d\n", fd);
71 * Deactivate encryption for a given fd.
73 * \param fd The file descriptor.
75 * This must be called if and only if \p fd was activated via enable_crypt().
77 void disable_crypt(int fd)
79 if (cda_size < fd + 1)
81 crypt_data_array[fd].recv = NULL;
82 crypt_data_array[fd].send = NULL;
83 crypt_data_array[fd].private_data = NULL;
88 * Determine the socket type for a given layer-4 protocol.
90 * \param l4type The symbolic name of the transport-layer protocol.
92 * \sa ip(7), socket(2)
94 static inline int sock_type(const unsigned l4type)
97 case IPPROTO_UDP: return SOCK_DGRAM;
98 case IPPROTO_TCP: return SOCK_STREAM;
99 case IPPROTO_DCCP: return SOCK_DCCP;
101 return -1; /* not supported here */
105 * Pretty-print transport-layer name.
107 static const char *layer4_name(const unsigned l4type)
110 case IPPROTO_UDP: return "UDP";
111 case IPPROTO_TCP: return "TCP";
112 case IPPROTO_DCCP: return "DCCP";
114 return "UNKNOWN PROTOCOL";
118 * Resolve IPv4/IPv6 address and create a ready-to-use active or passive socket.
120 * \param l3type The layer-3 type (\p AF_INET, \p AF_INET6, \p AF_UNSPEC).
121 * \param l4type The layer-4 type (\p IPPROTO_xxx).
122 * \param passive Whether this is a passive (1) or active (0) socket.
123 * \param host Remote or local hostname or IPv/6 address string.
124 * \param port_number Decimal port number.
126 * This creates a ready-made IPv4/v6 socket structure after looking up the
127 * necessary parameters. The interpretation of \a host depends on the value of
129 * - on a passive socket host is interpreted as an interface IPv4/6 address
130 * (can be left NULL);
131 * - on an active socket, \a host is the peer DNS name or IPv4/6 address
133 * - \a port_number is in either case the numeric port number (not service
136 * Furthermore, bind(2) is called on passive sockets, and connect(2) on active
137 * sockets. The algorithm tries all possible address combinations until it
140 * \return This function returns 1 on success and \a -E_ADDRESS_LOOKUP when no
141 * matching connection could be set up (with details in the error log).
143 * \sa ipv6(7), getaddrinfo(3), bind(2), connect(2).
145 int makesock(unsigned l3type, unsigned l4type, int passive,
146 const char *host, unsigned short port_number)
148 struct addrinfo *local = NULL, *src,
149 *remote = NULL, *dst, hints;
150 char *port = make_message("%u", port_number);
151 int rc, on = 1, sockfd = -1,
152 socktype = sock_type(l4type);
154 /* Set up address hint structure */
155 memset(&hints, 0, sizeof(hints));
156 hints.ai_family = l3type;
157 /* getaddrinfo does not really work well with SOCK_DCCP */
158 if (socktype == SOCK_DGRAM || socktype == SOCK_STREAM)
159 hints.ai_socktype = socktype;
161 /* only use addresses available on the host */
162 hints.ai_flags = AI_ADDRCONFIG;
163 if (l3type == AF_INET6)
164 /* use v4-mapped-v6 if no v6 addresses found */
165 hints.ai_flags |= AI_V4MAPPED | AI_ALL;
167 if (passive && host == NULL)
168 hints.ai_flags |= AI_PASSIVE;
170 /* Obtain local/remote address information */
171 if ((rc = getaddrinfo(host, port, &hints, passive ? &local : &remote))) {
172 PARA_ERROR_LOG("can not resolve %s address %s#%s: %s.\n",
174 host? : (passive? "[loopback]" : "[localhost]"),
175 port, gai_strerror(rc));
176 return -E_ADDRESS_LOOKUP;
179 /* Iterate over all src/dst combination, exhausting dst first */
180 for (src = local, dst = remote; src != NULL || dst != NULL; /* no op */ ) {
181 if (src && dst && src->ai_family == AF_INET
182 && dst->ai_family == AF_INET6)
183 goto get_next_dst; /* v4 -> v6 is not possible */
185 sockfd = socket(src ? src->ai_family : dst->ai_family,
191 * Set those options that need to be set before establishing
192 * the connection. Reuse the address on passive (listening)
193 * sockets to avoid failure on restart.
195 if (passive && setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
196 &on, sizeof(on)) == -1) {
197 PARA_ERROR_LOG("can not set SO_REUSEADDR: %s\n",
199 return -ERRNO_TO_PARA_ERROR(errno);
203 if (bind(sockfd, src->ai_addr, src->ai_addrlen) < 0) {
207 if (!dst) /* bind-only completed successfully */
211 if (dst && connect(sockfd, dst->ai_addr, dst->ai_addrlen) == 0)
212 break; /* connection completed successfully */
215 if (dst && (dst = dst->ai_next))
218 if (src && (src = src->ai_next)) /* restart inner loop */
224 freeaddrinfo(remote);
226 if (src == NULL && dst == NULL) {
227 PARA_ERROR_LOG("can not create %s socket %s#%s.\n",
228 layer4_name(l4type), host? : (passive?
229 "[loopback]" : "[localhost]"), port);
230 return -ERRNO_TO_PARA_ERROR(errno);
236 * Create a passive / listening socket.
238 * \param l3type The network-layer type (\p AF_xxx).
239 * \param l4type The transport-layer type (\p IPPROTO_xxx).
240 * \param port The decimal port number to listen on.
242 * \return Positive integer (socket descriptor) on success, negative value
245 * \sa makesock(), ip(7), ipv6(7), bind(2), listen(2).
247 int para_listen(unsigned l3type, unsigned l4type, unsigned short port)
249 int ret, fd = makesock(l3type, l4type, 1, NULL, port);
252 ret = listen(fd, BACKLOG);
255 return -ERRNO_TO_PARA_ERROR(errno);
257 PARA_INFO_LOG("listening on %s port %u, fd %d\n",
258 layer4_name(l4type), port, fd);
264 * Print numeric host and port number (beware - uses static char).
266 * \param sa The IPv4/IPv6 socket address to use.
267 * \param len The length of \p sa.
269 * \sa getnameinfo(3).
271 char *host_and_port(struct sockaddr *sa, socklen_t len)
273 static char output[NI_MAXHOST + NI_MAXSERV + 2];
274 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
277 ret = getnameinfo(sa, len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
278 NI_NUMERICHOST | NI_NUMERICSERV);
280 PARA_WARNING_LOG("hostname lookup error (%s).\n", gai_strerror(ret));
281 sprintf(output, "(unknown)");
283 sprintf(output, "%s#%s", hbuf, sbuf);
289 * Look up the local or remote side of a connected socket structure.
291 * \param fd The socket descriptor of the connected socket.
292 * \param getname Either \p getsockname() for local, or \p getpeername() for
295 * \return A static character string identifying hostname and port of the
298 * \sa getsockname(2), getpeername(2).
300 static char *__get_sock_name(int fd, int (*getname)(int, struct sockaddr*,
303 struct sockaddr_storage ss;
304 socklen_t sslen = sizeof(ss);
306 if (getname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
307 static char *dont_know = "(don't know)";
308 PARA_ERROR_LOG("can not determine address from fd %d: %s\n",
309 fd, strerror(errno));
312 return host_and_port((struct sockaddr *)&ss, sslen);
315 char *local_name(int sockfd)
317 return __get_sock_name(sockfd, getsockname);
320 char *remote_name(int sockfd)
322 return __get_sock_name(sockfd, getpeername);
326 * Send out a buffer, resend on short writes.
328 * \param fd The file descriptor.
329 * \param buf The buffer to be sent.
330 * \param len The length of \a buf.
332 * \return Standard. In any case, the number of bytes actually sent is stored
335 static int sendall(int fd, const char *buf, size_t *len)
341 while (*len < total) {
342 int ret = send(fd, buf + *len, total - *len, 0);
344 return -ERRNO_TO_PARA_ERROR(errno);
351 * Encrypt and send a binary buffer.
353 * \param fd The file descriptor.
354 * \param buf The buffer to be encrypted and sent.
355 * \param len The length of \a buf.
357 * Check if encryption is available. If yes, encrypt the given buffer. Send
358 * out the buffer, encrypted or not, and try to resend the remaing part in case
363 int send_bin_buffer(int fd, const char *buf, size_t len)
366 crypt_function *cf = NULL;
369 PARA_CRIT_LOG("%s", "len == 0\n");
370 if (fd + 1 <= cda_size)
371 cf = crypt_data_array[fd].send;
373 void *private = crypt_data_array[fd].private_data;
374 /* RC4 may write more than len to the output buffer */
375 unsigned char *outbuf = para_malloc(ROUND_UP(len, 8));
376 (*cf)(len, (unsigned char *)buf, outbuf, private);
377 ret = sendall(fd, (char *)outbuf, &len);
380 ret = sendall(fd, buf, &len);
385 * Encrypt and send null terminated buffer.
387 * \param fd The file descriptor.
388 * \param buf The null-terminated buffer to be send.
390 * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
394 int send_buffer(int fd, const char *buf)
396 return send_bin_buffer(fd, buf, strlen(buf));
401 * Send and encrypt a buffer given by a format string.
403 * \param fd The file descriptor.
404 * \param fmt A format string.
408 __printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
413 PARA_VSPRINTF(fmt, msg);
414 ret = send_buffer(fd, msg);
420 * Receive and decrypt.
422 * \param fd The file descriptor.
423 * \param buf The buffer to write the decrypted data to.
424 * \param size The size of \a buf.
426 * Receive at most \a size bytes from file descriptor \a fd. If encryption is
427 * available, decrypt the received buffer.
429 * \return The number of bytes received on success, negative on errors.
433 __must_check int recv_bin_buffer(int fd, char *buf, size_t size)
436 crypt_function *cf = NULL;
438 if (fd + 1 <= cda_size)
439 cf = crypt_data_array[fd].recv;
441 unsigned char *tmp = para_malloc(size);
442 void *private = crypt_data_array[fd].private_data;
443 n = recv(fd, tmp, size, 0);
446 unsigned char *b = (unsigned char *)buf;
447 (*cf)(numbytes, tmp, b, private);
451 n = recv(fd, buf, size, 0);
453 return -ERRNO_TO_PARA_ERROR(errno);
458 * Receive, decrypt and write terminating NULL byte.
460 * \param fd The file descriptor.
461 * \param buf The buffer to write the decrypted data to.
462 * \param size The size of \a buf.
464 * Read and decrypt at most \a size - 1 bytes from file descriptor \a fd and
465 * write a NULL byte at the end of the received data.
467 * \return The return value of the underlying call to \a recv_bin_buffer().
469 * \sa recv_bin_buffer()
471 int recv_buffer(int fd, char *buf, size_t size)
476 n = recv_bin_buffer(fd, buf, size - 1);
485 * Wrapper around the accept system call.
487 * \param fd The listening socket.
488 * \param addr Structure which is filled in with the address of the peer socket.
489 * \param size Should contain the size of the structure pointed to by \a addr.
491 * Accept incoming connections on \a addr. Retry if interrupted.
493 * \return The new file descriptor on success, negative on errors.
497 int para_accept(int fd, void *addr, socklen_t size)
502 new_fd = accept(fd, (struct sockaddr *) addr, &size);
503 while (new_fd < 0 && errno == EINTR);
504 return new_fd < 0? -ERRNO_TO_PARA_ERROR(errno) : new_fd;
508 * Prepare a structure for \p AF_UNIX socket addresses.
510 * \param u Pointer to the struct to be prepared.
511 * \param name The socket pathname.
513 * This just copies \a name to the sun_path component of \a u.
515 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
516 * than \p UNIX_PATH_MAX.
518 static int init_unix_addr(struct sockaddr_un *u, const char *name)
520 if (strlen(name) >= UNIX_PATH_MAX)
521 return -E_NAME_TOO_LONG;
522 memset(u->sun_path, 0, UNIX_PATH_MAX);
523 u->sun_family = PF_UNIX;
524 strcpy(u->sun_path, name);
529 * Prepare, create, and bind a socket for local communication.
531 * \param name The socket pathname.
532 * \param unix_addr Pointer to the \p AF_UNIX socket structure.
533 * \param mode The desired mode of the socket.
535 * This function creates a local socket for sequenced, reliable,
536 * two-way, connection-based byte streams.
538 * \return The file descriptor, on success, negative on errors.
544 int create_local_socket(const char *name, struct sockaddr_un *unix_addr,
549 ret = init_unix_addr(unix_addr, name);
552 ret = socket(PF_UNIX, SOCK_STREAM, 0);
554 return -ERRNO_TO_PARA_ERROR(errno);
556 ret = bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX);
558 ret = -ERRNO_TO_PARA_ERROR(errno);
562 if (chmod(name, mode) < 0)
571 * Prepare, create, and connect to a Unix domain socket for local communication.
573 * \param name The socket pathname.
575 * This function creates a local socket for sequenced, reliable, two-way,
576 * connection-based byte streams.
578 * \return The file descriptor, on success, negative on errors.
580 * \sa create_local_socket(), unix(7), connect(2).
582 int create_remote_socket(const char *name)
584 struct sockaddr_un unix_addr;
587 ret = init_unix_addr(&unix_addr, name);
590 fd = socket(PF_UNIX, SOCK_STREAM, 0);
592 return -ERRNO_TO_PARA_ERROR(errno);
593 if (connect(fd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) == -1) {
594 ret = -ERRNO_TO_PARA_ERROR(errno);
604 ssize_t send_cred_buffer(int sock, char *buf)
606 return send_buffer(sock, buf);
608 int recv_cred_buffer(int fd, char *buf, size_t size)
610 return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
612 #else /* HAVE_UCRED */
614 * Send \p NULL-terminated buffer and Unix credentials of the current process.
616 * \param sock The socket file descriptor.
617 * \param buf The buffer to be sent.
619 * \return On success, this call returns the number of characters sent. On
620 * error, \p -E_SENDMSG is returned.
622 * \sa sendmsg(2), okir's Black Hats Manual.
624 ssize_t send_cred_buffer(int sock, char *buf)
626 char control[sizeof(struct cmsghdr) + 10];
628 struct cmsghdr *cmsg;
629 static struct iovec iov;
635 iov.iov_len = strlen(buf);
639 /* compose the message */
640 memset(&msg, 0, sizeof(msg));
643 msg.msg_control = control;
644 msg.msg_controllen = sizeof(control);
645 /* attach the ucred struct */
646 cmsg = CMSG_FIRSTHDR(&msg);
647 cmsg->cmsg_level = SOL_SOCKET;
648 cmsg->cmsg_type = SCM_CREDENTIALS;
649 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
650 *(struct ucred *)CMSG_DATA(cmsg) = c;
651 msg.msg_controllen = cmsg->cmsg_len;
652 ret = sendmsg(sock, &msg, 0);
658 static void dispose_fds(int *fds, unsigned num)
662 for (i = 0; i < num; i++)
667 * Receive a buffer and the Unix credentials of the sending process.
669 * \param fd the socket file descriptor.
670 * \param buf the buffer to store the message.
671 * \param size the size of \a buffer.
673 * \return negative on errors, the user id on success.
675 * \sa recvmsg(2), okir's Black Hats Manual.
677 int recv_cred_buffer(int fd, char *buf, size_t size)
681 struct cmsghdr *cmsg;
687 setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
688 memset(&msg, 0, sizeof(msg));
689 memset(buf, 0, size);
694 msg.msg_control = control;
695 msg.msg_controllen = sizeof(control);
696 if (recvmsg(fd, &msg, 0) < 0)
698 result = -E_SCM_CREDENTIALS;
699 cmsg = CMSG_FIRSTHDR(&msg);
701 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
702 == SCM_CREDENTIALS) {
703 memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
706 if (cmsg->cmsg_level == SOL_SOCKET
707 && cmsg->cmsg_type == SCM_RIGHTS) {
708 dispose_fds((int *) CMSG_DATA(cmsg),
709 (cmsg->cmsg_len - CMSG_LEN(0))
712 cmsg = CMSG_NXTHDR(&msg, cmsg);
716 #endif /* HAVE_UCRED */
719 * Receive a buffer and check for a pattern.
721 * \param fd The file descriptor to receive from.
722 * \param pattern The expected pattern.
723 * \param bufsize The size of the internal buffer.
725 * \return Positive if \a pattern was received, negative otherwise.
727 * This function creates a buffer of size \a bufsize and tries
728 * to receive at most \a bufsize bytes from file descriptor \a fd.
729 * If at least \p strlen(\a pattern) bytes were received, the beginning of
730 * the received buffer is compared with \a pattern, ignoring case.
732 * \sa recv_buffer(), \sa strncasecmp(3).
734 int recv_pattern(int fd, const char *pattern, size_t bufsize)
736 size_t len = strlen(pattern);
737 char *buf = para_malloc(bufsize + 1);
738 int ret = -E_RECV_PATTERN, n = recv_buffer(fd, buf, bufsize);
742 if (strncasecmp(buf, pattern, len))
747 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n,
750 PARA_NOTICE_LOG("recvd: %s\n", buf);