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