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