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 /** holds information about one encrypted connection */
17 /** function used to decrypt received data */
19 /** function used to encrypt data to be sent */
21 /** context-dependent data, passed to \a recv() and \a send() */
24 /** array holding per fd crypt data per */
25 static struct crypt_data
*crypt_data_array
;
26 /** current size of the crypt data array */
27 static unsigned cda_size
= 0;
31 * activate encryption for one file descriptor
33 * \param fd the file descriptor
34 * \param recv_f the function used for decrypting received data
35 * \param send_f the function used for encrypting before sending
36 * \param private_data user data supplied by the caller
38 void enable_crypt(int fd
, crypt_function
*recv_f
, crypt_function
*send_f
,
41 if (fd
+ 1 > cda_size
) {
42 crypt_data_array
= para_realloc(crypt_data_array
,
43 (fd
+ 1) * sizeof(struct crypt_data
));
44 memset(crypt_data_array
+ cda_size
, 0,
45 (fd
+ 1 - cda_size
) * sizeof(struct crypt_data
));
48 crypt_data_array
[fd
].recv
= recv_f
;
49 crypt_data_array
[fd
].send
= send_f
;
50 crypt_data_array
[fd
].private_data
= private_data
;
51 PARA_INFO_LOG("rc4 encryption activated for fd %d\n", fd
);
55 * deactivate encryption for a given fd
57 * \param fd the file descriptor
59 * This must be called if and only if \p fd was activated via enable_crypt().
61 void disable_crypt(int fd
)
63 if (cda_size
< fd
+ 1)
65 crypt_data_array
[fd
].recv
= NULL
;
66 crypt_data_array
[fd
].send
= NULL
;
67 crypt_data_array
[fd
].private_data
= NULL
;
72 * initialize a struct sockaddr_in
74 * \param addr A pointer to the struct to be initialized
75 * \param port The port number to use
76 * \param he The address to use
78 * If \a he is null (server mode), \a addr->sin_addr is initialized with \p
79 * INADDR_ANY. Otherwise, the address given by \a he is copied to addr.
81 void init_sockaddr(struct sockaddr_in
*addr
, int port
, const struct hostent
*he
)
84 addr
->sin_family
= AF_INET
;
85 /* short, network byte order */
86 addr
->sin_port
= htons(port
);
88 addr
->sin_addr
= *((struct in_addr
*)he
->h_addr
);
90 addr
->sin_addr
.s_addr
= INADDR_ANY
;
91 /* zero the rest of the struct */
92 memset(&addr
->sin_zero
, '\0', 8);
96 * send out a buffer, resend on short writes
98 * \param fd the file descriptor
99 * \param buf The buffer to be sent
100 * \param len The length of \a buf
102 * Due to circumstances beyond your control, the kernel might not send all the
103 * data out in one chunk, and now, my friend, it's up to us to get the data out
104 * there (Beej's Guide to Network Programming).
106 * \return This function returns 1 on success and \a -E_SEND on errors. The
107 * number of bytes actually sent is stored upon successful return in \a len.
109 static int sendall(int fd
, const char *buf
, size_t *len
)
111 size_t total
= 0, bytesleft
= *len
; /* how many we have left to send */
114 while (total
< *len
) {
115 n
= send(fd
, buf
+ total
, bytesleft
, 0);
121 PARA_DEBUG_LOG("short write (%zd byte(s) left)",
124 *len
= total
; /* return number actually sent here */
125 return n
== -1? -E_SEND
: 1; /* return 1 on success */
129 * encrypt and send buffer
131 * \param fd: the file descriptor
132 * \param buf the buffer to be encrypted and sent
133 * \param len the length of \a buf
135 * Check if encrytpion is available. If yes, encrypt the given buffer. Send out
136 * the buffer, encrypted or not, and try to resend the remaing part in case of
139 * \return Positive on success, \p -E_SEND on errors.
141 int send_bin_buffer(int fd
, const char *buf
, size_t len
)
144 crypt_function
*cf
= NULL
;
147 PARA_CRIT_LOG("%s", "len == 0\n");
148 if (fd
+ 1 <= cda_size
)
149 cf
= crypt_data_array
[fd
].send
;
151 void *private = crypt_data_array
[fd
].private_data
;
152 unsigned char *outbuf
= para_malloc(len
);
153 (*cf
)(len
, (unsigned char *)buf
, outbuf
, private);
154 ret
= sendall(fd
, (char *)outbuf
, &len
);
157 ret
= sendall(fd
, buf
, &len
);
162 * encrypt and send null terminated buffer.
164 * \param fd the file descriptor
165 * \param buf the null-terminated buffer to be send
167 * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
169 * \return Positive on success, \p -E_SEND on errors.
171 int send_buffer(int fd
, const char *buf
)
173 return send_bin_buffer(fd
, buf
, strlen(buf
));
178 * send and encrypt a buffer given by a format string
180 * \param fd the file descriptor
181 * \param fmt a format string
183 * \return Positive on success, \p -E_SEND on errors.
185 __printf_2_3
int send_va_buffer(int fd
, const char *fmt
, ...)
190 PARA_VSPRINTF(fmt
, msg
);
191 ret
= send_buffer(fd
, msg
);
197 * receive and decrypt.
199 * \param fd the file descriptor
200 * \param buf the buffer to write the decrypted data to
201 * \param size the size of \a buf
203 * Receive at most \a size bytes from filedescriptor fd. If encryption is
204 * available, decrypt the received buffer.
206 * \return The number of bytes received on success. On receive errors, -E_RECV
207 * is returned. On crypt errors, the corresponding crypt error number is
212 __must_check
int recv_bin_buffer(int fd
, char *buf
, size_t size
)
215 crypt_function
*cf
= NULL
;
217 if (fd
+ 1 <= cda_size
)
218 cf
= crypt_data_array
[fd
].recv
;
220 unsigned char *tmp
= para_malloc(size
);
221 void *private = crypt_data_array
[fd
].private_data
;
222 n
= recv(fd
, tmp
, size
, 0);
225 unsigned char *b
= (unsigned char *)buf
;
226 (*cf
)(numbytes
, tmp
, b
, private);
230 n
= recv(fd
, buf
, size
, 0);
237 * receive, decrypt and write terminating NULL byte
239 * \param fd the file descriptor
240 * \param buf the buffer to write the decrypted data to
241 * \param size the size of \a buf
243 * Read and decrypt at most \a size - 1 bytes from file descriptor \a fd and
244 * write a NULL byte at the end of the received data.
246 * \return: The return value of the underlying call to \a recv_bin_buffer().
248 * \sa recv_bin_buffer()
250 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 * Create an IPv4 socket for sequenced, reliable, two-way, connection-based
289 * \return The socket fd on success, -E_SOCKET on errors.
297 if ((socket_fd
= socket(AF_INET
, SOCK_STREAM
, 0)) == -1)
303 * a wrapper around connect(2)
305 * \param fd the file descriptor
306 * \param their_addr the address to connect
308 * \return \p -E_CONNECT on errors, 1 on success
312 int para_connect(int fd
, struct sockaddr_in
*their_addr
)
316 if ((ret
= connect(fd
, (struct sockaddr
*)their_addr
,
317 sizeof(struct sockaddr
))) == -1)
323 * paraslash's wrapper around the accept system call
325 * \param fd the listening socket
326 * \param addr structure which is filled in with the address of the peer socket
327 * \param size should contain the size of the structure pointed to by \a addr
329 * Accept incoming connections on \a addr. Retry if interrupted.
331 * \return The new file descriptor on success, \a -E_ACCEPT on errors.
335 int para_accept(int fd
, void *addr
, socklen_t size
)
340 new_fd
= accept(fd
, (struct sockaddr
*) addr
, &size
);
341 while (new_fd
< 0 && errno
== EINTR
);
342 return new_fd
< 0? -E_ACCEPT
: new_fd
;
345 static int setserversockopts(int socket_fd
)
349 if (setsockopt(socket_fd
, SOL_SOCKET
, SO_REUSEADDR
, &yes
,
351 return -E_SETSOCKOPT
;
356 * prepare a structure for \p AF_UNIX socket addresses
358 * \param u pointer to the struct to be prepared
359 * \param name the socket pathname
361 * This just copies \a name to the sun_path component of \a u.
363 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
364 * than \p UNIX_PATH_MAX.
366 int init_unix_addr(struct sockaddr_un
*u
, const char *name
)
368 if (strlen(name
) >= UNIX_PATH_MAX
)
369 return -E_NAME_TOO_LONG
;
370 memset(u
->sun_path
, 0, UNIX_PATH_MAX
);
371 u
->sun_family
= PF_UNIX
;
372 strcpy(u
->sun_path
, name
);
377 * Prepare, create, and bind a socket for local communication.
379 * \param name The socket pathname.
380 * \param unix_addr Pointer to the \p AF_UNIX socket structure.
381 * \param mode The desired mode of the socket.
383 * This functions creates a local socket for sequenced, reliable,
384 * two-way, connection-based byte streams.
386 * \return The file descriptor, on success, negative on errors.
392 int create_local_socket(const char *name
, struct sockaddr_un
*unix_addr
,
397 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
401 ret
= init_unix_addr(unix_addr
, name
);
404 if (bind(fd
, (struct sockaddr
*) unix_addr
, UNIX_PATH_MAX
) < 0)
406 if (chmod(name
, mode
) < 0)
412 ssize_t
send_cred_buffer(int sock
, char *buf
)
414 return send_buffer(sock
, buf
);
416 int recv_cred_buffer(int fd
, char *buf
, size_t size
)
418 return recv_buffer(fd
, buf
, size
) > 0? 1 : -E_RECVMSG
;
420 #else /* HAVE_UCRED */
422 * send NULL terminated buffer and Unix credentials of the current process
424 * \param sock the socket file descriptor
425 * \param buf the buffer to be sent
427 * \return On success, this call returns the number of characters sent. On
428 * error, \p -E_SENDMSG ist returned.
430 * \sa okir's Black Hats Manual
433 ssize_t
send_cred_buffer(int sock
, char *buf
)
435 char control
[sizeof(struct cmsghdr
) + 10];
437 struct cmsghdr
*cmsg
;
438 static struct iovec iov
;
444 iov
.iov_len
= strlen(buf
);
448 /* compose the message */
449 memset(&msg
, 0, sizeof(msg
));
452 msg
.msg_control
= control
;
453 msg
.msg_controllen
= sizeof(control
);
454 /* attach the ucred struct */
455 cmsg
= CMSG_FIRSTHDR(&msg
);
456 cmsg
->cmsg_level
= SOL_SOCKET
;
457 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
458 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
459 *(struct ucred
*)CMSG_DATA(cmsg
) = c
;
460 msg
.msg_controllen
= cmsg
->cmsg_len
;
461 ret
= sendmsg(sock
, &msg
, 0);
467 static void dispose_fds(int *fds
, unsigned num
)
471 for (i
= 0; i
< num
; i
++)
476 * receive a buffer and the Unix credentials of the sending process
478 * \param fd the socket file descriptor
479 * \param buf the buffer to store the message
480 * \param size the size of \a buffer
482 * \return negative on errors, the user id on success.
484 * \sa okir's Black Hats Manual
487 int recv_cred_buffer(int fd
, char *buf
, size_t size
)
491 struct cmsghdr
*cmsg
;
497 setsockopt(fd
, SOL_SOCKET
, SO_PASSCRED
, &yes
, sizeof(int));
498 memset(&msg
, 0, sizeof(msg
));
499 memset(buf
, 0, size
);
504 msg
.msg_control
= control
;
505 msg
.msg_controllen
= sizeof(control
);
506 if (recvmsg(fd
, &msg
, 0) < 0)
508 result
= -E_SCM_CREDENTIALS
;
509 cmsg
= CMSG_FIRSTHDR(&msg
);
511 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
512 == SCM_CREDENTIALS
) {
513 memcpy(&cred
, CMSG_DATA(cmsg
), sizeof(struct ucred
));
516 if (cmsg
->cmsg_level
== SOL_SOCKET
517 && cmsg
->cmsg_type
== SCM_RIGHTS
) {
518 dispose_fds((int *) CMSG_DATA(cmsg
),
519 (cmsg
->cmsg_len
- CMSG_LEN(0))
522 cmsg
= CMSG_NXTHDR(&msg
, cmsg
);
526 #endif /* HAVE_UCRED */
528 /** how many pending connections queue will hold */
532 * create a socket, bind it and listen
534 * \param port the tcp port to listen on
536 * \return The file descriptor of the created socket, negative
544 int init_tcp_socket(int port
)
546 struct sockaddr_in my_addr
;
547 int fd
, ret
= get_socket();
552 ret
= setserversockopts(fd
);
555 init_sockaddr(&my_addr
, port
, NULL
);
557 if (bind(fd
, (struct sockaddr
*)&my_addr
,
558 sizeof(struct sockaddr
)) == -1) {
559 PARA_CRIT_LOG("bind error: %s\n", strerror(errno
));
563 if (listen(fd
, BACKLOG
) == -1)
565 PARA_INFO_LOG("listening on port %d, fd %d\n", port
, fd
);
573 * receive a buffer and check for a pattern
575 * \param fd the file descriptor to receive from
576 * \param pattern the expected pattern
577 * \param bufsize the size of the internal buffer
579 * \return Positive if \a pattern was received, negative otherwise.
581 * This function creates a buffer of size \a bufsize and tries
582 * to receive at most \a bufsize bytes from file descriptor \a fd.
583 * If at least \p strlen(\a pattern) bytes were received, the beginning of
584 * the received buffer is compared with \a pattern, ignoring case.
589 int recv_pattern(int fd
, const char *pattern
, size_t bufsize
)
591 size_t len
= strlen(pattern
);
592 char *buf
= para_malloc(bufsize
+ 1);
593 int ret
= -E_RECV_PATTERN
, n
= recv_buffer(fd
, buf
, bufsize
);
597 if (strncasecmp(buf
, pattern
, len
))
602 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n
, pattern
);
604 PARA_NOTICE_LOG("recvd: %s\n", buf
);