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