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. */
9 #include <netdb.h> /* hostent */
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 * Initialize a struct sockaddr_in.
78 * \param addr A pointer to the struct to be initialized.
79 * \param port The port number to use.
80 * \param he The address to use.
82 * If \a he is null (server mode), \a addr->sin_addr is initialized with \p
83 * INADDR_ANY. Otherwise, the address given by \a he is copied to addr.
85 static void init_sockaddr(struct sockaddr_in *addr, int port, const struct hostent *he)
88 addr->sin_family = AF_INET;
89 /* short, network byte order */
90 addr->sin_port = htons(port);
92 addr->sin_addr = *((struct in_addr *)he->h_addr);
94 addr->sin_addr.s_addr = INADDR_ANY;
95 /* zero the rest of the struct */
96 memset(&addr->sin_zero, '\0', 8);
100 * Send out a buffer, resend on short writes.
102 * \param fd The file descriptor.
103 * \param buf The buffer to be sent.
104 * \param len The length of \a buf.
106 * \return Standard. In any case, the number of bytes actually sent is stored
109 static int sendall(int fd, const char *buf, size_t *len)
115 while (*len < total) {
116 int ret = send(fd, buf + *len, total - *len, 0);
118 return -ERRNO_TO_PARA_ERROR(errno);
125 * Encrypt and send a binary buffer.
127 * \param fd The file descriptor.
128 * \param buf The buffer to be encrypted and sent.
129 * \param len The length of \a buf.
131 * Check if encryption is available. If yes, encrypt the given buffer. Send
132 * out the buffer, encrypted or not, and try to resend the remaing part in case
137 int send_bin_buffer(int fd, const char *buf, size_t len)
140 crypt_function *cf = NULL;
143 PARA_CRIT_LOG("%s", "len == 0\n");
144 if (fd + 1 <= cda_size)
145 cf = crypt_data_array[fd].send;
147 void *private = crypt_data_array[fd].private_data;
148 /* RC4 may write more than len to the output buffer */
149 unsigned char *outbuf = para_malloc(ROUND_UP(len, 8));
150 (*cf)(len, (unsigned char *)buf, outbuf, private);
151 ret = sendall(fd, (char *)outbuf, &len);
154 ret = sendall(fd, buf, &len);
159 * Encrypt and send null terminated buffer.
161 * \param fd The file descriptor.
162 * \param buf The null-terminated buffer to be send.
164 * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
168 int send_buffer(int fd, const char *buf)
170 return send_bin_buffer(fd, buf, strlen(buf));
175 * Send and encrypt a buffer given by a format string.
177 * \param fd The file descriptor.
178 * \param fmt A format string.
182 __printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
187 PARA_VSPRINTF(fmt, msg);
188 ret = send_buffer(fd, msg);
194 * Receive and decrypt.
196 * \param fd The file descriptor.
197 * \param buf The buffer to write the decrypted data to.
198 * \param size The size of \a buf.
200 * Receive at most \a size bytes from file descriptor \a fd. If encryption is
201 * available, decrypt the received buffer.
203 * \return The number of bytes received on success, negative on errors.
207 __must_check int recv_bin_buffer(int fd, char *buf, size_t size)
210 crypt_function *cf = NULL;
212 if (fd + 1 <= cda_size)
213 cf = crypt_data_array[fd].recv;
215 unsigned char *tmp = para_malloc(size);
216 void *private = crypt_data_array[fd].private_data;
217 n = recv(fd, tmp, size, 0);
220 unsigned char *b = (unsigned char *)buf;
221 (*cf)(numbytes, tmp, b, private);
225 n = recv(fd, buf, size, 0);
227 return -ERRNO_TO_PARA_ERROR(errno);
232 * Receive, decrypt and write terminating NULL byte.
234 * \param fd The file descriptor.
235 * \param buf The buffer to write the decrypted data to.
236 * \param size The size of \a buf.
238 * Read and decrypt at most \a size - 1 bytes from file descriptor \a fd and
239 * write a NULL byte at the end of the received data.
241 * \return The return value of the underlying call to \a recv_bin_buffer().
243 * \sa recv_bin_buffer()
245 int recv_buffer(int fd, char *buf, size_t size)
250 n = recv_bin_buffer(fd, buf, size - 1);
259 * Establish a tcp connection.
261 * \param host Hostname or IPv4 address.
262 * \param port The tcp port.
264 * \return Negative on errors, a valid file descriptor on success.
266 int tcp_connect(char *host, int port)
268 struct sockaddr_in addr;
272 PARA_INFO_LOG("getting host info of %s\n", host);
273 /* FIXME: gethostbyname() is obsolete */
274 he = gethostbyname(host);
276 return -ERRNO_TO_PARA_ERROR(h_errno);
277 init_sockaddr(&addr, port, he);
278 ret = get_stream_socket(AF_INET);
282 ret = PARA_CONNECT(fd, &addr);
290 * A wrapper around socket(2).
292 * \param domain The communication domain that selects the protocol family.
294 * Create an IPv4 socket for sequenced, reliable, two-way, connection-based
297 * \return The socket fd on success, negative on errors.
301 int get_stream_socket(int domain)
303 int fd = socket(domain, SOCK_STREAM, 0);
306 return -ERRNO_TO_PARA_ERROR(errno);
311 * Wrapper around the accept system call.
313 * \param fd The listening socket.
314 * \param addr Structure which is filled in with the address of the peer socket.
315 * \param size Should contain the size of the structure pointed to by \a addr.
317 * Accept incoming connections on \a addr. Retry if interrupted.
319 * \return The new file descriptor on success, negative on errors.
323 int para_accept(int fd, void *addr, socklen_t size)
328 new_fd = accept(fd, (struct sockaddr *) addr, &size);
329 while (new_fd < 0 && errno == EINTR);
330 return new_fd < 0? -ERRNO_TO_PARA_ERROR(errno) : new_fd;
334 * prepare a structure for \p AF_UNIX socket addresses
336 * \param u pointer to the struct to be prepared
337 * \param name the socket pathname
339 * This just copies \a name to the sun_path component of \a u.
341 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
342 * than \p UNIX_PATH_MAX.
344 int init_unix_addr(struct sockaddr_un *u, const char *name)
346 if (strlen(name) >= UNIX_PATH_MAX)
347 return -E_NAME_TOO_LONG;
348 memset(u->sun_path, 0, UNIX_PATH_MAX);
349 u->sun_family = PF_UNIX;
350 strcpy(u->sun_path, name);
355 * Prepare, create, and bind a socket for local communication.
357 * \param name The socket pathname.
358 * \param unix_addr Pointer to the \p AF_UNIX socket structure.
359 * \param mode The desired mode of the socket.
361 * This functions creates a local socket for sequenced, reliable,
362 * two-way, connection-based byte streams.
364 * \return The file descriptor, on success, negative on errors.
370 int create_local_socket(const char *name, struct sockaddr_un *unix_addr,
375 ret = init_unix_addr(unix_addr, name);
378 ret = socket(PF_UNIX, SOCK_STREAM, 0);
380 return -ERRNO_TO_PARA_ERROR(errno);
382 ret = bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX);
384 ret = -ERRNO_TO_PARA_ERROR(errno);
388 if (chmod(name, mode) < 0)
397 ssize_t send_cred_buffer(int sock, char *buf)
399 return send_buffer(sock, buf);
401 int recv_cred_buffer(int fd, char *buf, size_t size)
403 return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
405 #else /* HAVE_UCRED */
407 * send NULL terminated buffer and Unix credentials of the current process
409 * \param sock the socket file descriptor
410 * \param buf the buffer to be sent
412 * \return On success, this call returns the number of characters sent. On
413 * error, \p -E_SENDMSG is returned.
415 * \sa okir's Black Hats Manual
418 ssize_t send_cred_buffer(int sock, char *buf)
420 char control[sizeof(struct cmsghdr) + 10];
422 struct cmsghdr *cmsg;
423 static struct iovec iov;
429 iov.iov_len = strlen(buf);
433 /* compose the message */
434 memset(&msg, 0, sizeof(msg));
437 msg.msg_control = control;
438 msg.msg_controllen = sizeof(control);
439 /* attach the ucred struct */
440 cmsg = CMSG_FIRSTHDR(&msg);
441 cmsg->cmsg_level = SOL_SOCKET;
442 cmsg->cmsg_type = SCM_CREDENTIALS;
443 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
444 *(struct ucred *)CMSG_DATA(cmsg) = c;
445 msg.msg_controllen = cmsg->cmsg_len;
446 ret = sendmsg(sock, &msg, 0);
452 static void dispose_fds(int *fds, unsigned num)
456 for (i = 0; i < num; i++)
461 * receive a buffer and the Unix credentials of the sending process
463 * \param fd the socket file descriptor
464 * \param buf the buffer to store the message
465 * \param size the size of \a buffer
467 * \return negative on errors, the user id on success.
469 * \sa okir's Black Hats Manual
472 int recv_cred_buffer(int fd, char *buf, size_t size)
476 struct cmsghdr *cmsg;
482 setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
483 memset(&msg, 0, sizeof(msg));
484 memset(buf, 0, size);
489 msg.msg_control = control;
490 msg.msg_controllen = sizeof(control);
491 if (recvmsg(fd, &msg, 0) < 0)
493 result = -E_SCM_CREDENTIALS;
494 cmsg = CMSG_FIRSTHDR(&msg);
496 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
497 == SCM_CREDENTIALS) {
498 memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
501 if (cmsg->cmsg_level == SOL_SOCKET
502 && cmsg->cmsg_type == SCM_RIGHTS) {
503 dispose_fds((int *) CMSG_DATA(cmsg),
504 (cmsg->cmsg_len - CMSG_LEN(0))
507 cmsg = CMSG_NXTHDR(&msg, cmsg);
511 #endif /* HAVE_UCRED */
513 /** how many pending connections queue will hold */
517 * Create a tcp socket, bind it and listen on the given port.
519 * \param port The tcp port to listen on.
521 * \return The file descriptor of the created socket, negative on errors.
523 * \sa get_stream_socket()
528 int tcp_listen(int port)
530 struct sockaddr_in my_addr;
531 int fd, ret = get_stream_socket(AF_INET);
537 ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &ret, sizeof(int));
539 ret = -ERRNO_TO_PARA_ERROR(errno);
542 init_sockaddr(&my_addr, port, NULL);
543 ret = bind(fd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
545 ret = -ERRNO_TO_PARA_ERROR(errno);
548 ret = listen(fd, BACKLOG);
550 ret = -ERRNO_TO_PARA_ERROR(errno);
553 PARA_INFO_LOG("listening on port %d, fd %d\n", port, fd);
561 * receive a buffer and check for a pattern
563 * \param fd the file descriptor to receive from
564 * \param pattern the expected pattern
565 * \param bufsize the size of the internal buffer
567 * \return Positive if \a pattern was received, negative otherwise.
569 * This function creates a buffer of size \a bufsize and tries
570 * to receive at most \a bufsize bytes from file descriptor \a fd.
571 * If at least \p strlen(\a pattern) bytes were received, the beginning of
572 * the received buffer is compared with \a pattern, ignoring case.
577 int recv_pattern(int fd, const char *pattern, size_t bufsize)
579 size_t len = strlen(pattern);
580 char *buf = para_malloc(bufsize + 1);
581 int ret = -E_RECV_PATTERN, n = recv_buffer(fd, buf, bufsize);
585 if (strncasecmp(buf, pattern, len))
590 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n, pattern);
592 PARA_NOTICE_LOG("recvd: %s\n", buf);