]> git.tuebingen.mpg.de Git - paraslash.git/blob - net.c
init_tcp_socket: close socket fd on errors
[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  * \param ret the hostent structure is returned here
229  *
230  * \return positive on success, negative on errors. On success, \a ret
231  * contains the return value of the underlying gethostbyname() call.
232  *
233  * \sa gethostbyname(2)
234  */
235 int get_host_info(char *host, struct hostent **ret)
236 {
237         PARA_INFO_LOG("getting host info of %s\n", host);
238         /* FIXME: gethostbyname() is obsolete */
239         *ret = gethostbyname(host);
240         return *ret? 1 : -E_HOST_INFO;
241 }
242
243 /**
244  * a wrapper around socket(2)
245  *
246  * Create an IPv4 socket for sequenced, reliable, two-way, connection-based
247  * byte streams.
248  *
249  * @return The socket fd on success, -E_SOCKET on errors.
250  * \sa socket(2)
251  */
252 int get_socket(void)
253 {
254         int socket_fd;
255
256         if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
257                 return -E_SOCKET;
258         return socket_fd;
259 }
260
261 /**
262  * a wrapper around connect(2)
263  *
264  * @param fd the file descriptor
265  * @param their_addr the address to connect
266  *
267  * @return \p -E_CONNECT on errors, 1 on success
268  * \sa connect(2)
269  */
270 int para_connect(int fd, struct sockaddr_in *their_addr)
271 {
272         int ret;
273
274         if ((ret = connect(fd, (struct sockaddr *)their_addr,
275                         sizeof(struct sockaddr))) == -1)
276                 return -E_CONNECT;
277         return 1;
278 }
279
280 /**
281  * paraslash's wrapper around the accept system call
282  *
283  * @param fd the listening socket
284  * @param addr structure which is filled in with the address of the peer socket
285  * @param size should contain the size of the structure pointed to by \a addr
286  *
287  * \sa accept(2).
288  */
289 int para_accept(int fd, void *addr, socklen_t size)
290 {
291         int new_fd;
292
293         new_fd = accept(fd, (struct sockaddr *) addr, &size);
294         return new_fd == -1? -E_ACCEPT : new_fd;
295 }
296
297 static int setserversockopts(int socket_fd)
298 {
299         int yes = 1;
300
301         if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes,
302                         sizeof(int)) == -1)
303                 return -E_SETSOCKOPT;
304         return 1;
305 }
306
307 /**
308  * prepare a structure for \p AF_UNIX socket addresses
309  *
310  * \param u pointer to the struct to be prepared
311  * \param name the socket pathname
312  *
313  * This just copies \a name to the sun_path component of \a u.
314  *
315  * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
316  * than \p UNIX_PATH_MAX.
317  */
318 int init_unix_addr(struct sockaddr_un *u, const char *name)
319 {
320         if (strlen(name) >= UNIX_PATH_MAX)
321                 return -E_NAME_TOO_LONG;
322         memset(u->sun_path, 0, UNIX_PATH_MAX);
323         u->sun_family = PF_UNIX;
324         strcpy(u->sun_path, name);
325         return 1;
326 }
327
328 /**
329  * prepare, create, and bind and socket for local communication
330  *
331  * \param name the socket pathname
332  * \param unix_addr pointer to the \p AF_UNIX socket structure
333  * \param mode the desired mode of the socket
334  *
335  * This functions creates a local socket for sequenced, reliable,
336  * two-way, connection-based byte streams.
337  * \sa socket(2)
338  * \sa bind(2)
339  * \sa chmod(2)
340  */
341 int create_pf_socket(const char *name, struct sockaddr_un *unix_addr, int mode)
342 {
343         int fd, ret;
344
345         fd = socket(PF_UNIX, SOCK_STREAM, 0);
346         if (fd < 0)
347                 return -E_SOCKET;
348 //      unlink(name);
349         ret = init_unix_addr(unix_addr, name);
350         if (ret < 0)
351                 return ret;
352         if (bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX) < 0)
353                 return -E_BIND;
354         if (chmod(name, mode) < 0)
355                 return -E_CHMOD;
356         return fd;
357 }
358
359 #ifndef HAVE_UCRED
360         struct ucred {
361         uid_t uid, pid, gid;
362 };
363 ssize_t send_cred_buffer(int sock, char *buf)
364 {
365         return send_buffer(sock, buf);
366 }
367 int recv_cred_buffer(int fd, char *buf, size_t size)
368 {
369         return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
370 }
371 #else /* HAVE_UCRED */
372 /**
373  * send NULL terminated buffer and Unix credentials of the current process
374  *
375  * \param sock the socket file descriptor
376  * \param buf the buffer to be sent
377  *
378  * \return On success, this call returns the number of characters sent.  On
379  * error, \p -E_SENDMSG ist returned.
380  * \sa  okir's Black Hats Manual
381  * \sa sendmsg(2)
382  */
383 ssize_t send_cred_buffer(int sock, char *buf)
384 {
385         char control[sizeof(struct cmsghdr) + 10];
386         struct msghdr msg;
387         struct cmsghdr *cmsg;
388         static struct iovec iov;
389         struct ucred c;
390         int ret;
391
392         /* Response data */
393         iov.iov_base = buf;
394         iov.iov_len  = strlen(buf);
395         c.pid = getpid();
396         c.uid = getuid();
397         c.gid = getgid();
398         /* compose the message */
399         memset(&msg, 0, sizeof(msg));
400         msg.msg_iov = &iov;
401         msg.msg_iovlen = 1;
402         msg.msg_control = control;
403         msg.msg_controllen = sizeof(control);
404         /* attach the ucred struct */
405         cmsg = CMSG_FIRSTHDR(&msg);
406         cmsg->cmsg_level = SOL_SOCKET;
407         cmsg->cmsg_type = SCM_CREDENTIALS;
408         cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
409         *(struct ucred *)CMSG_DATA(cmsg) = c;
410         msg.msg_controllen = cmsg->cmsg_len;
411         ret = sendmsg(sock, &msg, 0);
412         if (ret  < 0)
413                 ret = -E_SENDMSG;
414         return ret;
415 }
416
417 static void dispose_fds(int *fds, int num)
418 {
419         int i;
420
421         for (i = 0; i < num; i++)
422                 close(fds[i]);
423 }
424
425 /**
426  * receive a buffer and the Unix credentials of the sending process
427  *
428  * \param fd the socket file descriptor
429  * \param buf the buffer to store the message
430  * \param size the size of \a buffer
431  *
432  * \return negative on errors, the user id on success.
433  *
434  * \sa okir's Black Hats Manual
435  * \sa recvmsg(2)
436  */
437 int recv_cred_buffer(int fd, char *buf, size_t size)
438 {
439         char control[255];
440         struct msghdr msg;
441         struct cmsghdr *cmsg;
442         struct iovec iov;
443         int result = 0;
444         int yes = 1;
445         struct ucred cred;
446
447         setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
448         memset(&msg, 0, sizeof(msg));
449         memset(buf, 0, size);
450         iov.iov_base = buf;
451         iov.iov_len = size;
452         msg.msg_iov = &iov;
453         msg.msg_iovlen = 1;
454         msg.msg_control = control;
455         msg.msg_controllen = sizeof(control);
456         if (recvmsg(fd, &msg, 0) < 0)
457                 return -E_RECVMSG;
458         result = -E_SCM_CREDENTIALS;
459         cmsg = CMSG_FIRSTHDR(&msg);
460         while (cmsg) {
461                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
462                                 == SCM_CREDENTIALS) {
463                         memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
464                         result = cred.uid;
465                 } else
466                         if (cmsg->cmsg_level == SOL_SOCKET
467                                         && cmsg->cmsg_type == SCM_RIGHTS) {
468                                 dispose_fds((int *) CMSG_DATA(cmsg),
469                                         (cmsg->cmsg_len - CMSG_LEN(0))
470                                         / sizeof(int));
471                         }
472                 cmsg = CMSG_NXTHDR(&msg, cmsg);
473         }
474         return result;
475 }
476 #endif /* HAVE_UCRED */
477
478 /** how many pending connections queue will hold */
479 #define BACKLOG 10
480
481 /**
482  * create a socket, bind it and listen
483  * \param port the tcp port to listen on
484  *
485  * \return The file descriptor of the created socket, negative
486  * on errors.
487  *
488  * \sa get_socket()
489  * \sa setsockopt(2)
490  * \sa bind(2)
491  * \sa listen(2)
492  */
493 int init_tcp_socket(int port)
494 {
495         struct sockaddr_in my_addr;
496         int fd, ret = get_socket();
497
498         if (ret < 0)
499                 return ret;
500         fd = ret;
501         ret = setserversockopts(fd);
502         if (ret < 0)
503                 goto err;
504         init_sockaddr(&my_addr, port, NULL);
505         ret = -E_BIND;
506         if (bind(fd, (struct sockaddr *)&my_addr,
507                         sizeof(struct sockaddr)) == -1) {
508                 PARA_CRIT_LOG("bind error: %s\n", strerror(errno));
509                 goto err;
510         }
511         ret = -E_LISTEN;
512         if (listen(fd, BACKLOG) == -1)
513                 goto err;
514         PARA_INFO_LOG("listening on port %d, fd %d\n", port, fd);
515         return fd;
516 err:
517         close(fd);
518         return ret;
519 }
520
521 /**
522  * receive a buffer and check for a pattern
523  *
524  * \param fd the file descriptor to receive from
525  * \param pattern the expected pattern
526  * \param bufsize the size of the internal buffer
527  *
528  * \return Positive if \a pattern was received, negative otherwise.
529  *
530  * This function creates a buffer of size \a bufsize and tries
531  * to receive at most \a bufsize bytes from file descriptor \a fd.
532  * If at least \p strlen(\a pattern) bytes were received, the beginning of
533  * the received buffer is compared with \a pattern, ignoring case.
534  * \sa recv_buffer()
535  * \sa strncasecmp(3)
536  */
537 int recv_pattern(int fd, const char *pattern, size_t bufsize)
538 {
539         size_t len = strlen(pattern);
540         char *buf = para_malloc(bufsize + 1);
541         int ret = -E_RECV_PATTERN, n = recv_buffer(fd, buf, bufsize);
542
543         if (n < len)
544                 goto out;
545         if (strncasecmp(buf, pattern, len))
546                 goto out;
547         ret = 1;
548 out:
549         if (ret < 0)
550                 PARA_NOTICE_LOG("did not receive pattern '%s'\n", pattern);
551         free(buf);
552         return ret;
553 }