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