fix trivial typo
[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 "net.h"
11 #include "string.h"
12 #include "error.h"
13
14
15 /** holds 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         /** context-dependent data, passed to \a recv() and \a send() */
22         void *private_data;
23 };
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;
28
29
30 /**
31  * activate encryption for one file descriptor
32  *
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
37  */
38 void enable_crypt(int fd, crypt_function *recv_f, crypt_function *send_f,
39         void *private_data)
40 {
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));
46                 cda_size = fd + 1;
47         }
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);
52 }
53
54 /**
55  * deactivate encryption for a given fd
56  *
57  * \param fd the file descriptor
58  *
59  * This must be called if and only if \p fd was activated via enable_crypt().
60  */
61 void disable_crypt(int fd)
62 {
63         if (cda_size < fd + 1)
64                 return;
65         crypt_data_array[fd].recv = NULL;
66         crypt_data_array[fd].send = NULL;
67         crypt_data_array[fd].private_data = NULL;
68 }
69
70
71 /**
72  * initialize a struct sockaddr_in
73  *
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
77  *
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.
80  */
81 void init_sockaddr(struct sockaddr_in *addr, int port, const struct hostent *he)
82 {
83         /* host byte order */
84         addr->sin_family = AF_INET;
85         /* short, network byte order */
86         addr->sin_port = htons(port);
87         if (he)
88                 addr->sin_addr = *((struct in_addr *)he->h_addr);
89         else
90                 addr->sin_addr.s_addr = INADDR_ANY;
91         /* zero the rest of the struct */
92         memset(&addr->sin_zero, '\0', 8);
93 }
94
95 /*
96  * send out a buffer, resend on short writes
97  *
98  * \param fd the file descriptor
99  * \param buf The buffer to be sent
100  * \param len The length of \a buf
101  *
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).
105  *
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.
108  */
109 static int sendall(int fd, const char *buf, size_t *len)
110 {
111         size_t total = 0, bytesleft = *len; /* how many we have left to send */
112         int n = -1;
113
114         while (total < *len) {
115                 n = send(fd, buf + total, bytesleft, 0);
116                 if (n == -1)
117                         break;
118                 total += n;
119                 bytesleft -= n;
120                 if (total < *len)
121                         PARA_DEBUG_LOG("short write (%zd byte(s) left)",
122                                 *len - total);
123         }
124         *len = total; /* return number actually sent here */
125         return n == -1? -E_SEND : 1; /* return 1 on success */
126 }
127
128 /**
129  * encrypt and send buffer
130  *
131  * \param fd:  the file descriptor
132  * \param buf the buffer to be encrypted and sent
133  * \param len the length of \a buf
134  *
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
137  * short writes.
138  *
139  * \return Positive on success, \p -E_SEND on errors.
140  */
141 int send_bin_buffer(int fd, const char *buf, size_t len)
142 {
143         int ret;
144         crypt_function *cf = NULL;
145
146         if (!len)
147                 PARA_CRIT_LOG("%s", "len == 0\n");
148         if (fd + 1 <= cda_size)
149                 cf = crypt_data_array[fd].send;
150         if (cf) {
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);
155                 free(outbuf);
156         } else
157                 ret = sendall(fd, buf, &len);
158         return ret;
159 }
160
161 /**
162  * encrypt and send null terminated buffer.
163  *
164  * \param fd the file descriptor
165  * \param buf the null-terminated buffer to be send
166  *
167  * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
168  *
169  * \return Positive on success, \p -E_SEND on errors.
170  */
171 int send_buffer(int fd, const char *buf)
172 {
173         return send_bin_buffer(fd, buf, strlen(buf));
174 }
175
176
177 /**
178  * send and encrypt a buffer given by a format string
179  *
180  * \param fd the file descriptor
181  * \param fmt a format string
182  *
183  * \return Positive on success, \p -E_SEND on errors.
184  */
185 __printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
186 {
187         char *msg;
188         int ret;
189
190         PARA_VSPRINTF(fmt, msg);
191         ret = send_buffer(fd, msg);
192         free(msg);
193         return ret;
194 }
195
196 /**
197  * receive and decrypt.
198  *
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
202  *
203  * Receive at most \a size bytes from filedescriptor fd. If encryption is
204  * available, decrypt the received buffer.
205  *
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
208  * returned.
209  *
210  * \sa recv(2)
211  */
212 __must_check int recv_bin_buffer(int fd, char *buf, size_t size)
213 {
214         ssize_t 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                         size_t numbytes = n;
225                         unsigned char *b = (unsigned char *)buf;
226                         (*cf)(numbytes, tmp, b, private);
227                 }
228                 free(tmp);
229         } else
230                 n = recv(fd, buf, size, 0);
231         if (n == -1)
232                 n = -E_RECV;
233         return n;
234 }
235
236 /**
237  * receive, decrypt and write terminating NULL byte
238  *
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
242  *
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.
245  *
246  * \return: The return value of the underlying call to \a recv_bin_buffer().
247  *
248  * \sa recv_bin_buffer()
249  */
250 int recv_buffer(int fd, char *buf, size_t size)
251 {
252         int n;
253
254         if (!size)
255                 return -E_RECV;
256         n = recv_bin_buffer(fd, buf, size - 1);
257         if (n >= 0)
258                 buf[n] = '\0';
259         else
260                 *buf = '\0';
261         return n;
262 }
263
264 /**
265  * wrapper around gethostbyname
266  *
267  * \param host hostname or IPv4 address
268  * \param ret the hostent structure is returned here
269  *
270  * \return positive on success, negative on errors. On success, \a ret
271  * contains the return value of the underlying gethostbyname() call.
272  *
273  * \sa gethostbyname(2)
274  */
275 int get_host_info(char *host, struct hostent **ret)
276 {
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;
281 }
282
283 /**
284  * a wrapper around socket(2)
285  *
286  * Create an IPv4 socket for sequenced, reliable, two-way, connection-based
287  * byte streams.
288  *
289  * \return The socket fd on success, -E_SOCKET on errors.
290  *
291  * \sa socket(2)
292  */
293 int get_socket(void)
294 {
295         int socket_fd;
296
297         if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
298                 return -E_SOCKET;
299         return socket_fd;
300 }
301
302 /**
303  * a wrapper around connect(2)
304  *
305  * \param fd the file descriptor
306  * \param their_addr the address to connect
307  *
308  * \return \p -E_CONNECT on errors, 1 on success
309  *
310  * \sa connect(2)
311  */
312 int para_connect(int fd, struct sockaddr_in *their_addr)
313 {
314         int ret;
315
316         if ((ret = connect(fd, (struct sockaddr *)their_addr,
317                         sizeof(struct sockaddr))) == -1)
318                 return -E_CONNECT;
319         return 1;
320 }
321
322 /**
323  * paraslash's wrapper around the accept system call
324  *
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
328  *
329  * Accept incoming connections on \a addr. Retry if interrupted.
330  *
331  * \return The new file descriptor on success, \a -E_ACCEPT on errors.
332  *
333  * \sa accept(2).
334  */
335 int para_accept(int fd, void *addr, socklen_t size)
336 {
337         int new_fd;
338
339         do
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;
343 }
344
345 static int setserversockopts(int socket_fd)
346 {
347         int yes = 1;
348
349         if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes,
350                         sizeof(int)) == -1)
351                 return -E_SETSOCKOPT;
352         return 1;
353 }
354
355 /**
356  * prepare a structure for \p AF_UNIX socket addresses
357  *
358  * \param u pointer to the struct to be prepared
359  * \param name the socket pathname
360  *
361  * This just copies \a name to the sun_path component of \a u.
362  *
363  * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
364  * than \p UNIX_PATH_MAX.
365  */
366 int init_unix_addr(struct sockaddr_un *u, const char *name)
367 {
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);
373         return 1;
374 }
375
376 /**
377  * prepare, create, and bind and socket for local communication
378  *
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
382  *
383  * This functions creates a local socket for sequenced, reliable,
384  * two-way, connection-based byte streams.
385  *
386  * \return The file descriptor, on success, negative on errors.
387  *
388  * \sa socket(2)
389  * \sa bind(2)
390  * \sa chmod(2)
391  */
392 int create_pf_socket(const char *name, struct sockaddr_un *unix_addr,
393                 mode_t mode)
394 {
395         int fd, ret;
396
397         fd = socket(PF_UNIX, SOCK_STREAM, 0);
398         if (fd < 0)
399                 return -E_SOCKET;
400 //      unlink(name);
401         ret = init_unix_addr(unix_addr, name);
402         if (ret < 0)
403                 return ret;
404         if (bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX) < 0)
405                 return -E_BIND;
406         if (chmod(name, mode) < 0)
407                 return -E_CHMOD;
408         return fd;
409 }
410
411 #ifndef HAVE_UCRED
412 ssize_t send_cred_buffer(int sock, char *buf)
413 {
414         return send_buffer(sock, buf);
415 }
416 int recv_cred_buffer(int fd, char *buf, size_t size)
417 {
418         return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
419 }
420 #else /* HAVE_UCRED */
421 /**
422  * send NULL terminated buffer and Unix credentials of the current process
423  *
424  * \param sock the socket file descriptor
425  * \param buf the buffer to be sent
426  *
427  * \return On success, this call returns the number of characters sent.  On
428  * error, \p -E_SENDMSG ist returned.
429  *
430  * \sa  okir's Black Hats Manual
431  * \sa sendmsg(2)
432  */
433 ssize_t send_cred_buffer(int sock, char *buf)
434 {
435         char control[sizeof(struct cmsghdr) + 10];
436         struct msghdr msg;
437         struct cmsghdr *cmsg;
438         static struct iovec iov;
439         struct ucred c;
440         int ret;
441
442         /* Response data */
443         iov.iov_base = buf;
444         iov.iov_len  = strlen(buf);
445         c.pid = getpid();
446         c.uid = getuid();
447         c.gid = getgid();
448         /* compose the message */
449         memset(&msg, 0, sizeof(msg));
450         msg.msg_iov = &iov;
451         msg.msg_iovlen = 1;
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);
462         if (ret  < 0)
463                 ret = -E_SENDMSG;
464         return ret;
465 }
466
467 static void dispose_fds(int *fds, unsigned num)
468 {
469         int i;
470
471         for (i = 0; i < num; i++)
472                 close(fds[i]);
473 }
474
475 /**
476  * receive a buffer and the Unix credentials of the sending process
477  *
478  * \param fd the socket file descriptor
479  * \param buf the buffer to store the message
480  * \param size the size of \a buffer
481  *
482  * \return negative on errors, the user id on success.
483  *
484  * \sa okir's Black Hats Manual
485  * \sa recvmsg(2)
486  */
487 int recv_cred_buffer(int fd, char *buf, size_t size)
488 {
489         char control[255];
490         struct msghdr msg;
491         struct cmsghdr *cmsg;
492         struct iovec iov;
493         int result = 0;
494         int yes = 1;
495         struct ucred cred;
496
497         setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
498         memset(&msg, 0, sizeof(msg));
499         memset(buf, 0, size);
500         iov.iov_base = buf;
501         iov.iov_len = size;
502         msg.msg_iov = &iov;
503         msg.msg_iovlen = 1;
504         msg.msg_control = control;
505         msg.msg_controllen = sizeof(control);
506         if (recvmsg(fd, &msg, 0) < 0)
507                 return -E_RECVMSG;
508         result = -E_SCM_CREDENTIALS;
509         cmsg = CMSG_FIRSTHDR(&msg);
510         while (cmsg) {
511                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
512                                 == SCM_CREDENTIALS) {
513                         memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
514                         result = cred.uid;
515                 } else
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))
520                                         / sizeof(int));
521                         }
522                 cmsg = CMSG_NXTHDR(&msg, cmsg);
523         }
524         return result;
525 }
526 #endif /* HAVE_UCRED */
527
528 /** how many pending connections queue will hold */
529 #define BACKLOG 10
530
531 /**
532  * create a socket, bind it and listen
533  *
534  * \param port the tcp port to listen on
535  *
536  * \return The file descriptor of the created socket, negative
537  * on errors.
538  *
539  * \sa get_socket()
540  * \sa setsockopt(2)
541  * \sa bind(2)
542  * \sa listen(2)
543  */
544 int init_tcp_socket(int port)
545 {
546         struct sockaddr_in my_addr;
547         int fd, ret = get_socket();
548
549         if (ret < 0)
550                 return ret;
551         fd = ret;
552         ret = setserversockopts(fd);
553         if (ret < 0)
554                 goto err;
555         init_sockaddr(&my_addr, port, NULL);
556         ret = -E_BIND;
557         if (bind(fd, (struct sockaddr *)&my_addr,
558                         sizeof(struct sockaddr)) == -1) {
559                 PARA_CRIT_LOG("bind error: %s\n", strerror(errno));
560                 goto err;
561         }
562         ret = -E_LISTEN;
563         if (listen(fd, BACKLOG) == -1)
564                 goto err;
565         PARA_INFO_LOG("listening on port %d, fd %d\n", port, fd);
566         return fd;
567 err:
568         close(fd);
569         return ret;
570 }
571
572 /**
573  * receive a buffer and check for a pattern
574  *
575  * \param fd the file descriptor to receive from
576  * \param pattern the expected pattern
577  * \param bufsize the size of the internal buffer
578  *
579  * \return Positive if \a pattern was received, negative otherwise.
580  *
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.
585  *
586  * \sa recv_buffer()
587  * \sa strncasecmp(3)
588  */
589 int recv_pattern(int fd, const char *pattern, size_t bufsize)
590 {
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);
594
595         if (n < len)
596                 goto out;
597         if (strncasecmp(buf, pattern, len))
598                 goto out;
599         ret = 1;
600 out:
601         if (ret < 0) {
602                 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n, pattern);
603                 if (n > 0)
604                         PARA_NOTICE_LOG("recvd: %s\n", buf);
605         }
606         free(buf);
607         return ret;
608 }