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 * \return The socket fd on success, -E_SOCKET on errors.
296 * Create an IPv4 socket for sequenced, reliable, two-way, connection-based
301 int get_stream_socket(int domain
)
305 if ((socket_fd
= socket(domain
, SOCK_STREAM
, 0)) == -1)
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
;
333 static int setserversockopts(int socket_fd
)
337 if (setsockopt(socket_fd
, SOL_SOCKET
, SO_REUSEADDR
, &yes
,
339 return -E_SETSOCKOPT
;
344 * prepare a structure for \p AF_UNIX socket addresses
346 * \param u pointer to the struct to be prepared
347 * \param name the socket pathname
349 * This just copies \a name to the sun_path component of \a u.
351 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
352 * than \p UNIX_PATH_MAX.
354 int init_unix_addr(struct sockaddr_un
*u
, const char *name
)
356 if (strlen(name
) >= UNIX_PATH_MAX
)
357 return -E_NAME_TOO_LONG
;
358 memset(u
->sun_path
, 0, UNIX_PATH_MAX
);
359 u
->sun_family
= PF_UNIX
;
360 strcpy(u
->sun_path
, name
);
365 * Prepare, create, and bind a socket for local communication.
367 * \param name The socket pathname.
368 * \param unix_addr Pointer to the \p AF_UNIX socket structure.
369 * \param mode The desired mode of the socket.
371 * This functions creates a local socket for sequenced, reliable,
372 * two-way, connection-based byte streams.
374 * \return The file descriptor, on success, negative on errors.
380 int create_local_socket(const char *name
, struct sockaddr_un
*unix_addr
,
385 ret
= init_unix_addr(unix_addr
, name
);
388 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
392 if (bind(fd
, (struct sockaddr
*) unix_addr
, UNIX_PATH_MAX
) < 0)
395 if (chmod(name
, mode
) < 0)
404 ssize_t
send_cred_buffer(int sock
, char *buf
)
406 return send_buffer(sock
, buf
);
408 int recv_cred_buffer(int fd
, char *buf
, size_t size
)
410 return recv_buffer(fd
, buf
, size
) > 0? 1 : -E_RECVMSG
;
412 #else /* HAVE_UCRED */
414 * send NULL terminated buffer and Unix credentials of the current process
416 * \param sock the socket file descriptor
417 * \param buf the buffer to be sent
419 * \return On success, this call returns the number of characters sent. On
420 * error, \p -E_SENDMSG is returned.
422 * \sa okir's Black Hats Manual
425 ssize_t
send_cred_buffer(int sock
, char *buf
)
427 char control
[sizeof(struct cmsghdr
) + 10];
429 struct cmsghdr
*cmsg
;
430 static struct iovec iov
;
436 iov
.iov_len
= strlen(buf
);
440 /* compose the message */
441 memset(&msg
, 0, sizeof(msg
));
444 msg
.msg_control
= control
;
445 msg
.msg_controllen
= sizeof(control
);
446 /* attach the ucred struct */
447 cmsg
= CMSG_FIRSTHDR(&msg
);
448 cmsg
->cmsg_level
= SOL_SOCKET
;
449 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
450 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
451 *(struct ucred
*)CMSG_DATA(cmsg
) = c
;
452 msg
.msg_controllen
= cmsg
->cmsg_len
;
453 ret
= sendmsg(sock
, &msg
, 0);
459 static void dispose_fds(int *fds
, unsigned num
)
463 for (i
= 0; i
< num
; i
++)
468 * receive a buffer and the Unix credentials of the sending process
470 * \param fd the socket file descriptor
471 * \param buf the buffer to store the message
472 * \param size the size of \a buffer
474 * \return negative on errors, the user id on success.
476 * \sa okir's Black Hats Manual
479 int recv_cred_buffer(int fd
, char *buf
, size_t size
)
483 struct cmsghdr
*cmsg
;
489 setsockopt(fd
, SOL_SOCKET
, SO_PASSCRED
, &yes
, sizeof(int));
490 memset(&msg
, 0, sizeof(msg
));
491 memset(buf
, 0, size
);
496 msg
.msg_control
= control
;
497 msg
.msg_controllen
= sizeof(control
);
498 if (recvmsg(fd
, &msg
, 0) < 0)
500 result
= -E_SCM_CREDENTIALS
;
501 cmsg
= CMSG_FIRSTHDR(&msg
);
503 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
504 == SCM_CREDENTIALS
) {
505 memcpy(&cred
, CMSG_DATA(cmsg
), sizeof(struct ucred
));
508 if (cmsg
->cmsg_level
== SOL_SOCKET
509 && cmsg
->cmsg_type
== SCM_RIGHTS
) {
510 dispose_fds((int *) CMSG_DATA(cmsg
),
511 (cmsg
->cmsg_len
- CMSG_LEN(0))
514 cmsg
= CMSG_NXTHDR(&msg
, cmsg
);
518 #endif /* HAVE_UCRED */
520 /** how many pending connections queue will hold */
524 * create a socket, bind it and listen
526 * \param port the tcp port to listen on
528 * \return The file descriptor of the created socket, negative
531 * \sa get_stream_socket()
536 int init_tcp_socket(int port
)
538 struct sockaddr_in my_addr
;
539 int fd
, ret
= get_stream_socket(AF_INET
);
544 ret
= setserversockopts(fd
);
547 init_sockaddr(&my_addr
, port
, NULL
);
549 if (bind(fd
, (struct sockaddr
*)&my_addr
,
550 sizeof(struct sockaddr
)) == -1) {
551 PARA_CRIT_LOG("bind error: %s\n", strerror(errno
));
555 if (listen(fd
, BACKLOG
) == -1)
557 PARA_INFO_LOG("listening on port %d, fd %d\n", port
, fd
);
565 * receive a buffer and check for a pattern
567 * \param fd the file descriptor to receive from
568 * \param pattern the expected pattern
569 * \param bufsize the size of the internal buffer
571 * \return Positive if \a pattern was received, negative otherwise.
573 * This function creates a buffer of size \a bufsize and tries
574 * to receive at most \a bufsize bytes from file descriptor \a fd.
575 * If at least \p strlen(\a pattern) bytes were received, the beginning of
576 * the received buffer is compared with \a pattern, ignoring case.
581 int recv_pattern(int fd
, const char *pattern
, size_t bufsize
)
583 size_t len
= strlen(pattern
);
584 char *buf
= para_malloc(bufsize
+ 1);
585 int ret
= -E_RECV_PATTERN
, n
= recv_buffer(fd
, buf
, bufsize
);
589 if (strncasecmp(buf
, pattern
, len
))
594 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n
, pattern
);
596 PARA_NOTICE_LOG("recvd: %s\n", buf
);