Fix link to gitweb on the main page.
[paraslash.git] / net.c
1 /*
2  * Copyright (C) 2005-2007 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file net.c Networking-related helper functions. */
8
9 #include <netdb.h> /* hostent */
10
11 #include "para.h"
12 #include "error.h"
13 #include "net.h"
14 #include "string.h"
15
16
17 /** Information about one encrypted connection. */
18 struct crypt_data {
19         /** Function used to decrypt received data. */
20         crypt_function *recv;
21         /** Function used to encrypt data to be sent. */
22         crypt_function *send;
23         /**
24          * Context-dependent data (crypt keys), passed verbatim to the above
25          * crypt functions.
26          */
27         void *private_data;
28 };
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;
33
34 /**
35  * Activate encryption for one file descriptor.
36  *
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.
41  */
42 void enable_crypt(int fd, crypt_function *recv_f, crypt_function *send_f,
43         void *private_data)
44 {
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));
50                 cda_size = fd + 1;
51         }
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);
56 }
57
58 /**
59  * Deactivate encryption for a given fd.
60  *
61  * \param fd The file descriptor.
62  *
63  * This must be called if and only if \p fd was activated via enable_crypt().
64  */
65 void disable_crypt(int fd)
66 {
67         if (cda_size < fd + 1)
68                 return;
69         crypt_data_array[fd].recv = NULL;
70         crypt_data_array[fd].send = NULL;
71         crypt_data_array[fd].private_data = NULL;
72 }
73
74
75 /**
76  * Initialize a struct sockaddr_in.
77  *
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.
81  *
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.
84  */
85 static void init_sockaddr(struct sockaddr_in *addr, int port, const struct hostent *he)
86 {
87         /* host byte order */
88         addr->sin_family = AF_INET;
89         /* short, network byte order */
90         addr->sin_port = htons(port);
91         if (he)
92                 addr->sin_addr = *((struct in_addr *)he->h_addr);
93         else
94                 addr->sin_addr.s_addr = INADDR_ANY;
95         /* zero the rest of the struct */
96         memset(&addr->sin_zero, '\0', 8);
97 }
98
99 /*
100  * Send out a buffer, resend on short writes.
101  *
102  * \param fd The file descriptor.
103  * \param buf The buffer to be sent.
104  * \param len The length of \a buf.
105  *
106  * \return Standard. In any case, the number of bytes actually sent is stored
107  * in \a len.
108  */
109 static int sendall(int fd, const char *buf, size_t *len)
110 {
111         size_t total = *len;
112
113         assert(total);
114         *len = 0;
115         while (*len < total) {
116                 int ret = send(fd, buf + *len, total - *len, 0);
117                 if (ret == -1)
118                         return -ERRNO_TO_PARA_ERROR(errno);
119                 *len += ret;
120         }
121         return 1;
122 }
123
124 /**
125  * Encrypt and send a binary buffer.
126  *
127  * \param fd The file descriptor.
128  * \param buf The buffer to be encrypted and sent.
129  * \param len The length of \a buf.
130  *
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
133  * of short writes.
134  *
135  * \return Standard.
136  */
137 int send_bin_buffer(int fd, const char *buf, size_t len)
138 {
139         int ret;
140         crypt_function *cf = NULL;
141
142         if (!len)
143                 PARA_CRIT_LOG("%s", "len == 0\n");
144         if (fd + 1 <= cda_size)
145                 cf = crypt_data_array[fd].send;
146         if (cf) {
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);
152                 free(outbuf);
153         } else
154                 ret = sendall(fd, buf, &len);
155         return ret;
156 }
157
158 /**
159  * Encrypt and send null terminated buffer.
160  *
161  * \param fd The file descriptor.
162  * \param buf The null-terminated buffer to be send.
163  *
164  * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
165  *
166  * \return Standard.
167  */
168 int send_buffer(int fd, const char *buf)
169 {
170         return send_bin_buffer(fd, buf, strlen(buf));
171 }
172
173
174 /**
175  * Send and encrypt a buffer given by a format string.
176  *
177  * \param fd The file descriptor.
178  * \param fmt A format string.
179  *
180  * \return Standard.
181  */
182 __printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
183 {
184         char *msg;
185         int ret;
186
187         PARA_VSPRINTF(fmt, msg);
188         ret = send_buffer(fd, msg);
189         free(msg);
190         return ret;
191 }
192
193 /**
194  * Receive and decrypt.
195  *
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.
199  *
200  * Receive at most \a size bytes from file descriptor \a fd. If encryption is
201  * available, decrypt the received buffer.
202  *
203  * \return The number of bytes received on success, negative on errors.
204  *
205  * \sa recv(2)
206  */
207 __must_check int recv_bin_buffer(int fd, char *buf, size_t size)
208 {
209         ssize_t n;
210         crypt_function *cf = NULL;
211
212         if (fd + 1 <= cda_size)
213                 cf = crypt_data_array[fd].recv;
214         if (cf) {
215                 unsigned char *tmp = para_malloc(size);
216                 void *private = crypt_data_array[fd].private_data;
217                 n = recv(fd, tmp, size, 0);
218                 if (n > 0) {
219                         size_t numbytes = n;
220                         unsigned char *b = (unsigned char *)buf;
221                         (*cf)(numbytes, tmp, b, private);
222                 }
223                 free(tmp);
224         } else
225                 n = recv(fd, buf, size, 0);
226         if (n == -1)
227                 return -ERRNO_TO_PARA_ERROR(errno);
228         return n;
229 }
230
231 /**
232  * Receive, decrypt and write terminating NULL byte.
233  *
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.
237  *
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.
240  *
241  * \return The return value of the underlying call to \a recv_bin_buffer().
242  *
243  * \sa recv_bin_buffer()
244  */
245 int recv_buffer(int fd, char *buf, size_t size)
246 {
247         int n;
248
249         assert(size);
250         n = recv_bin_buffer(fd, buf, size - 1);
251         if (n >= 0)
252                 buf[n] = '\0';
253         else
254                 *buf = '\0';
255         return n;
256 }
257
258 /**
259  * Establish a tcp connection.
260  *
261  * \param host Hostname or IPv4 address.
262  * \param port The tcp port.
263  *
264  * \return Negative on errors, a valid file descriptor on success.
265  */
266 int tcp_connect(char *host, int port)
267 {
268         struct sockaddr_in addr;
269         struct hostent *he;
270         int ret, fd;
271
272         PARA_INFO_LOG("getting host info of %s\n", host);
273         /* FIXME: gethostbyname() is obsolete */
274         he = gethostbyname(host);
275         if (!he)
276                 return -ERRNO_TO_PARA_ERROR(h_errno);
277         init_sockaddr(&addr, port, he);
278         ret = get_stream_socket(AF_INET);
279         if (ret < 0)
280                 return ret;
281         fd = ret;
282         ret = PARA_CONNECT(fd, &addr);
283         if (ret >= 0)
284                 return fd;
285         close(fd);
286         return ret;
287 }
288
289 /**
290  * A wrapper around socket(2).
291  *
292  * \param domain The communication domain that selects the protocol family.
293  *
294  * Create an IPv4 socket for sequenced, reliable, two-way, connection-based
295  * byte streams.
296  *
297  * \return The socket fd on success, negative on errors.
298  *
299  * \sa socket(2).
300  */
301 int get_stream_socket(int domain)
302 {
303         int fd = socket(domain, SOCK_STREAM, 0);
304
305         if (fd < 0)
306                 return -ERRNO_TO_PARA_ERROR(errno);
307         return fd;
308 }
309
310 /**
311  * Wrapper around the accept system call.
312  *
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.
316  *
317  * Accept incoming connections on \a addr. Retry if interrupted.
318  *
319  * \return The new file descriptor on success, negative on errors.
320  *
321  * \sa accept(2).
322  */
323 int para_accept(int fd, void *addr, socklen_t size)
324 {
325         int new_fd;
326
327         do
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;
331 }
332
333 /**
334  * prepare a structure for \p AF_UNIX socket addresses
335  *
336  * \param u pointer to the struct to be prepared
337  * \param name the socket pathname
338  *
339  * This just copies \a name to the sun_path component of \a u.
340  *
341  * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
342  * than \p UNIX_PATH_MAX.
343  */
344 int init_unix_addr(struct sockaddr_un *u, const char *name)
345 {
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);
351         return 1;
352 }
353
354 /**
355  * Prepare, create, and bind a socket for local communication.
356  *
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.
360  *
361  * This functions creates a local socket for sequenced, reliable,
362  * two-way, connection-based byte streams.
363  *
364  * \return The file descriptor, on success, negative on errors.
365  *
366  * \sa socket(2)
367  * \sa bind(2)
368  * \sa chmod(2)
369  */
370 int create_local_socket(const char *name, struct sockaddr_un *unix_addr,
371                 mode_t mode)
372 {
373         int fd, ret;
374
375         ret = init_unix_addr(unix_addr, name);
376         if (ret < 0)
377                 return ret;
378         ret = socket(PF_UNIX, SOCK_STREAM, 0);
379         if (ret < 0)
380                 return -ERRNO_TO_PARA_ERROR(errno);
381         fd = ret;
382         ret = bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX);
383         if (ret < 0) {
384                 ret = -ERRNO_TO_PARA_ERROR(errno);
385                 goto err;
386         }
387         ret = -E_CHMOD;
388         if (chmod(name, mode) < 0)
389                 goto err;
390         return fd;
391 err:
392         close(fd);
393         return ret;
394 }
395
396 #ifndef HAVE_UCRED
397 ssize_t send_cred_buffer(int sock, char *buf)
398 {
399         return send_buffer(sock, buf);
400 }
401 int recv_cred_buffer(int fd, char *buf, size_t size)
402 {
403         return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
404 }
405 #else /* HAVE_UCRED */
406 /**
407  * send NULL terminated buffer and Unix credentials of the current process
408  *
409  * \param sock the socket file descriptor
410  * \param buf the buffer to be sent
411  *
412  * \return On success, this call returns the number of characters sent.  On
413  * error, \p -E_SENDMSG is returned.
414  *
415  * \sa  okir's Black Hats Manual
416  * \sa sendmsg(2)
417  */
418 ssize_t send_cred_buffer(int sock, char *buf)
419 {
420         char control[sizeof(struct cmsghdr) + 10];
421         struct msghdr msg;
422         struct cmsghdr *cmsg;
423         static struct iovec iov;
424         struct ucred c;
425         int ret;
426
427         /* Response data */
428         iov.iov_base = buf;
429         iov.iov_len  = strlen(buf);
430         c.pid = getpid();
431         c.uid = getuid();
432         c.gid = getgid();
433         /* compose the message */
434         memset(&msg, 0, sizeof(msg));
435         msg.msg_iov = &iov;
436         msg.msg_iovlen = 1;
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);
447         if (ret  < 0)
448                 ret = -E_SENDMSG;
449         return ret;
450 }
451
452 static void dispose_fds(int *fds, unsigned num)
453 {
454         int i;
455
456         for (i = 0; i < num; i++)
457                 close(fds[i]);
458 }
459
460 /**
461  * receive a buffer and the Unix credentials of the sending process
462  *
463  * \param fd the socket file descriptor
464  * \param buf the buffer to store the message
465  * \param size the size of \a buffer
466  *
467  * \return negative on errors, the user id on success.
468  *
469  * \sa okir's Black Hats Manual
470  * \sa recvmsg(2)
471  */
472 int recv_cred_buffer(int fd, char *buf, size_t size)
473 {
474         char control[255];
475         struct msghdr msg;
476         struct cmsghdr *cmsg;
477         struct iovec iov;
478         int result = 0;
479         int yes = 1;
480         struct ucred cred;
481
482         setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
483         memset(&msg, 0, sizeof(msg));
484         memset(buf, 0, size);
485         iov.iov_base = buf;
486         iov.iov_len = size;
487         msg.msg_iov = &iov;
488         msg.msg_iovlen = 1;
489         msg.msg_control = control;
490         msg.msg_controllen = sizeof(control);
491         if (recvmsg(fd, &msg, 0) < 0)
492                 return -E_RECVMSG;
493         result = -E_SCM_CREDENTIALS;
494         cmsg = CMSG_FIRSTHDR(&msg);
495         while (cmsg) {
496                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
497                                 == SCM_CREDENTIALS) {
498                         memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
499                         result = cred.uid;
500                 } else
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))
505                                         / sizeof(int));
506                         }
507                 cmsg = CMSG_NXTHDR(&msg, cmsg);
508         }
509         return result;
510 }
511 #endif /* HAVE_UCRED */
512
513 /** how many pending connections queue will hold */
514 #define BACKLOG 10
515
516 /**
517  * Create a tcp socket, bind it and listen on the given port.
518  *
519  * \param port The tcp port to listen on.
520  *
521  * \return The file descriptor of the created socket, negative on errors.
522  *
523  * \sa get_stream_socket()
524  * \sa setsockopt(2)
525  * \sa bind(2)
526  * \sa listen(2)
527  */
528 int tcp_listen(int port)
529 {
530         struct sockaddr_in my_addr;
531         int fd, ret = get_stream_socket(AF_INET);
532
533         if (ret < 0)
534                 return ret;
535         fd = ret;
536         ret = 1;
537         ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &ret, sizeof(int));
538         if (ret < 0) {
539                 ret = -ERRNO_TO_PARA_ERROR(errno);
540                 goto err;
541         }
542         init_sockaddr(&my_addr, port, NULL);
543         ret = bind(fd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
544         if (ret < 0) {
545                 ret = -ERRNO_TO_PARA_ERROR(errno);
546                 goto err;
547         }
548         ret = listen(fd, BACKLOG);
549         if (ret < 0) {
550                 ret = -ERRNO_TO_PARA_ERROR(errno);
551                 goto err;
552         }
553         PARA_INFO_LOG("listening on port %d, fd %d\n", port, fd);
554         return fd;
555 err:
556         close(fd);
557         return ret;
558 }
559
560 /**
561  * receive a buffer and check for a pattern
562  *
563  * \param fd the file descriptor to receive from
564  * \param pattern the expected pattern
565  * \param bufsize the size of the internal buffer
566  *
567  * \return Positive if \a pattern was received, negative otherwise.
568  *
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.
573  *
574  * \sa recv_buffer()
575  * \sa strncasecmp(3)
576  */
577 int recv_pattern(int fd, const char *pattern, size_t bufsize)
578 {
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);
582
583         if (n < len)
584                 goto out;
585         if (strncasecmp(buf, pattern, len))
586                 goto out;
587         ret = 1;
588 out:
589         if (ret < 0) {
590                 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n, pattern);
591                 if (n > 0)
592                         PARA_NOTICE_LOG("recvd: %s\n", buf);
593         }
594         free(buf);
595         return ret;
596 }