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 */
15 /** Information about one encrypted connection. */
17 /** Function used to decrypt received data. */
19 /** Function used to encrypt data to be sent. */
22 * Context-dependent data (crypt keys), passed verbatim to the above
27 /** Array holding per fd crypt data. */
28 static struct crypt_data
*crypt_data_array
;
29 /** Current size of the crypt data array. */
30 static unsigned cda_size
= 0;
33 * activate encryption for one file descriptor
35 * \param fd the file descriptor
36 * \param recv_f the function used for decrypting received data
37 * \param send_f the function used for encrypting before sending
38 * \param private_data user data supplied by the caller
40 void enable_crypt(int fd
, crypt_function
*recv_f
, crypt_function
*send_f
,
43 if (fd
+ 1 > cda_size
) {
44 crypt_data_array
= para_realloc(crypt_data_array
,
45 (fd
+ 1) * sizeof(struct crypt_data
));
46 memset(crypt_data_array
+ cda_size
, 0,
47 (fd
+ 1 - cda_size
) * sizeof(struct crypt_data
));
50 crypt_data_array
[fd
].recv
= recv_f
;
51 crypt_data_array
[fd
].send
= send_f
;
52 crypt_data_array
[fd
].private_data
= private_data
;
53 PARA_INFO_LOG("rc4 encryption activated for fd %d\n", fd
);
57 * deactivate encryption for a given fd
59 * \param fd the file descriptor
61 * This must be called if and only if \p fd was activated via enable_crypt().
63 void disable_crypt(int fd
)
65 if (cda_size
< fd
+ 1)
67 crypt_data_array
[fd
].recv
= NULL
;
68 crypt_data_array
[fd
].send
= NULL
;
69 crypt_data_array
[fd
].private_data
= NULL
;
74 * initialize a struct sockaddr_in
76 * \param addr A pointer to the struct to be initialized
77 * \param port The port number to use
78 * \param he The address to use
80 * If \a he is null (server mode), \a addr->sin_addr is initialized with \p
81 * INADDR_ANY. Otherwise, the address given by \a he is copied to addr.
83 void init_sockaddr(struct sockaddr_in
*addr
, int port
, const struct hostent
*he
)
86 addr
->sin_family
= AF_INET
;
87 /* short, network byte order */
88 addr
->sin_port
= htons(port
);
90 addr
->sin_addr
= *((struct in_addr
*)he
->h_addr
);
92 addr
->sin_addr
.s_addr
= INADDR_ANY
;
93 /* zero the rest of the struct */
94 memset(&addr
->sin_zero
, '\0', 8);
98 * send out a buffer, resend on short writes
100 * \param fd the file descriptor
101 * \param buf The buffer to be sent
102 * \param len The length of \a buf
104 * Due to circumstances beyond your control, the kernel might not send all the
105 * data out in one chunk, and now, my friend, it's up to us to get the data out
106 * there (Beej's Guide to Network Programming).
108 * \return This function returns 1 on success and \a -E_SEND on errors. The
109 * number of bytes actually sent is stored upon successful return in \a len.
111 static int sendall(int fd
, const char *buf
, size_t *len
)
113 size_t total
= 0, bytesleft
= *len
; /* how many we have left to send */
116 while (total
< *len
) {
117 n
= send(fd
, buf
+ total
, bytesleft
, 0);
123 PARA_DEBUG_LOG("short write (%zd byte(s) left)\n",
126 *len
= total
; /* return number actually sent here */
127 return n
== -1? -E_SEND
: 1; /* return 1 on success */
131 * Encrypt and send a binary buffer.
133 * \param fd The file descriptor.
134 * \param buf The buffer to be encrypted and sent.
135 * \param len The length of \a buf.
137 * Check if encryption is available. If yes, encrypt the given buffer. Send
138 * out the buffer, encrypted or not, and try to resend the remaing part in case
141 * \return Positive on success, \p -E_SEND on errors.
143 int send_bin_buffer(int fd
, const char *buf
, size_t len
)
146 crypt_function
*cf
= NULL
;
149 PARA_CRIT_LOG("%s", "len == 0\n");
150 if (fd
+ 1 <= cda_size
)
151 cf
= crypt_data_array
[fd
].send
;
153 void *private = crypt_data_array
[fd
].private_data
;
154 /* RC4 may write more than len to the output buffer */
155 unsigned char *outbuf
= para_malloc(ROUND_UP(len
, 8));
156 (*cf
)(len
, (unsigned char *)buf
, outbuf
, private);
157 ret
= sendall(fd
, (char *)outbuf
, &len
);
160 ret
= sendall(fd
, buf
, &len
);
165 * encrypt and send null terminated buffer.
167 * \param fd the file descriptor
168 * \param buf the null-terminated buffer to be send
170 * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
172 * \return Positive on success, \p -E_SEND on errors.
174 int send_buffer(int fd
, const char *buf
)
176 return send_bin_buffer(fd
, buf
, strlen(buf
));
181 * send and encrypt a buffer given by a format string
183 * \param fd the file descriptor
184 * \param fmt a format string
186 * \return Positive on success, \p -E_SEND on errors.
188 __printf_2_3
int send_va_buffer(int fd
, const char *fmt
, ...)
193 PARA_VSPRINTF(fmt
, msg
);
194 ret
= send_buffer(fd
, msg
);
200 * receive and decrypt.
202 * \param fd the file descriptor
203 * \param buf the buffer to write the decrypted data to
204 * \param size the size of \a buf
206 * Receive at most \a size bytes from file descriptor \a fd. If encryption is
207 * available, decrypt the received buffer.
209 * \return The number of bytes received on success, negative on errors.
213 __must_check
int recv_bin_buffer(int fd
, char *buf
, size_t size
)
216 crypt_function
*cf
= NULL
;
218 if (fd
+ 1 <= cda_size
)
219 cf
= crypt_data_array
[fd
].recv
;
221 unsigned char *tmp
= para_malloc(size
);
222 void *private = crypt_data_array
[fd
].private_data
;
223 n
= recv(fd
, tmp
, size
, 0);
226 unsigned char *b
= (unsigned char *)buf
;
227 (*cf
)(numbytes
, tmp
, b
, private);
231 n
= recv(fd
, buf
, size
, 0);
233 return -ERRNO_TO_PARA_ERROR(errno
);
238 * receive, decrypt and write terminating NULL byte
240 * \param fd the file descriptor
241 * \param buf the buffer to write the decrypted data to
242 * \param size the size of \a buf
244 * Read and decrypt at most \a size - 1 bytes from file descriptor \a fd and
245 * write a NULL byte at the end of the received data.
247 * \return: The return value of the underlying call to \a recv_bin_buffer().
249 * \sa recv_bin_buffer()
251 int recv_buffer(int fd
, char *buf
, size_t size
)
256 n
= recv_bin_buffer(fd
, buf
, size
- 1);
265 * wrapper around gethostbyname
267 * \param host hostname or IPv4 address
268 * \param ret the hostent structure is returned here
270 * \return positive on success, negative on errors. On success, \a ret
271 * contains the return value of the underlying gethostbyname() call.
273 * \sa gethostbyname(2)
275 int get_host_info(char *host
, struct hostent
**ret
)
277 PARA_INFO_LOG("getting host info of %s\n", host
);
278 /* FIXME: gethostbyname() is obsolete */
279 *ret
= gethostbyname(host
);
280 return *ret
? 1 : -E_HOST_INFO
;
284 * A wrapper around socket(2).
286 * \param domain The communication domain that selects the protocol family.
288 * \return The socket fd on success, -E_SOCKET on errors.
290 * Create an IPv4 socket for sequenced, reliable, two-way, connection-based
295 int get_stream_socket(int domain
)
299 if ((socket_fd
= socket(domain
, SOCK_STREAM
, 0)) == -1)
305 * paraslash's wrapper around the accept system call
307 * \param fd the listening socket
308 * \param addr structure which is filled in with the address of the peer socket
309 * \param size should contain the size of the structure pointed to by \a addr
311 * Accept incoming connections on \a addr. Retry if interrupted.
313 * \return The new file descriptor on success, \a -E_ACCEPT on errors.
317 int para_accept(int fd
, void *addr
, socklen_t size
)
322 new_fd
= accept(fd
, (struct sockaddr
*) addr
, &size
);
323 while (new_fd
< 0 && errno
== EINTR
);
324 return new_fd
< 0? -E_ACCEPT
: new_fd
;
327 static int setserversockopts(int socket_fd
)
331 if (setsockopt(socket_fd
, SOL_SOCKET
, SO_REUSEADDR
, &yes
,
333 return -E_SETSOCKOPT
;
338 * prepare a structure for \p AF_UNIX socket addresses
340 * \param u pointer to the struct to be prepared
341 * \param name the socket pathname
343 * This just copies \a name to the sun_path component of \a u.
345 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
346 * than \p UNIX_PATH_MAX.
348 int init_unix_addr(struct sockaddr_un
*u
, const char *name
)
350 if (strlen(name
) >= UNIX_PATH_MAX
)
351 return -E_NAME_TOO_LONG
;
352 memset(u
->sun_path
, 0, UNIX_PATH_MAX
);
353 u
->sun_family
= PF_UNIX
;
354 strcpy(u
->sun_path
, name
);
359 * Prepare, create, and bind a socket for local communication.
361 * \param name The socket pathname.
362 * \param unix_addr Pointer to the \p AF_UNIX socket structure.
363 * \param mode The desired mode of the socket.
365 * This functions creates a local socket for sequenced, reliable,
366 * two-way, connection-based byte streams.
368 * \return The file descriptor, on success, negative on errors.
374 int create_local_socket(const char *name
, struct sockaddr_un
*unix_addr
,
379 ret
= init_unix_addr(unix_addr
, name
);
382 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
386 if (bind(fd
, (struct sockaddr
*) unix_addr
, UNIX_PATH_MAX
) < 0)
389 if (chmod(name
, mode
) < 0)
398 ssize_t
send_cred_buffer(int sock
, char *buf
)
400 return send_buffer(sock
, buf
);
402 int recv_cred_buffer(int fd
, char *buf
, size_t size
)
404 return recv_buffer(fd
, buf
, size
) > 0? 1 : -E_RECVMSG
;
406 #else /* HAVE_UCRED */
408 * send NULL terminated buffer and Unix credentials of the current process
410 * \param sock the socket file descriptor
411 * \param buf the buffer to be sent
413 * \return On success, this call returns the number of characters sent. On
414 * error, \p -E_SENDMSG ist returned.
416 * \sa okir's Black Hats Manual
419 ssize_t
send_cred_buffer(int sock
, char *buf
)
421 char control
[sizeof(struct cmsghdr
) + 10];
423 struct cmsghdr
*cmsg
;
424 static struct iovec iov
;
430 iov
.iov_len
= strlen(buf
);
434 /* compose the message */
435 memset(&msg
, 0, sizeof(msg
));
438 msg
.msg_control
= control
;
439 msg
.msg_controllen
= sizeof(control
);
440 /* attach the ucred struct */
441 cmsg
= CMSG_FIRSTHDR(&msg
);
442 cmsg
->cmsg_level
= SOL_SOCKET
;
443 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
444 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
445 *(struct ucred
*)CMSG_DATA(cmsg
) = c
;
446 msg
.msg_controllen
= cmsg
->cmsg_len
;
447 ret
= sendmsg(sock
, &msg
, 0);
453 static void dispose_fds(int *fds
, unsigned num
)
457 for (i
= 0; i
< num
; i
++)
462 * receive a buffer and the Unix credentials of the sending process
464 * \param fd the socket file descriptor
465 * \param buf the buffer to store the message
466 * \param size the size of \a buffer
468 * \return negative on errors, the user id on success.
470 * \sa okir's Black Hats Manual
473 int recv_cred_buffer(int fd
, char *buf
, size_t size
)
477 struct cmsghdr
*cmsg
;
483 setsockopt(fd
, SOL_SOCKET
, SO_PASSCRED
, &yes
, sizeof(int));
484 memset(&msg
, 0, sizeof(msg
));
485 memset(buf
, 0, size
);
490 msg
.msg_control
= control
;
491 msg
.msg_controllen
= sizeof(control
);
492 if (recvmsg(fd
, &msg
, 0) < 0)
494 result
= -E_SCM_CREDENTIALS
;
495 cmsg
= CMSG_FIRSTHDR(&msg
);
497 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
498 == SCM_CREDENTIALS
) {
499 memcpy(&cred
, CMSG_DATA(cmsg
), sizeof(struct ucred
));
502 if (cmsg
->cmsg_level
== SOL_SOCKET
503 && cmsg
->cmsg_type
== SCM_RIGHTS
) {
504 dispose_fds((int *) CMSG_DATA(cmsg
),
505 (cmsg
->cmsg_len
- CMSG_LEN(0))
508 cmsg
= CMSG_NXTHDR(&msg
, cmsg
);
512 #endif /* HAVE_UCRED */
514 /** how many pending connections queue will hold */
518 * create a socket, bind it and listen
520 * \param port the tcp port to listen on
522 * \return The file descriptor of the created socket, negative
525 * \sa get_stream_socket()
530 int init_tcp_socket(int port
)
532 struct sockaddr_in my_addr
;
533 int fd
, ret
= get_stream_socket(AF_INET
);
538 ret
= setserversockopts(fd
);
541 init_sockaddr(&my_addr
, port
, NULL
);
543 if (bind(fd
, (struct sockaddr
*)&my_addr
,
544 sizeof(struct sockaddr
)) == -1) {
545 PARA_CRIT_LOG("bind error: %s\n", strerror(errno
));
549 if (listen(fd
, BACKLOG
) == -1)
551 PARA_INFO_LOG("listening on port %d, fd %d\n", port
, fd
);
559 * receive a buffer and check for a pattern
561 * \param fd the file descriptor to receive from
562 * \param pattern the expected pattern
563 * \param bufsize the size of the internal buffer
565 * \return Positive if \a pattern was received, negative otherwise.
567 * This function creates a buffer of size \a bufsize and tries
568 * to receive at most \a bufsize bytes from file descriptor \a fd.
569 * If at least \p strlen(\a pattern) bytes were received, the beginning of
570 * the received buffer is compared with \a pattern, ignoring case.
575 int recv_pattern(int fd
, const char *pattern
, size_t bufsize
)
577 size_t len
= strlen(pattern
);
578 char *buf
= para_malloc(bufsize
+ 1);
579 int ret
= -E_RECV_PATTERN
, n
= recv_buffer(fd
, buf
, bufsize
);
583 if (strncasecmp(buf
, pattern
, len
))
588 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n
, pattern
);
590 PARA_NOTICE_LOG("recvd: %s\n", buf
);