net.c: Fix a fd leak in create_local_socket().
[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 a 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_local_socket(const char *name, struct sockaddr_un *unix_addr,
393 mode_t mode)
394 {
395 int fd, ret;
396
397 ret = init_unix_addr(unix_addr, name);
398 if (ret < 0)
399 return ret;
400 fd = socket(PF_UNIX, SOCK_STREAM, 0);
401 if (fd < 0)
402 return -E_SOCKET;
403 ret = -E_BIND;
404 if (bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX) < 0)
405 goto err;
406 ret = -E_CHMOD;
407 if (chmod(name, mode) < 0)
408 goto err;
409 return fd;
410 err:
411 close(fd);
412 return ret;
413 }
414
415 #ifndef HAVE_UCRED
416 ssize_t send_cred_buffer(int sock, char *buf)
417 {
418 return send_buffer(sock, buf);
419 }
420 int recv_cred_buffer(int fd, char *buf, size_t size)
421 {
422 return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
423 }
424 #else /* HAVE_UCRED */
425 /**
426 * send NULL terminated buffer and Unix credentials of the current process
427 *
428 * \param sock the socket file descriptor
429 * \param buf the buffer to be sent
430 *
431 * \return On success, this call returns the number of characters sent. On
432 * error, \p -E_SENDMSG ist returned.
433 *
434 * \sa okir's Black Hats Manual
435 * \sa sendmsg(2)
436 */
437 ssize_t send_cred_buffer(int sock, char *buf)
438 {
439 char control[sizeof(struct cmsghdr) + 10];
440 struct msghdr msg;
441 struct cmsghdr *cmsg;
442 static struct iovec iov;
443 struct ucred c;
444 int ret;
445
446 /* Response data */
447 iov.iov_base = buf;
448 iov.iov_len = strlen(buf);
449 c.pid = getpid();
450 c.uid = getuid();
451 c.gid = getgid();
452 /* compose the message */
453 memset(&msg, 0, sizeof(msg));
454 msg.msg_iov = &iov;
455 msg.msg_iovlen = 1;
456 msg.msg_control = control;
457 msg.msg_controllen = sizeof(control);
458 /* attach the ucred struct */
459 cmsg = CMSG_FIRSTHDR(&msg);
460 cmsg->cmsg_level = SOL_SOCKET;
461 cmsg->cmsg_type = SCM_CREDENTIALS;
462 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
463 *(struct ucred *)CMSG_DATA(cmsg) = c;
464 msg.msg_controllen = cmsg->cmsg_len;
465 ret = sendmsg(sock, &msg, 0);
466 if (ret < 0)
467 ret = -E_SENDMSG;
468 return ret;
469 }
470
471 static void dispose_fds(int *fds, unsigned num)
472 {
473 int i;
474
475 for (i = 0; i < num; i++)
476 close(fds[i]);
477 }
478
479 /**
480 * receive a buffer and the Unix credentials of the sending process
481 *
482 * \param fd the socket file descriptor
483 * \param buf the buffer to store the message
484 * \param size the size of \a buffer
485 *
486 * \return negative on errors, the user id on success.
487 *
488 * \sa okir's Black Hats Manual
489 * \sa recvmsg(2)
490 */
491 int recv_cred_buffer(int fd, char *buf, size_t size)
492 {
493 char control[255];
494 struct msghdr msg;
495 struct cmsghdr *cmsg;
496 struct iovec iov;
497 int result = 0;
498 int yes = 1;
499 struct ucred cred;
500
501 setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
502 memset(&msg, 0, sizeof(msg));
503 memset(buf, 0, size);
504 iov.iov_base = buf;
505 iov.iov_len = size;
506 msg.msg_iov = &iov;
507 msg.msg_iovlen = 1;
508 msg.msg_control = control;
509 msg.msg_controllen = sizeof(control);
510 if (recvmsg(fd, &msg, 0) < 0)
511 return -E_RECVMSG;
512 result = -E_SCM_CREDENTIALS;
513 cmsg = CMSG_FIRSTHDR(&msg);
514 while (cmsg) {
515 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
516 == SCM_CREDENTIALS) {
517 memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
518 result = cred.uid;
519 } else
520 if (cmsg->cmsg_level == SOL_SOCKET
521 && cmsg->cmsg_type == SCM_RIGHTS) {
522 dispose_fds((int *) CMSG_DATA(cmsg),
523 (cmsg->cmsg_len - CMSG_LEN(0))
524 / sizeof(int));
525 }
526 cmsg = CMSG_NXTHDR(&msg, cmsg);
527 }
528 return result;
529 }
530 #endif /* HAVE_UCRED */
531
532 /** how many pending connections queue will hold */
533 #define BACKLOG 10
534
535 /**
536 * create a socket, bind it and listen
537 *
538 * \param port the tcp port to listen on
539 *
540 * \return The file descriptor of the created socket, negative
541 * on errors.
542 *
543 * \sa get_socket()
544 * \sa setsockopt(2)
545 * \sa bind(2)
546 * \sa listen(2)
547 */
548 int init_tcp_socket(int port)
549 {
550 struct sockaddr_in my_addr;
551 int fd, ret = get_socket();
552
553 if (ret < 0)
554 return ret;
555 fd = ret;
556 ret = setserversockopts(fd);
557 if (ret < 0)
558 goto err;
559 init_sockaddr(&my_addr, port, NULL);
560 ret = -E_BIND;
561 if (bind(fd, (struct sockaddr *)&my_addr,
562 sizeof(struct sockaddr)) == -1) {
563 PARA_CRIT_LOG("bind error: %s\n", strerror(errno));
564 goto err;
565 }
566 ret = -E_LISTEN;
567 if (listen(fd, BACKLOG) == -1)
568 goto err;
569 PARA_INFO_LOG("listening on port %d, fd %d\n", port, fd);
570 return fd;
571 err:
572 close(fd);
573 return ret;
574 }
575
576 /**
577 * receive a buffer and check for a pattern
578 *
579 * \param fd the file descriptor to receive from
580 * \param pattern the expected pattern
581 * \param bufsize the size of the internal buffer
582 *
583 * \return Positive if \a pattern was received, negative otherwise.
584 *
585 * This function creates a buffer of size \a bufsize and tries
586 * to receive at most \a bufsize bytes from file descriptor \a fd.
587 * If at least \p strlen(\a pattern) bytes were received, the beginning of
588 * the received buffer is compared with \a pattern, ignoring case.
589 *
590 * \sa recv_buffer()
591 * \sa strncasecmp(3)
592 */
593 int recv_pattern(int fd, const char *pattern, size_t bufsize)
594 {
595 size_t len = strlen(pattern);
596 char *buf = para_malloc(bufsize + 1);
597 int ret = -E_RECV_PATTERN, n = recv_buffer(fd, buf, bufsize);
598
599 if (n < len)
600 goto out;
601 if (strncasecmp(buf, pattern, len))
602 goto out;
603 ret = 1;
604 out:
605 if (ret < 0) {
606 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n, pattern);
607 if (n > 0)
608 PARA_NOTICE_LOG("recvd: %s\n", buf);
609 }
610 free(buf);
611 return ret;
612 }