aacdec: Fix some signedness issues
[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 <netdb.h>
25 #include "error.h"
26
27 extern void (*crypt_function_recv)(unsigned long len, const unsigned char *indata, unsigned char *outdata);
28 extern void (*crypt_function_send)(unsigned long len, const unsigned char *indata, unsigned char *outdata);
29
30
31 /**
32  * initialize a struct sockaddr_in
33  * @param addr A pointer to the struct to be initialized
34  * @param port The port number to use
35  * @param he The address to use
36  *
37  * If \a he is null (server mode), \a addr->sin_addr is initialized with \p INADDR_ANY.
38  * Otherwise, the address given by \a he is copied to addr.
39  */
40 void init_sockaddr(struct sockaddr_in *addr, int port, const struct hostent *he)
41 {
42         /* host byte order */
43         addr->sin_family = AF_INET;
44         /* short, network byte order */
45         addr->sin_port = htons(port);
46         if (he)
47                 addr->sin_addr = *((struct in_addr *)he->h_addr);
48         else
49                 addr->sin_addr.s_addr = INADDR_ANY;
50         /* zero the rest of the struct */
51         memset(&addr->sin_zero, '\0', 8);
52 }
53
54 /*
55  * send out a buffer, resend on short writes
56  * @param fd the file descriptor
57  * @param buf The buffer to be sent
58  * @len The length of \a buf
59  *
60  * Due to circumstances beyond your control, the kernel might not send all the
61  * data out in one chunk, and now, my friend, it's up to us to get the data out
62  * there (Beej's Guide to Network Programming).
63  */
64 static int sendall(int fd, const char *buf, size_t *len)
65 {
66         int total = 0;        /* how many bytes we've sent */
67         int bytesleft = *len; /* how many we have left to send */
68         int n = -1;
69
70         while (total < *len) {
71                 n = send(fd, buf + total, bytesleft, 0);
72                 if (n == -1)
73                         break;
74                 total += n;
75                 bytesleft -= n;
76                 if (total < *len)
77                         PARA_DEBUG_LOG("short write (%zd byte(s) left)",
78                                 *len - total);
79         }
80         *len = total; /* return number actually sent here */
81         return n == -1? -E_SEND : 1; /* return 1 on success */
82 }
83
84 /**
85  * encrypt and send buffer
86  * @param fd:  the file descriptor
87  * @param buf the buffer to be encrypted and sent
88  * @param len the length of \a buf
89  *
90  * Check if encrytion is available. If yes, encrypt the given buffer.  Send out
91  * the buffer, encrypted or not, and try to resend the remaing part in case of
92  * short writes.
93  *
94  * @return Positive on success, \p -E_SEND on errors.
95  */
96 int send_bin_buffer(int fd, const char *buf, size_t len)
97 {
98         int ret;
99
100         if (!len)
101                 PARA_CRIT_LOG("%s", "len == 0\n");
102         if (crypt_function_send) {
103                 unsigned char *outbuf = para_malloc(len);
104                 crypt_function_send(len, (unsigned char *)buf, outbuf);
105                 ret = sendall(fd, (char *)outbuf, &len);
106                 free(outbuf);
107         } else
108                 ret = sendall(fd, buf, &len);
109         return ret;
110 }
111
112 /**
113  * encrypt and send null terminated buffer.
114  * @param fd the file descriptor
115  * @param buf the null-terminated buffer to be send
116  *
117  * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
118  *
119  * @return Positive on success, \p -E_SEND on errors.
120  */
121 int send_buffer(int fd, const char *buf)
122 {
123         return send_bin_buffer(fd, buf, strlen(buf));
124 }
125
126
127 /**
128  * send and encrypt a buffer given by a format string
129  * @param fd the file descriptor
130  * @param fmt a format string
131  *
132  * @return Positive on success, \p -E_SEND on errors.
133  */
134 __printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
135 {
136         char *msg;
137         int ret;
138
139         PARA_VSPRINTF(fmt, msg);
140         ret = send_buffer(fd, msg);
141         free(msg);
142         return ret;
143 }
144
145 /**
146  * receive and decrypt.
147  *
148  * @param fd the file descriptor
149  * @param buf the buffer to write the decrypted data to
150  * @param size the size of @param buf
151  *
152  * Receive at most \a size bytes from filedescriptor fd. If encrytion is
153  * available, decrypt the received buffer.
154  *
155  * @return the number of bytes received on success. On receive errors, -E_RECV
156  * is returned. On crypt errors, the corresponding crypt error number is
157  * returned.
158  * \sa recv(2)
159  */
160 __must_check int recv_bin_buffer(int fd, char *buf, ssize_t size)
161 {
162         int n;
163
164         if (crypt_function_recv) {
165                 unsigned char *tmp = para_malloc(size);
166                 n = recv(fd, tmp, size, 0);
167                 if (n > 0)
168                         crypt_function_recv(n, tmp, (unsigned char *)buf);
169                 free(tmp);
170         } else
171                 n = recv(fd, buf, size, 0);
172         if (n == -1)
173                 n = -E_RECV;
174         return n;
175 }
176
177 /**
178  * receive, decrypt and write terminating NULL byte
179  *
180  * @param fd the file descriptor
181  * @param buf the buffer to write the decrypted data to
182  * @param size the size of \a buf
183  *
184  * Read and decrypt at most size - 1 bytes from file descriptor \a fd and write
185  * a NULL byte at the end of the received data.
186  *
187 */
188 int recv_buffer(int fd, char *buf, ssize_t size)
189 {
190         int n;
191
192         if ((n = recv_bin_buffer(fd, buf, size - 1)) >= 0)
193                 buf[n] = '\0';
194         return n;
195 }
196
197 /**
198  * wrapper around gethostbyname
199  *
200  * @param host hostname or IPv4 address
201  * \return The hostent structure or a NULL pointer if an error occurs
202  * \sa gethostbyname(2)
203  */
204 struct hostent *get_host_info(char *host)
205 {
206         PARA_INFO_LOG("getting host info of %s\n", host);
207         /* FIXME: gethostbyname() is obsolete */
208         return gethostbyname(host);
209 }
210
211 /**
212  * a wrapper around socket(2)
213  *
214  * Create an IPv4 socket for sequenced, reliable, two-way, connection-based
215  * byte streams.
216  *
217  * @return The socket fd on success, -E_SOCKET on errors.
218  * \sa socket(2)
219  */
220 int get_socket(void)
221 {
222         int socket_fd;
223
224         if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
225                 return -E_SOCKET;
226         return socket_fd;
227 }
228
229 /**
230  * a wrapper around connect(2)
231  *
232  * @param fd the file descriptor
233  * @param their_addr the address to connect
234  *
235  * @return \p -E_CONNECT on errors, 1 on success
236  * \sa connect(2)
237  */
238 int para_connect(int fd, struct sockaddr_in *their_addr)
239 {
240         int ret;
241
242         if ((ret = connect(fd, (struct sockaddr *)their_addr,
243                         sizeof(struct sockaddr))) == -1)
244                 return -E_CONNECT;
245         return 1;
246 }
247
248 /**
249  * paraslash's wrapper around the accept system call
250  *
251  * @param fd the listening socket
252  * @param addr structure which is filled in with the address of the peer socket
253  * @param size should contain the size of the structure pointed to by \a addr
254  *
255  * \sa accept(2).
256  */
257 int para_accept(int fd, void *addr, socklen_t size)
258 {
259         int new_fd;
260
261         new_fd = accept(fd, (struct sockaddr *) addr, &size);
262         return new_fd == -1? -E_ACCEPT : new_fd;
263 }
264
265 static int setserversockopts(int socket_fd)
266 {
267         int yes = 1;
268
269         if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes,
270                         sizeof(int)) == -1)
271                 return -E_SETSOCKOPT;
272         return 1;
273 }
274
275 static int do_bind(int socket_fd, struct sockaddr_in *my_addr)
276 {
277         if (bind(socket_fd, (struct sockaddr *)my_addr,
278                 sizeof(struct sockaddr)) == -1)
279                 return -E_BIND;
280         return 1;
281 }
282
283 /**
284  * prepare a structure for \p AF_UNIX socket addresses
285  *
286  * \param u pointer to the struct to be prepared
287  * \param name the socket pathname
288  *
289  * This just copies \a name to the sun_path component of \a u.
290  *
291  * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
292  * than \p UNIX_PATH_MAX.
293  */
294 int init_unix_addr(struct sockaddr_un *u, const char *name)
295 {
296         if (strlen(name) >= UNIX_PATH_MAX)
297                 return -E_NAME_TOO_LONG;
298         memset(u->sun_path, 0, UNIX_PATH_MAX);
299         u->sun_family = PF_UNIX;
300         strcpy(u->sun_path, name);
301         return 1;
302 }
303
304 /**
305  * prepare, create, and bind and socket for local communication
306  *
307  * \param name the socket pathname
308  * \param unix_addr pointer to the \p AF_UNIX socket structure
309  * \param mode the desired mode of the socket
310  *
311  * This functions creates a local socket for sequenced, reliable,
312  * two-way, connection-based byte streams.
313  * \sa socket(2)
314  * \sa bind(2)
315  * \sa chmod(2)
316  */
317 int create_pf_socket(const char *name, struct sockaddr_un *unix_addr, int mode)
318 {
319         int fd, ret;
320
321         fd = socket(PF_UNIX, SOCK_STREAM, 0);
322         if (fd < 0)
323                 return -E_SOCKET;
324 //      unlink(name);
325         ret = init_unix_addr(unix_addr, name);
326         if (ret < 0)
327                 return ret;
328         if (bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX) < 0)
329                 return -E_BIND;
330         if (chmod(name, mode) < 0)
331                 return -E_CHMOD;
332         return fd;
333 }
334
335 #ifndef HAVE_UCRED
336         struct ucred {
337         uid_t uid, pid, gid;
338 };
339 ssize_t send_cred_buffer(int sock, char *buf)
340 {
341         return send_buffer(sock, buf);
342 }
343 int recv_cred_buffer(int fd, char *buf, size_t size)
344 {
345         return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
346 }
347 #else /* HAVE_UCRED */
348 /**
349  * send NULL terminated buffer and Unix credentials of the current process
350  *
351  * \param sock the socket file descriptor
352  * \param buf the buffer to be sent
353  *
354  * \return On success, this call returns the number of characters sent.  On
355  * error, \p -E_SENDMSG ist returned.
356  * \sa  okir's Black Hats Manual
357  * \sa sendmsg(2)
358  */
359 ssize_t send_cred_buffer(int sock, char *buf)
360 {
361         char control[sizeof(struct cmsghdr) + 10];
362         struct msghdr msg;
363         struct cmsghdr *cmsg;
364         static struct iovec iov;
365         struct ucred c;
366         int ret;
367
368         /* Response data */
369         iov.iov_base = buf;
370         iov.iov_len  = strlen(buf);
371         c.pid = getpid();
372         c.uid = getuid();
373         c.gid = getgid();
374         /* compose the message */
375         memset(&msg, 0, sizeof(msg));
376         msg.msg_iov = &iov;
377         msg.msg_iovlen = 1;
378         msg.msg_control = control;
379         msg.msg_controllen = sizeof(control);
380         /* attach the ucred struct */
381         cmsg = CMSG_FIRSTHDR(&msg);
382         cmsg->cmsg_level = SOL_SOCKET;
383         cmsg->cmsg_type = SCM_CREDENTIALS;
384         cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
385         *(struct ucred *)CMSG_DATA(cmsg) = c;
386         msg.msg_controllen = cmsg->cmsg_len;
387         ret = sendmsg(sock, &msg, 0);
388         if (ret  < 0)
389                 ret = -E_SENDMSG;
390         return ret;
391 }
392
393 static void dispose_fds(int *fds, int num)
394 {
395         int i;
396
397         for (i = 0; i < num; i++)
398                 close(fds[i]);
399 }
400
401 /**
402  * receive a buffer and the Unix credentials of the sending process
403  *
404  * \param fd the socket file descriptor
405  * \param buf the buffer to store the message
406  * \param size the size of \a buffer
407  *
408  * \return negative on errors, the user id on success.
409  *
410  * \sa okir's Black Hats Manual
411  * \sa recvmsg(2)
412  */
413 int recv_cred_buffer(int fd, char *buf, size_t size)
414 {
415         char control[255];
416         struct msghdr msg;
417         struct cmsghdr *cmsg;
418         struct iovec iov;
419         int result = 0;
420         int yes = 1;
421         struct ucred cred;
422
423         setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
424         memset(&msg, 0, sizeof(msg));
425         memset(buf, 0, size);
426         iov.iov_base = buf;
427         iov.iov_len = size;
428         msg.msg_iov = &iov;
429         msg.msg_iovlen = 1;
430         msg.msg_control = control;
431         msg.msg_controllen = sizeof(control);
432         if (recvmsg(fd, &msg, 0) < 0)
433                 return -E_RECVMSG;
434         result = -E_SCM_CREDENTIALS;
435         cmsg = CMSG_FIRSTHDR(&msg);
436         while (cmsg) {
437                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
438                                 == SCM_CREDENTIALS) {
439                         memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
440                         result = cred.uid;
441                 } else
442                         if (cmsg->cmsg_level == SOL_SOCKET
443                                         && cmsg->cmsg_type == SCM_RIGHTS) {
444                                 dispose_fds((int *) CMSG_DATA(cmsg),
445                                         (cmsg->cmsg_len - CMSG_LEN(0))
446                                         / sizeof(int));
447                         }
448                 cmsg = CMSG_NXTHDR(&msg, cmsg);
449         }
450         return result;
451 }
452 #endif /* HAVE_UCRED */
453
454 /** how many pending connections queue will hold */
455 #define BACKLOG 10
456
457 /**
458  * create a socket, bind it and listen
459  * \param port the tcp port to listen on
460  *
461  * \return The file descriptor of the created socket, negative
462  * on errors.
463  *
464  * \sa get_socket()
465  * \sa setsockopt(2)
466  * \sa bind(2)
467  * \sa listen(2)
468  */
469 int init_tcp_socket(int port)
470 {
471         int sockfd, ret;
472         struct sockaddr_in my_addr;
473
474         if ((sockfd = get_socket()) < 0)
475                 return sockfd;
476         ret = setserversockopts(sockfd);
477         if (ret < 0)
478                 return ret;
479         init_sockaddr(&my_addr, port, NULL);
480         ret = do_bind(sockfd, &my_addr);
481         if (ret < 0)
482                 return ret;
483         if (listen(sockfd, BACKLOG) == -1)
484                 return -E_LISTEN;
485         PARA_INFO_LOG("listening on port %d, fd %d\n", port, sockfd);
486         return sockfd;
487 }
488
489 /**
490  * receive a buffer and check for a pattern
491  *
492  * \param fd the file descriptor to receive from
493  * \param pattern the expected pattern
494  * \param bufsize the size of the internal buffer
495  *
496  * \return Positive if \a pattern was received, negative otherwise.
497  *
498  * This function creates a buffer of size \a bufsize and tries
499  * to receive at most \a bufsize bytes from file descriptor \a fd.
500  * If at least \p strlen(\a pattern) bytes were received, the beginning of
501  * the received buffer is compared with \a pattern, ignoring case.
502  * \sa recv_buffer()
503  * \sa strncasecmp(3)
504  */
505 int recv_pattern(int fd, const char *pattern, size_t bufsize)
506 {
507         size_t len = strlen(pattern);
508         char *buf = para_malloc(bufsize + 1);
509         int ret = -E_RECV_PATTERN, n = recv_buffer(fd, buf, bufsize);
510
511         if (n < len)
512                 goto out;
513         if (strncasecmp(buf, pattern, len))
514                 goto out;
515         ret = 1;
516 out:
517         free(buf);
518         if (ret < 0)
519                 PARA_NOTICE_LOG("did not receive pattern '%s'\n", buf);
520         return ret;
521 }