]> git.tuebingen.mpg.de Git - paraslash.git/blob - net.c
8860312bf531b225bed615d2fa90d10b1f469534
[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>
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  * Determine the socket type for a given layer-4 protocol.
101  *
102  * \param l4type The symbolic name of the transport-layer protocol.
103  *
104  * \sa ip(7), socket(2)
105  */
106 static inline int sock_type(const unsigned l4type)
107 {
108         switch (l4type) {
109         case IPPROTO_UDP:       return SOCK_DGRAM;
110         case IPPROTO_TCP:       return SOCK_STREAM;
111         case IPPROTO_DCCP:      return SOCK_DCCP;
112         }
113         return -1;              /* not supported here */
114 }
115
116 /**
117  * Pretty-print transport-layer name.
118  */
119 static const char *layer4_name(const unsigned l4type)
120 {
121         switch (l4type) {
122         case IPPROTO_UDP:       return "UDP";
123         case IPPROTO_TCP:       return "TCP";
124         case IPPROTO_DCCP:      return "DCCP";
125         }
126         return "UNKNOWN PROTOCOL";
127 }
128
129 /**
130  * Resolve IPv4/IPv6 address and create a ready-to-use active or passive socket.
131  *
132  * @param l3type        The layer-3 type (\p AF_INET, \p AF_INET6, \p AF_UNSPEC)
133  * @param l4type        The layer-4 type (\p IPPROTO_xxx).
134  * @param passive       Whether this is a passive (1) or active (0) socket/
135  * @param host          Remote or local hostname or IPv/6 address string.
136  * @param port_number   Decimal port number.
137  *
138  * This creates a ready-made IPv4/v6 socket structure after looking up the necessary
139  * parameters. The interpretation of \a host depends on the value of \a passive:
140  *   - on a passive socket host is interpreted as an interface IPv4/6 address
141  *     (can be left NULL);
142  *   - on an active socket, \a host is the peer DNS name or IPv4/6 address to connect to;
143  *   - \a port_number is in either case the numeric port number (not service string).
144  * Furthermore, bind(2) is called on passive sockets, and connect(2) on active sockets.
145  * The algorithm tries all possible address combinations until it succeeds.
146  *
147  * \return This function returns 1 on success and \a -E_ADDRESS_LOOKUP when no matching
148  * connection could be set up (with details in the error log).
149  *
150  *  \sa ipv6(7), getaddrinfo(3), bind(2), connect(2)
151  */
152 int makesock(unsigned l3type, unsigned l4type, int passive,
153              const char *host, unsigned short port_number)
154 {
155         struct addrinfo *local = NULL, *src,
156                         *remote = NULL, *dst, hints;
157         char            *port = make_message("%u", port_number);
158         int             rc, on = 1, sockfd = -1,
159                         socktype = sock_type(l4type);
160
161         /*
162          *      Set up address hint structure
163          */
164         memset(&hints, 0, sizeof(hints));
165         hints.ai_family = l3type;
166         /* getaddrinfo does not really work well with SOCK_DCCP */
167         if (socktype == SOCK_DGRAM || socktype == SOCK_STREAM)
168                 hints.ai_socktype = socktype;
169
170         /* only use addresses available on the host */
171         hints.ai_flags = AI_ADDRCONFIG;
172         if (l3type == AF_INET6)
173                 /* use v4-mapped-v6 if no v6 addresses found */
174                 hints.ai_flags |= AI_V4MAPPED | AI_ALL;
175
176         if (passive && host == NULL)
177                 hints.ai_flags |= AI_PASSIVE;
178
179         /*
180          *      Obtain local/remote address information
181          */
182         if ((rc = getaddrinfo(host, port, &hints, passive ? &local : &remote))) {
183                 PARA_ERROR_LOG("can not resolve %s address %s#%s: %s.\n",
184                                 layer4_name(l4type),
185                                 host?  : (passive? "[loopback]" : "[localhost]"),
186                                 port, gai_strerror(rc));
187                 return -E_ADDRESS_LOOKUP;
188         }
189
190         /*
191          *      Iterate over all src/dst combination, exhausting dst first
192          */
193         for (src = local, dst = remote; src != NULL || dst != NULL; /* no op */ ) {
194                 if (src && dst && src->ai_family == AF_INET
195                                && dst->ai_family == AF_INET6)   /* v4 -> v6 is not possible */
196                         goto get_next_dst;
197
198                 sockfd = socket(src ? src->ai_family : dst->ai_family, socktype, l4type);
199                 if (sockfd < 0)
200                         goto get_next_dst;
201
202                 /*
203                  * Set those options that need to be set before establishing the connection
204                  */
205                 /* Reuse the address on passive (listening) sockets to avoid failure on restart */
206                 if (passive && setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
207                         PARA_ERROR_LOG("can not set SO_REUSEADDR: %s\n", strerror(errno));
208                         return -ERRNO_TO_PARA_ERROR(errno);
209                 }
210
211                 if (src) {
212                         if (bind(sockfd, src->ai_addr, src->ai_addrlen) < 0) {
213                                 close(sockfd);
214                                 goto get_next_src;
215                         }
216                         if (!dst)
217                                 break;  /* bind-only completed successfully */
218                 }
219
220                 if (dst && connect(sockfd, dst->ai_addr, dst->ai_addrlen) == 0)
221                         break;          /* connection completed successfully */
222                 close(sockfd);
223 get_next_dst:
224                 if (dst && (dst = dst->ai_next))
225                         continue;
226 get_next_src:
227                 if (src && (src = src->ai_next))
228                         dst = remote;   /* restart inner loop */
229         }
230         if (local)
231                 freeaddrinfo(local);
232         if (remote)
233                 freeaddrinfo(remote);
234
235         if (src == NULL && dst == NULL) {
236                 PARA_ERROR_LOG("can not create %s socket %s#%s.\n", layer4_name(l4type),
237                                 host?  : (passive? "[loopback]" : "[localhost]"), port);
238                 return -ERRNO_TO_PARA_ERROR(errno);
239         }
240         return sockfd;
241 }
242
243 /**
244  * Create a passive / listening socket.
245  * \param l3type        The network-layer type (\p AF_xxx)
246  * \param l4type        The transport-layer type (\p IPPROTO_xxx).
247  * \param port          The decimal port number to listen on.
248  *
249  * \return Positive integer (socket descriptor) on success, negative value otherwise.
250  * \sa makesock(), ip(7), ipv6(7), bind(2), listen(2).
251  */
252 int para_listen(unsigned l3type, unsigned l4type, unsigned short port)
253 {
254         int ret, fd = makesock(l3type, l4type, 1, NULL, port);
255
256         if (fd > 0) {
257                 ret = listen(fd, BACKLOG);
258                 if (ret < 0) {
259                         close(fd);
260                         return -ERRNO_TO_PARA_ERROR(errno);
261                 }
262                 PARA_INFO_LOG("listening on %s port %u, fd %d\n",
263                               layer4_name(l4type), port, fd);
264         }
265         return fd;
266 }
267
268 /**
269  * Print numeric host and port number (beware - uses static char).
270  * \param sa    The IPv4/IPv6 socket address to use.
271  * \param len   The length of \p sa.
272  *
273  * \sa getnameinfo(3)
274  */
275 char *host_and_port(struct sockaddr *sa, socklen_t len)
276 {
277         static char     output[NI_MAXHOST + NI_MAXSERV + 2];
278         char            hbuf[NI_MAXHOST],
279                         sbuf[NI_MAXSERV];
280         int             ret;
281
282         ret = getnameinfo(sa, len, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
283                           NI_NUMERICHOST | NI_NUMERICSERV);
284         if (ret)        {
285                 PARA_WARNING_LOG("hostname lookup error (%s).\n", gai_strerror(ret));
286                 sprintf(output, "(unknown)");
287         } else {
288                 sprintf(output, "%s#%s", hbuf, sbuf);
289         }
290         return output;
291 }
292
293 /**
294  * Look up the local or remote side of a connected socket structure.
295  * \param fd            The socket descriptor of the connected socket.
296  * \param getname       Either \fn getsockname() for local, or \fn getpeername() for remote side.
297  *
298  * \return A static character string identifying hostname and port of the chosen side
299  * \sa getsockname(2), getpeername(2)
300  */
301 static char *__get_sock_name(int fd, int (*getname)(int, struct sockaddr*, socklen_t *))
302 {
303         struct sockaddr_storage   ss;
304         socklen_t                 sslen = sizeof(ss);
305
306         if (getname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
307                 static char *dont_know = "(don't know)";
308                 PARA_ERROR_LOG("can not determine address from fd %d: %s\n", fd, strerror(errno));
309                 return dont_know;
310         }
311
312         return host_and_port((struct sockaddr *)&ss, sslen);
313 }
314
315 char  *local_name(int sockfd)
316 {
317         return __get_sock_name(sockfd, getsockname);
318 }
319
320 char *remote_name(int sockfd)
321 {
322         return __get_sock_name(sockfd, getpeername);
323 }
324
325 /*
326  * Send out a buffer, resend on short writes.
327  *
328  * \param fd The file descriptor.
329  * \param buf The buffer to be sent.
330  * \param len The length of \a buf.
331  *
332  * \return Standard. In any case, the number of bytes actually sent is stored
333  * in \a len.
334  */
335 static int sendall(int fd, const char *buf, size_t *len)
336 {
337         size_t total = *len;
338
339         assert(total);
340         *len = 0;
341         while (*len < total) {
342                 int ret = send(fd, buf + *len, total - *len, 0);
343                 if (ret == -1)
344                         return -ERRNO_TO_PARA_ERROR(errno);
345                 *len += ret;
346         }
347         return 1;
348 }
349
350 /**
351  * Encrypt and send a binary buffer.
352  *
353  * \param fd The file descriptor.
354  * \param buf The buffer to be encrypted and sent.
355  * \param len The length of \a buf.
356  *
357  * Check if encryption is available. If yes, encrypt the given buffer.  Send
358  * out the buffer, encrypted or not, and try to resend the remaing part in case
359  * of short writes.
360  *
361  * \return Standard.
362  */
363 int send_bin_buffer(int fd, const char *buf, size_t len)
364 {
365         int ret;
366         crypt_function *cf = NULL;
367
368         if (!len)
369                 PARA_CRIT_LOG("%s", "len == 0\n");
370         if (fd + 1 <= cda_size)
371                 cf = crypt_data_array[fd].send;
372         if (cf) {
373                 void *private = crypt_data_array[fd].private_data;
374                 /* RC4 may write more than len to the output buffer */
375                 unsigned char *outbuf = para_malloc(ROUND_UP(len, 8));
376                 (*cf)(len, (unsigned char *)buf, outbuf, private);
377                 ret = sendall(fd, (char *)outbuf, &len);
378                 free(outbuf);
379         } else
380                 ret = sendall(fd, buf, &len);
381         return ret;
382 }
383
384 /**
385  * Encrypt and send null terminated buffer.
386  *
387  * \param fd The file descriptor.
388  * \param buf The null-terminated buffer to be send.
389  *
390  * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
391  *
392  * \return Standard.
393  */
394 int send_buffer(int fd, const char *buf)
395 {
396         return send_bin_buffer(fd, buf, strlen(buf));
397 }
398
399
400 /**
401  * Send and encrypt a buffer given by a format string.
402  *
403  * \param fd The file descriptor.
404  * \param fmt A format string.
405  *
406  * \return Standard.
407  */
408 __printf_2_3 int send_va_buffer(int fd, const char *fmt, ...)
409 {
410         char *msg;
411         int ret;
412
413         PARA_VSPRINTF(fmt, msg);
414         ret = send_buffer(fd, msg);
415         free(msg);
416         return ret;
417 }
418
419 /**
420  * Receive and decrypt.
421  *
422  * \param fd The file descriptor.
423  * \param buf The buffer to write the decrypted data to.
424  * \param size The size of \a buf.
425  *
426  * Receive at most \a size bytes from file descriptor \a fd. If encryption is
427  * available, decrypt the received buffer.
428  *
429  * \return The number of bytes received on success, negative on errors.
430  *
431  * \sa recv(2)
432  */
433 __must_check int recv_bin_buffer(int fd, char *buf, size_t size)
434 {
435         ssize_t n;
436         crypt_function *cf = NULL;
437
438         if (fd + 1 <= cda_size)
439                 cf = crypt_data_array[fd].recv;
440         if (cf) {
441                 unsigned char *tmp = para_malloc(size);
442                 void *private = crypt_data_array[fd].private_data;
443                 n = recv(fd, tmp, size, 0);
444                 if (n > 0) {
445                         size_t numbytes = n;
446                         unsigned char *b = (unsigned char *)buf;
447                         (*cf)(numbytes, tmp, b, private);
448                 }
449                 free(tmp);
450         } else
451                 n = recv(fd, buf, size, 0);
452         if (n == -1)
453                 return -ERRNO_TO_PARA_ERROR(errno);
454         return n;
455 }
456
457 /**
458  * Receive, decrypt and write terminating NULL byte.
459  *
460  * \param fd The file descriptor.
461  * \param buf The buffer to write the decrypted data to.
462  * \param size The size of \a buf.
463  *
464  * Read and decrypt at most \a size - 1 bytes from file descriptor \a fd and
465  * write a NULL byte at the end of the received data.
466  *
467  * \return The return value of the underlying call to \a recv_bin_buffer().
468  *
469  * \sa recv_bin_buffer()
470  */
471 int recv_buffer(int fd, char *buf, size_t size)
472 {
473         int n;
474
475         assert(size);
476         n = recv_bin_buffer(fd, buf, size - 1);
477         if (n >= 0)
478                 buf[n] = '\0';
479         else
480                 *buf = '\0';
481         return n;
482 }
483
484 /**
485  * Establish a tcp connection.
486  *
487  * \param host Hostname or IPv4 address.
488  * \param port The tcp port.
489  *
490  * \return Negative on errors, a valid file descriptor on success.
491  */
492 int tcp_connect(char *host, int port)
493 {
494         struct sockaddr_in addr;
495         struct hostent *he;
496         int ret, fd;
497
498         PARA_INFO_LOG("getting host info of %s\n", host);
499         /* FIXME: gethostbyname() is obsolete */
500         he = gethostbyname(host);
501         if (!he)
502                 return -ERRNO_TO_PARA_ERROR(h_errno);
503         init_sockaddr(&addr, port, he);
504         ret = get_stream_socket(AF_INET);
505         if (ret < 0)
506                 return ret;
507         fd = ret;
508         ret = PARA_CONNECT(fd, &addr);
509         if (ret >= 0)
510                 return fd;
511         close(fd);
512         return ret;
513 }
514
515 /**
516  * A wrapper around socket(2).
517  *
518  * \param domain The communication domain that selects the protocol family.
519  *
520  * Create an IPv4 socket for sequenced, reliable, two-way, connection-based
521  * byte streams.
522  *
523  * \return The socket fd on success, negative on errors.
524  *
525  * \sa socket(2).
526  */
527 int get_stream_socket(int domain)
528 {
529         int fd = socket(domain, SOCK_STREAM, 0);
530
531         if (fd < 0)
532                 return -ERRNO_TO_PARA_ERROR(errno);
533         return fd;
534 }
535
536 /**
537  * Wrapper around the accept system call.
538  *
539  * \param fd The listening socket.
540  * \param addr Structure which is filled in with the address of the peer socket.
541  * \param size Should contain the size of the structure pointed to by \a addr.
542  *
543  * Accept incoming connections on \a addr. Retry if interrupted.
544  *
545  * \return The new file descriptor on success, negative on errors.
546  *
547  * \sa accept(2).
548  */
549 int para_accept(int fd, void *addr, socklen_t size)
550 {
551         int new_fd;
552
553         do
554                 new_fd = accept(fd, (struct sockaddr *) addr, &size);
555         while (new_fd < 0 && errno == EINTR);
556         return new_fd < 0? -ERRNO_TO_PARA_ERROR(errno) : new_fd;
557 }
558
559 /**
560  * prepare a structure for \p AF_UNIX socket addresses
561  *
562  * \param u pointer to the struct to be prepared
563  * \param name the socket pathname
564  *
565  * This just copies \a name to the sun_path component of \a u.
566  *
567  * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
568  * than \p UNIX_PATH_MAX.
569  */
570 int init_unix_addr(struct sockaddr_un *u, const char *name)
571 {
572         if (strlen(name) >= UNIX_PATH_MAX)
573                 return -E_NAME_TOO_LONG;
574         memset(u->sun_path, 0, UNIX_PATH_MAX);
575         u->sun_family = PF_UNIX;
576         strcpy(u->sun_path, name);
577         return 1;
578 }
579
580 /**
581  * Prepare, create, and bind a socket for local communication.
582  *
583  * \param name The socket pathname.
584  * \param unix_addr Pointer to the \p AF_UNIX socket structure.
585  * \param mode The desired mode of the socket.
586  *
587  * This functions creates a local socket for sequenced, reliable,
588  * two-way, connection-based byte streams.
589  *
590  * \return The file descriptor, on success, negative on errors.
591  *
592  * \sa socket(2)
593  * \sa bind(2)
594  * \sa chmod(2)
595  */
596 int create_local_socket(const char *name, struct sockaddr_un *unix_addr,
597                 mode_t mode)
598 {
599         int fd, ret;
600
601         ret = init_unix_addr(unix_addr, name);
602         if (ret < 0)
603                 return ret;
604         ret = socket(PF_UNIX, SOCK_STREAM, 0);
605         if (ret < 0)
606                 return -ERRNO_TO_PARA_ERROR(errno);
607         fd = ret;
608         ret = bind(fd, (struct sockaddr *) unix_addr, UNIX_PATH_MAX);
609         if (ret < 0) {
610                 ret = -ERRNO_TO_PARA_ERROR(errno);
611                 goto err;
612         }
613         ret = -E_CHMOD;
614         if (chmod(name, mode) < 0)
615                 goto err;
616         return fd;
617 err:
618         close(fd);
619         return ret;
620 }
621
622 #ifndef HAVE_UCRED
623 ssize_t send_cred_buffer(int sock, char *buf)
624 {
625         return send_buffer(sock, buf);
626 }
627 int recv_cred_buffer(int fd, char *buf, size_t size)
628 {
629         return recv_buffer(fd, buf, size) > 0? 1 : -E_RECVMSG;
630 }
631 #else /* HAVE_UCRED */
632 /**
633  * send NULL terminated buffer and Unix credentials of the current process
634  *
635  * \param sock the socket file descriptor
636  * \param buf the buffer to be sent
637  *
638  * \return On success, this call returns the number of characters sent.  On
639  * error, \p -E_SENDMSG is returned.
640  *
641  * \sa  okir's Black Hats Manual
642  * \sa sendmsg(2)
643  */
644 ssize_t send_cred_buffer(int sock, char *buf)
645 {
646         char control[sizeof(struct cmsghdr) + 10];
647         struct msghdr msg;
648         struct cmsghdr *cmsg;
649         static struct iovec iov;
650         struct ucred c;
651         int ret;
652
653         /* Response data */
654         iov.iov_base = buf;
655         iov.iov_len  = strlen(buf);
656         c.pid = getpid();
657         c.uid = getuid();
658         c.gid = getgid();
659         /* compose the message */
660         memset(&msg, 0, sizeof(msg));
661         msg.msg_iov = &iov;
662         msg.msg_iovlen = 1;
663         msg.msg_control = control;
664         msg.msg_controllen = sizeof(control);
665         /* attach the ucred struct */
666         cmsg = CMSG_FIRSTHDR(&msg);
667         cmsg->cmsg_level = SOL_SOCKET;
668         cmsg->cmsg_type = SCM_CREDENTIALS;
669         cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
670         *(struct ucred *)CMSG_DATA(cmsg) = c;
671         msg.msg_controllen = cmsg->cmsg_len;
672         ret = sendmsg(sock, &msg, 0);
673         if (ret  < 0)
674                 ret = -E_SENDMSG;
675         return ret;
676 }
677
678 static void dispose_fds(int *fds, unsigned num)
679 {
680         int i;
681
682         for (i = 0; i < num; i++)
683                 close(fds[i]);
684 }
685
686 /**
687  * receive a buffer and the Unix credentials of the sending process
688  *
689  * \param fd the socket file descriptor
690  * \param buf the buffer to store the message
691  * \param size the size of \a buffer
692  *
693  * \return negative on errors, the user id on success.
694  *
695  * \sa okir's Black Hats Manual
696  * \sa recvmsg(2)
697  */
698 int recv_cred_buffer(int fd, char *buf, size_t size)
699 {
700         char control[255];
701         struct msghdr msg;
702         struct cmsghdr *cmsg;
703         struct iovec iov;
704         int result = 0;
705         int yes = 1;
706         struct ucred cred;
707
708         setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &yes, sizeof(int));
709         memset(&msg, 0, sizeof(msg));
710         memset(buf, 0, size);
711         iov.iov_base = buf;
712         iov.iov_len = size;
713         msg.msg_iov = &iov;
714         msg.msg_iovlen = 1;
715         msg.msg_control = control;
716         msg.msg_controllen = sizeof(control);
717         if (recvmsg(fd, &msg, 0) < 0)
718                 return -E_RECVMSG;
719         result = -E_SCM_CREDENTIALS;
720         cmsg = CMSG_FIRSTHDR(&msg);
721         while (cmsg) {
722                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type
723                                 == SCM_CREDENTIALS) {
724                         memcpy(&cred, CMSG_DATA(cmsg), sizeof(struct ucred));
725                         result = cred.uid;
726                 } else
727                         if (cmsg->cmsg_level == SOL_SOCKET
728                                         && cmsg->cmsg_type == SCM_RIGHTS) {
729                                 dispose_fds((int *) CMSG_DATA(cmsg),
730                                         (cmsg->cmsg_len - CMSG_LEN(0))
731                                         / sizeof(int));
732                         }
733                 cmsg = CMSG_NXTHDR(&msg, cmsg);
734         }
735         return result;
736 }
737 #endif /* HAVE_UCRED */
738
739 /**
740  * Create a tcp socket, bind it and listen on the given port.
741  *
742  * \param port The tcp port to listen on.
743  *
744  * \return The file descriptor of the created socket, negative on errors.
745  *
746  * \sa get_stream_socket()
747  * \sa setsockopt(2)
748  * \sa bind(2)
749  * \sa listen(2)
750  */
751 int tcp_listen(int port)
752 {
753         struct sockaddr_in my_addr;
754         int fd, ret = get_stream_socket(AF_INET);
755
756         if (ret < 0)
757                 return ret;
758         fd = ret;
759         ret = 1;
760         ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &ret, sizeof(int));
761         if (ret < 0) {
762                 ret = -ERRNO_TO_PARA_ERROR(errno);
763                 goto err;
764         }
765         init_sockaddr(&my_addr, port, NULL);
766         ret = bind(fd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
767         if (ret < 0) {
768                 ret = -ERRNO_TO_PARA_ERROR(errno);
769                 goto err;
770         }
771         ret = listen(fd, BACKLOG);
772         if (ret < 0) {
773                 ret = -ERRNO_TO_PARA_ERROR(errno);
774                 goto err;
775         }
776         PARA_INFO_LOG("listening on port %d, fd %d\n", port, fd);
777         return fd;
778 err:
779         close(fd);
780         return ret;
781 }
782
783 /**
784  * receive a buffer and check for a pattern
785  *
786  * \param fd the file descriptor to receive from
787  * \param pattern the expected pattern
788  * \param bufsize the size of the internal buffer
789  *
790  * \return Positive if \a pattern was received, negative otherwise.
791  *
792  * This function creates a buffer of size \a bufsize and tries
793  * to receive at most \a bufsize bytes from file descriptor \a fd.
794  * If at least \p strlen(\a pattern) bytes were received, the beginning of
795  * the received buffer is compared with \a pattern, ignoring case.
796  *
797  * \sa recv_buffer()
798  * \sa strncasecmp(3)
799  */
800 int recv_pattern(int fd, const char *pattern, size_t bufsize)
801 {
802         size_t len = strlen(pattern);
803         char *buf = para_malloc(bufsize + 1);
804         int ret = -E_RECV_PATTERN, n = recv_buffer(fd, buf, bufsize);
805
806         if (n < len)
807                 goto out;
808         if (strncasecmp(buf, pattern, len))
809                 goto out;
810         ret = 1;
811 out:
812         if (ret < 0) {
813                 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n, pattern);
814                 if (n > 0)
815                         PARA_NOTICE_LOG("recvd: %s\n", buf);
816         }
817         free(buf);
818         return ret;
819 }