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