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