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