move user handling code into seperate functions
[paraslash.git] / net.c
1 /*
2  * Copyright (C) 2005-2006 Andre Noll <maan@systemlinux.org>
3  *
4  *     This program is free software; you can redistribute it and/or modify
5  *     it under the terms of the GNU General Public License as published by
6  *     the Free Software Foundation; either version 2 of the License, or
7  *     (at your option) any later version.
8  *
9  *     This program is distributed in the hope that it will be useful,
10  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *     GNU General Public License for more details.
13  *
14  *     You should have received a copy of the GNU General Public License
15  *     along with this program; if not, write to the Free Software
16  *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
17  */
18
19 /** \file net.c networking-related helper functions */
20
21 #include "para.h"
22 #include "net.h"
23 #include "string.h"
24 #include "error.h"
25
26
27 /** \cond holds information about one encrypted connection */
28 struct crypt_data {
29         crypt_function *recv;
30         crypt_function *send;
31         void *private_data;
32 };
33 static unsigned cda_size = 0;
34 static struct crypt_data *crypt_data_array;
35 /** \endcond */
36
37
38 /**
39  * activate encryption for one file descriptor
40  *
41  * \param fd the file descriptor
42  * \param recv_f the function used for decrypting received data
43  * \param send_f the function used for encrypting before sending
44  * \param private_data user data supplied by the caller
45  */
46 void enable_crypt(int fd, crypt_function *recv_f, crypt_function *send_f,
47         void *private_data)
48 {
49         if (fd + 1 > cda_size) {
50                 crypt_data_array = para_realloc(crypt_data_array,
51                         (fd + 1) * sizeof(struct crypt_data));
52                 memset(crypt_data_array + cda_size, 0,
53                         (fd + 1 - cda_size) * sizeof(struct crypt_data));
54                 cda_size = fd + 1;
55         }
56         crypt_data_array[fd].recv = recv_f;
57         crypt_data_array[fd].send = send_f;
58         crypt_data_array[fd].private_data = private_data;
59         PARA_INFO_LOG("rc4 encryption activated for fd %d\n", fd);
60 }
61
62 /**
63  * deactivate encryption for a given fd
64  *
65  * \param fd the file descriptor
66  *
67  * This must be called if and only if \p fd was activated via enable_crypt().
68  */
69 void disable_crypt(int fd)
70 {
71         if (cda_size < fd + 1)
72                 return;
73         crypt_data_array[fd].recv = NULL;
74         crypt_data_array[fd].send = NULL;
75         crypt_data_array[fd].private_data = NULL;
76 }
77
78
79 /**
80  * initialize a struct sockaddr_in
81  * @param addr A pointer to the struct to be initialized
82  * @param port The port number to use
83  * @param he The address to use
84  *
85  * If \a he is null (server mode), \a addr->sin_addr is initialized with \p INADDR_ANY.
86  * Otherwise, the address given by \a he is copied to addr.
87  */
88 void init_sockaddr(struct sockaddr_in *addr, int port, const struct hostent *he)
89 {
90         /* host byte order */
91         addr->sin_family = AF_INET;
92         /* short, network byte order */
93         addr->sin_port = htons(port);
94         if (he)
95                 addr->sin_addr = *((struct in_addr *)he->h_addr);
96         else
97                 addr->sin_addr.s_addr = INADDR_ANY;
98         /* zero the rest of the struct */
99         memset(&addr->sin_zero, '\0', 8);
100 }
101
102 /*
103  * send out a buffer, resend on short writes
104  * @param fd the file descriptor
105  * @param buf The buffer to be sent
106  * @len The length of \a buf
107  *
108  * Due to circumstances beyond your control, the kernel might not send all the
109  * data out in one chunk, and now, my friend, it's up to us to get the data out
110  * there (Beej's Guide to Network Programming).
111  */
112 static int sendall(int fd, const char *buf, size_t *len)
113 {
114         int total = 0;        /* how many bytes we've sent */
115         int bytesleft = *len; /* how many we have left to send */
116         int n = -1;
117
118         while (total < *len) {
119                 n = send(fd, buf + total, bytesleft, 0);
120                 if (n == -1)
121                         break;
122                 total += n;
123                 bytesleft -= n;
124                 if (total < *len)
125                         PARA_DEBUG_LOG("short write (%zd byte(s) left)",
126                                 *len - total);
127         }
128         *len = total; /* return number actually sent here */
129         return n == -1? -E_SEND : 1; /* return 1 on success */
130 }
131
132 /**
133  * encrypt and send buffer
134  * @param fd:  the file descriptor
135  * @param buf the buffer to be encrypted and sent
136  * @param len the length of \a buf
137  *
138  * Check if encrytpion is available. If yes, encrypt the given buffer.  Send out
139  * the buffer, encrypted or not, and try to resend the remaing part in case of
140  * short writes.
141  *
142  * @return Positive on success, \p -E_SEND on errors.
143  */
144 int send_bin_buffer(int fd, const char *buf, size_t len)
145 {
146         int ret;
147         crypt_function *cf = NULL;
148
149         if (!len)
150                 PARA_CRIT_LOG("%s", "len == 0\n");
151         if (fd + 1 <= cda_size)
152                 cf = crypt_data_array[fd].send;
153         if (cf) {
154                 void *private = crypt_data_array[fd].private_data;
155                 unsigned char *outbuf = para_malloc(len);
156                 (*cf)(len, (unsigned char *)buf, outbuf, private);
157                 ret = sendall(fd, (char *)outbuf, &len);
158                 free(outbuf);
159         } else
160                 ret = sendall(fd, buf, &len);
161         return ret;
162 }
163
164 /**
165  * encrypt and send null terminated buffer.
166  * @param fd the file descriptor
167  * @param buf the null-terminated buffer to be send
168  *
169  * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
170  *
171  * @return Positive on success, \p -E_SEND on errors.
172  */
173 int send_buffer(int fd, const char *buf)
174 {
175         return send_bin_buffer(fd, buf, strlen(buf));
176 }
177
178
179 /**
180  * send and encrypt a buffer given by a format string
181  * @param fd the file descriptor
182  * @param fmt a format string
183  *
184  * @return Positive on success, \p -E_SEND on errors.
185  */
186 __printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
187 {
188         char *msg;
189         int ret;
190
191         PARA_VSPRINTF(fmt, msg);
192         ret = send_buffer(fd, msg);
193         free(msg);
194         return ret;
195 }
196
197 /**
198  * receive and decrypt.
199  *
200  * @param fd the file descriptor
201  * @param buf the buffer to write the decrypted data to
202  * @param size the size of @param buf
203  *
204  * Receive at most \a size bytes from filedescriptor fd. If encryption is
205  * available, decrypt the received buffer.
206  *
207  * @return the number of bytes received on success. On receive errors, -E_RECV
208  * is returned. On crypt errors, the corresponding crypt error number is
209  * returned.
210  * \sa recv(2)
211  */
212 __must_check int recv_bin_buffer(int fd, char *buf, ssize_t size)
213 {
214         int n;
215         crypt_function *cf = NULL;
216
217         if (fd + 1 <= cda_size)
218                 cf = crypt_data_array[fd].recv;
219         if (cf) {
220                 unsigned char *tmp = para_malloc(size);
221                 void *private = crypt_data_array[fd].private_data;
222                 n = recv(fd, tmp, size, 0);
223                 if (n > 0)
224                         (*cf)(n, tmp, (unsigned char *)buf, private);
225                 free(tmp);
226         } else
227                 n = recv(fd, buf, size, 0);
228         if (n == -1)
229                 n = -E_RECV;
230         return n;
231 }
232
233 /**
234  * receive, decrypt and write terminating NULL byte
235  *
236  * @param fd the file descriptor
237  * @param buf the buffer to write the decrypted data to
238  * @param size the size of \a buf
239  *
240  * Read and decrypt at most size - 1 bytes from file descriptor \a fd and write
241  * a NULL byte at the end of the received data.
242  *
243 */
244 int recv_buffer(int fd, char *buf, ssize_t size)
245 {
246         int n;
247
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  * Create an IPv4 socket for sequenced, reliable, two-way, connection-based
279  * byte streams.
280  *
281  * @return The socket fd on success, -E_SOCKET on errors.
282  * \sa socket(2)
283  */
284 int get_socket(void)
285 {
286         int socket_fd;
287
288         if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
289                 return -E_SOCKET;
290         return socket_fd;
291 }
292
293 /**
294  * a wrapper around connect(2)
295  *
296  * @param fd the file descriptor
297  * @param their_addr the address to connect
298  *
299  * @return \p -E_CONNECT on errors, 1 on success
300  * \sa connect(2)
301  */
302 int para_connect(int fd, struct sockaddr_in *their_addr)
303 {
304         int ret;
305
306         if ((ret = connect(fd, (struct sockaddr *)their_addr,
307                         sizeof(struct sockaddr))) == -1)
308                 return -E_CONNECT;
309         return 1;
310 }
311
312 /**
313  * paraslash's wrapper around the accept system call
314  *
315  * \param fd the listening socket
316  * \param addr structure which is filled in with the address of the peer socket
317  * \param size should contain the size of the structure pointed to by \a addr
318  *
319  * \sa accept(2).
320  */
321 int para_accept(int fd, void *addr, socklen_t size)
322 {
323         int new_fd;
324
325         do 
326                 new_fd = accept(fd, (struct sockaddr *) addr, &size);
327         while (new_fd < 0 && errno == EINTR);
328         return new_fd < 0? -E_ACCEPT : new_fd;
329 }
330
331 static int setserversockopts(int socket_fd)
332 {
333         int yes = 1;
334
335         if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes,
336                         sizeof(int)) == -1)
337                 return -E_SETSOCKOPT;
338         return 1;
339 }
340
341 /**
342  * prepare a structure for \p AF_UNIX socket addresses
343  *
344  * \param u pointer to the struct to be prepared
345  * \param name the socket pathname
346  *
347  * This just copies \a name to the sun_path component of \a u.
348  *
349  * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
350  * than \p UNIX_PATH_MAX.
351  */
352 int init_unix_addr(struct sockaddr_un *u, const char *name)
353 {
354         if (strlen(name) >= UNIX_PATH_MAX)
355                 return -E_NAME_TOO_LONG;
356         memset(u->sun_path, 0, UNIX_PATH_MAX);
357         u->sun_family = PF_UNIX;
358         strcpy(u->sun_path, name);
359         return 1;
360 }
361
362 /**
363  * prepare, create, and bind and socket for local communication
364  *
365  * \param name the socket pathname
366  * \param unix_addr pointer to the \p AF_UNIX socket structure
367  * \param mode the desired mode of the socket
368  *
369  * This functions creates a local socket for sequenced, reliable,
370  * two-way, connection-based byte streams.
371  * \sa socket(2)
372  * \sa bind(2)
373  * \sa chmod(2)
374  */
375 int create_pf_socket(const char *name, struct sockaddr_un *unix_addr, int mode)
376 {
377         int fd, ret;
378
379         fd = socket(PF_UNIX, SOCK_STREAM, 0);
380         if (fd < 0)
381                 return -E_SOCKET;
382 //      unlink(name);
383         ret = init_unix_addr(unix_addr, name);
384         if (ret < 0)
385                 return ret;
386         if (bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX) < 0)
387                 return -E_BIND;
388         if (chmod(name, mode) < 0)
389                 return -E_CHMOD;
390         return fd;
391 }
392
393 #ifndef HAVE_UCRED
394 ssize_t send_cred_buffer(int sock, char *buf)
395 {
396         return send_buffer(sock, buf);
397 }
398 int recv_cred_buffer(int fd, char *buf, size_t size)
399 {
400         return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
401 }
402 #else /* HAVE_UCRED */
403 /**
404  * send NULL terminated buffer and Unix credentials of the current process
405  *
406  * \param sock the socket file descriptor
407  * \param buf the buffer to be sent
408  *
409  * \return On success, this call returns the number of characters sent.  On
410  * error, \p -E_SENDMSG ist returned.
411  * \sa  okir's Black Hats Manual
412  * \sa sendmsg(2)
413  */
414 ssize_t send_cred_buffer(int sock, char *buf)
415 {
416         char control[sizeof(struct cmsghdr) + 10];
417         struct msghdr msg;
418         struct cmsghdr *cmsg;
419         static struct iovec iov;
420         struct ucred c;
421         int ret;
422
423         /* Response data */
424         iov.iov_base = buf;
425         iov.iov_len  = strlen(buf);
426         c.pid = getpid();
427         c.uid = getuid();
428         c.gid = getgid();
429         /* compose the message */
430         memset(&msg, 0, sizeof(msg));
431         msg.msg_iov = &iov;
432         msg.msg_iovlen = 1;
433         msg.msg_control = control;
434         msg.msg_controllen = sizeof(control);
435         /* attach the ucred struct */
436         cmsg = CMSG_FIRSTHDR(&msg);
437         cmsg->cmsg_level = SOL_SOCKET;
438         cmsg->cmsg_type = SCM_CREDENTIALS;
439         cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
440         *(struct ucred *)CMSG_DATA(cmsg) = c;
441         msg.msg_controllen = cmsg->cmsg_len;
442         ret = sendmsg(sock, &msg, 0);
443         if (ret  < 0)
444                 ret = -E_SENDMSG;
445         return ret;
446 }
447
448 static void dispose_fds(int *fds, int num)
449 {
450         int i;
451
452         for (i = 0; i < num; i++)
453                 close(fds[i]);
454 }
455
456 /**
457  * receive a buffer and the Unix credentials of the sending process
458  *
459  * \param fd the socket file descriptor
460  * \param buf the buffer to store the message
461  * \param size the size of \a buffer
462  *
463  * \return negative on errors, the user id on success.
464  *
465  * \sa okir's Black Hats Manual
466  * \sa recvmsg(2)
467  */
468 int recv_cred_buffer(int fd, char *buf, size_t size)
469 {
470         char control[255];
471         struct msghdr msg;
472         struct cmsghdr *cmsg;
473         struct iovec iov;
474         int result = 0;
475         int yes = 1;
476         struct ucred cred;
477
478         setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
479         memset(&msg, 0, sizeof(msg));
480         memset(buf, 0, size);
481         iov.iov_base = buf;
482         iov.iov_len = size;
483         msg.msg_iov = &iov;
484         msg.msg_iovlen = 1;
485         msg.msg_control = control;
486         msg.msg_controllen = sizeof(control);
487         if (recvmsg(fd, &msg, 0) < 0)
488                 return -E_RECVMSG;
489         result = -E_SCM_CREDENTIALS;
490         cmsg = CMSG_FIRSTHDR(&msg);
491         while (cmsg) {
492                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
493                                 == SCM_CREDENTIALS) {
494                         memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
495                         result = cred.uid;
496                 } else
497                         if (cmsg->cmsg_level == SOL_SOCKET
498                                         && cmsg->cmsg_type == SCM_RIGHTS) {
499                                 dispose_fds((int *) CMSG_DATA(cmsg),
500                                         (cmsg->cmsg_len - CMSG_LEN(0))
501                                         / sizeof(int));
502                         }
503                 cmsg = CMSG_NXTHDR(&msg, cmsg);
504         }
505         return result;
506 }
507 #endif /* HAVE_UCRED */
508
509 /** how many pending connections queue will hold */
510 #define BACKLOG 10
511
512 /**
513  * create a socket, bind it and listen
514  * \param port the tcp port to listen on
515  *
516  * \return The file descriptor of the created socket, negative
517  * on errors.
518  *
519  * \sa get_socket()
520  * \sa setsockopt(2)
521  * \sa bind(2)
522  * \sa listen(2)
523  */
524 int init_tcp_socket(int port)
525 {
526         struct sockaddr_in my_addr;
527         int fd, ret = get_socket();
528
529         if (ret < 0)
530                 return ret;
531         fd = ret;
532         ret = setserversockopts(fd);
533         if (ret < 0)
534                 goto err;
535         init_sockaddr(&my_addr, port, NULL);
536         ret = -E_BIND;
537         if (bind(fd, (struct sockaddr *)&my_addr,
538                         sizeof(struct sockaddr)) == -1) {
539                 PARA_CRIT_LOG("bind error: %s\n", strerror(errno));
540                 goto err;
541         }
542         ret = -E_LISTEN;
543         if (listen(fd, BACKLOG) == -1)
544                 goto err;
545         PARA_INFO_LOG("listening on port %d, fd %d\n", port, fd);
546         return fd;
547 err:
548         close(fd);
549         return ret;
550 }
551
552 /**
553  * receive a buffer and check for a pattern
554  *
555  * \param fd the file descriptor to receive from
556  * \param pattern the expected pattern
557  * \param bufsize the size of the internal buffer
558  *
559  * \return Positive if \a pattern was received, negative otherwise.
560  *
561  * This function creates a buffer of size \a bufsize and tries
562  * to receive at most \a bufsize bytes from file descriptor \a fd.
563  * If at least \p strlen(\a pattern) bytes were received, the beginning of
564  * the received buffer is compared with \a pattern, ignoring case.
565  * \sa recv_buffer()
566  * \sa strncasecmp(3)
567  */
568 int recv_pattern(int fd, const char *pattern, size_t bufsize)
569 {
570         size_t len = strlen(pattern);
571         char *buf = para_malloc(bufsize + 1);
572         int ret = -E_RECV_PATTERN, n = recv_buffer(fd, buf, bufsize);
573
574         if (n < len)
575                 goto out;
576         if (strncasecmp(buf, pattern, len))
577                 goto out;
578         ret = 1;
579 out:
580         if (ret < 0) {
581                 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n, pattern);
582                 if (n > 0)
583                         PARA_NOTICE_LOG("recvd: %s\n", buf);
584         }
585         free(buf);
586         return ret;
587 }