swrap: Rename swrap_packet_init().
[sfrench/samba-autobuild/.git] / lib / socket_wrapper / socket_wrapper.c
1 /*
2  * Copyright (C) Jelmer Vernooij 2005,2008 <jelmer@samba.org>
3  * Copyright (C) Stefan Metzmacher 2006-2009 <metze@samba.org>
4  * Copyright (C) Andreas Schneider 2013 <asn@samba.org>
5  *
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * 3. Neither the name of the author nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  */
36
37 /*
38    Socket wrapper library. Passes all socket communication over
39    unix domain sockets if the environment variable SOCKET_WRAPPER_DIR
40    is set.
41 */
42
43 #include "config.h"
44
45 #include <sys/types.h>
46 #include <sys/time.h>
47 #include <sys/stat.h>
48 #include <sys/socket.h>
49 #include <sys/ioctl.h>
50 #ifdef HAVE_SYS_FILIO_H
51 #include <sys/filio.h>
52 #endif
53 #ifdef HAVE_SYS_SIGNALFD_H
54 #include <sys/signalfd.h>
55 #endif
56 #ifdef HAVE_SYS_EVENTFD_H
57 #include <sys/eventfd.h>
58 #endif
59 #ifdef HAVE_SYS_TIMERFD_H
60 #include <sys/timerfd.h>
61 #endif
62 #include <sys/uio.h>
63 #include <errno.h>
64 #include <sys/un.h>
65 #include <netinet/in.h>
66 #include <netinet/tcp.h>
67 #include <arpa/inet.h>
68 #include <fcntl.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <stdio.h>
72 #include <stdint.h>
73 #include <stdarg.h>
74 #include <stdbool.h>
75 #include <unistd.h>
76 #ifdef HAVE_GNU_LIB_NAMES_H
77 #include <gnu/lib-names.h>
78 #endif
79 #ifdef HAVE_RPC_RPC_H
80 #include <rpc/rpc.h>
81 #endif
82
83 enum swrap_dbglvl_e {
84         SWRAP_LOG_ERROR = 0,
85         SWRAP_LOG_WARN,
86         SWRAP_LOG_DEBUG,
87         SWRAP_LOG_TRACE
88 };
89
90 /* GCC have printf type attribute check. */
91 #ifdef HAVE_FUNCTION_ATTRIBUTE_FORMAT
92 #define PRINTF_ATTRIBUTE(a,b) __attribute__ ((__format__ (__printf__, a, b)))
93 #else
94 #define PRINTF_ATTRIBUTE(a,b)
95 #endif /* HAVE_FUNCTION_ATTRIBUTE_FORMAT */
96
97 #ifdef HAVE_DESTRUCTOR_ATTRIBUTE
98 #define DESTRUCTOR_ATTRIBUTE __attribute__ ((destructor))
99 #else
100 #define DESTRUCTOR_ATTRIBUTE
101 #endif
102
103 #ifdef HAVE_GCC_THREAD_LOCAL_STORAGE
104 # define SWRAP_THREAD __thread
105 #else
106 # define SWRAP_THREAD
107 #endif
108
109 #ifndef MIN
110 #define MIN(a,b) ((a)<(b)?(a):(b))
111 #endif
112
113 #ifndef ZERO_STRUCT
114 #define ZERO_STRUCT(x) memset((char *)&(x), 0, sizeof(x))
115 #endif
116
117 #ifndef ZERO_STRUCTP
118 #define ZERO_STRUCTP(x) do { \
119                 if ((x) != NULL) \
120                         memset((char *)(x), 0, sizeof(*(x))); \
121         } while(0)
122 #endif
123
124 #ifndef discard_const
125 #define discard_const(ptr) ((void *)((uintptr_t)(ptr)))
126 #endif
127
128 #ifndef discard_const_p
129 #define discard_const_p(type, ptr) ((type *)discard_const(ptr))
130 #endif
131
132 #ifdef IPV6_PKTINFO
133 # ifndef IPV6_RECVPKTINFO
134 #  define IPV6_RECVPKTINFO IPV6_PKTINFO
135 # endif /* IPV6_RECVPKTINFO */
136 #endif /* IPV6_PKTINFO */
137
138 /*
139  * On BSD IP_PKTINFO has a different name because during
140  * the time when they implemented it, there was no RFC.
141  * The name for IPv6 is the same as on Linux.
142  */
143 #ifndef IP_PKTINFO
144 # ifdef IP_RECVDSTADDR
145 #  define IP_PKTINFO IP_RECVDSTADDR
146 # endif
147 #endif
148
149
150 #define SWRAP_DLIST_ADD(list,item) do { \
151         if (!(list)) { \
152                 (item)->prev    = NULL; \
153                 (item)->next    = NULL; \
154                 (list)          = (item); \
155         } else { \
156                 (item)->prev    = NULL; \
157                 (item)->next    = (list); \
158                 (list)->prev    = (item); \
159                 (list)          = (item); \
160         } \
161 } while (0)
162
163 #define SWRAP_DLIST_REMOVE(list,item) do { \
164         if ((list) == (item)) { \
165                 (list)          = (item)->next; \
166                 if (list) { \
167                         (list)->prev    = NULL; \
168                 } \
169         } else { \
170                 if ((item)->prev) { \
171                         (item)->prev->next      = (item)->next; \
172                 } \
173                 if ((item)->next) { \
174                         (item)->next->prev      = (item)->prev; \
175                 } \
176         } \
177         (item)->prev    = NULL; \
178         (item)->next    = NULL; \
179 } while (0)
180
181 #if defined(HAVE_GETTIMEOFDAY_TZ) || defined(HAVE_GETTIMEOFDAY_TZ_VOID)
182 #define swrapGetTimeOfDay(tval) gettimeofday(tval,NULL)
183 #else
184 #define swrapGetTimeOfDay(tval) gettimeofday(tval)
185 #endif
186
187 /* we need to use a very terse format here as IRIX 6.4 silently
188    truncates names to 16 chars, so if we use a longer name then we
189    can't tell which port a packet came from with recvfrom()
190
191    with this format we have 8 chars left for the directory name
192 */
193 #define SOCKET_FORMAT "%c%02X%04X"
194 #define SOCKET_TYPE_CHAR_TCP            'T'
195 #define SOCKET_TYPE_CHAR_UDP            'U'
196 #define SOCKET_TYPE_CHAR_TCP_V6         'X'
197 #define SOCKET_TYPE_CHAR_UDP_V6         'Y'
198
199 /*
200  * Cut down to 1500 byte packets for stream sockets,
201  * which makes it easier to format PCAP capture files
202  * (as the caller will simply continue from here)
203  */
204 #define SOCKET_MAX_PACKET 1500
205
206 #define SOCKET_MAX_SOCKETS 1024
207
208 /* This limit is to avoid broadcast sendto() needing to stat too many
209  * files.  It may be raised (with a performance cost) to up to 254
210  * without changing the format above */
211 #define MAX_WRAPPED_INTERFACES 40
212
213 struct swrap_address {
214         socklen_t sa_socklen;
215         union {
216                 struct sockaddr s;
217                 struct sockaddr_in in;
218 #ifdef HAVE_IPV6
219                 struct sockaddr_in6 in6;
220 #endif
221                 struct sockaddr_un un;
222                 struct sockaddr_storage ss;
223         } sa;
224 };
225
226 struct socket_info_fd {
227         struct socket_info_fd *prev, *next;
228         int fd;
229 };
230
231 struct socket_info
232 {
233         struct socket_info_fd *fds;
234
235         int family;
236         int type;
237         int protocol;
238         int bound;
239         int bcast;
240         int is_server;
241         int connected;
242         int defer_connect;
243         int pktinfo;
244
245         char *tmp_path;
246
247         struct sockaddr *bindname;
248         socklen_t bindname_len;
249
250         struct sockaddr *myname;
251         socklen_t myname_len;
252
253         struct sockaddr *peername;
254         socklen_t peername_len;
255
256         struct {
257                 unsigned long pck_snd;
258                 unsigned long pck_rcv;
259         } io;
260
261         struct socket_info *prev, *next;
262 };
263
264 /*
265  * File descriptors are shared between threads so we should share socket
266  * information too.
267  */
268 struct socket_info *sockets;
269
270 /* Function prototypes */
271
272 bool socket_wrapper_enabled(void);
273 void swrap_destructor(void) DESTRUCTOR_ATTRIBUTE;
274
275 #ifdef NDEBUG
276 # define SWRAP_LOG(...)
277 #else
278
279 static void swrap_log(enum swrap_dbglvl_e dbglvl, const char *format, ...) PRINTF_ATTRIBUTE(2, 3);
280 # define SWRAP_LOG(dbglvl, ...) swrap_log((dbglvl), __VA_ARGS__)
281
282 static void swrap_log(enum swrap_dbglvl_e dbglvl, const char *format, ...)
283 {
284         char buffer[1024];
285         va_list va;
286         const char *d;
287         unsigned int lvl = 0;
288
289         d = getenv("SOCKET_WRAPPER_DEBUGLEVEL");
290         if (d != NULL) {
291                 lvl = atoi(d);
292         }
293
294         va_start(va, format);
295         vsnprintf(buffer, sizeof(buffer), format, va);
296         va_end(va);
297
298         if (lvl >= dbglvl) {
299                 switch (dbglvl) {
300                         case SWRAP_LOG_ERROR:
301                                 fprintf(stderr,
302                                         "SWRAP_ERROR(%d): %s\n",
303                                         (int)getpid(), buffer);
304                                 break;
305                         case SWRAP_LOG_WARN:
306                                 fprintf(stderr,
307                                         "SWRAP_WARN(%d): %s\n",
308                                         (int)getpid(), buffer);
309                                 break;
310                         case SWRAP_LOG_DEBUG:
311                                 fprintf(stderr,
312                                         "SWRAP_DEBUG(%d): %s\n",
313                                         (int)getpid(), buffer);
314                                 break;
315                         case SWRAP_LOG_TRACE:
316                                 fprintf(stderr,
317                                         "SWRAP_TRACE(%d): %s\n",
318                                         (int)getpid(), buffer);
319                                 break;
320                 }
321         }
322 }
323 #endif
324
325 /*********************************************************
326  * SWRAP LOADING LIBC FUNCTIONS
327  *********************************************************/
328
329 #include <dlfcn.h>
330
331 struct swrap_libc_fns {
332         int (*libc_accept)(int sockfd,
333                            struct sockaddr *addr,
334                            socklen_t *addrlen);
335         int (*libc_bind)(int sockfd,
336                          const struct sockaddr *addr,
337                          socklen_t addrlen);
338         int (*libc_close)(int fd);
339         int (*libc_connect)(int sockfd,
340                             const struct sockaddr *addr,
341                             socklen_t addrlen);
342         int (*libc_dup)(int fd);
343         int (*libc_dup2)(int oldfd, int newfd);
344 #ifdef HAVE_EVENTFD
345         int (*libc_eventfd)(int count, int flags);
346 #endif
347         int (*libc_getpeername)(int sockfd,
348                                 struct sockaddr *addr,
349                                 socklen_t *addrlen);
350         int (*libc_getsockname)(int sockfd,
351                                 struct sockaddr *addr,
352                                 socklen_t *addrlen);
353         int (*libc_getsockopt)(int sockfd,
354                                int level,
355                                int optname,
356                                void *optval,
357                                socklen_t *optlen);
358         int (*libc_ioctl)(int d, unsigned long int request, ...);
359         int (*libc_listen)(int sockfd, int backlog);
360         int (*libc_open)(const char *pathname, int flags, mode_t mode);
361         int (*libc_pipe)(int pipefd[2]);
362         int (*libc_read)(int fd, void *buf, size_t count);
363         ssize_t (*libc_readv)(int fd, const struct iovec *iov, int iovcnt);
364         int (*libc_recv)(int sockfd, void *buf, size_t len, int flags);
365         int (*libc_recvfrom)(int sockfd,
366                              void *buf,
367                              size_t len,
368                              int flags,
369                              struct sockaddr *src_addr,
370                              socklen_t *addrlen);
371         int (*libc_recvmsg)(int sockfd, const struct msghdr *msg, int flags);
372         int (*libc_send)(int sockfd, const void *buf, size_t len, int flags);
373         int (*libc_sendmsg)(int sockfd, const struct msghdr *msg, int flags);
374         int (*libc_sendto)(int sockfd,
375                            const void *buf,
376                            size_t len,
377                            int flags,
378                            const  struct sockaddr *dst_addr,
379                            socklen_t addrlen);
380         int (*libc_setsockopt)(int sockfd,
381                                int level,
382                                int optname,
383                                const void *optval,
384                                socklen_t optlen);
385 #ifdef HAVE_SIGNALFD
386         int (*libc_signalfd)(int fd, const sigset_t *mask, int flags);
387 #endif
388         int (*libc_socket)(int domain, int type, int protocol);
389         int (*libc_socketpair)(int domain, int type, int protocol, int sv[2]);
390 #ifdef HAVE_TIMERFD_CREATE
391         int (*libc_timerfd_create)(int clockid, int flags);
392 #endif
393         ssize_t (*libc_writev)(int fd, const struct iovec *iov, int iovcnt);
394 };
395
396 struct swrap {
397         void *libc_handle;
398         void *libsocket_handle;
399
400         bool initialised;
401         bool enabled;
402
403         char *socket_dir;
404
405         struct swrap_libc_fns fns;
406 };
407
408 static struct swrap swrap;
409
410 /* prototypes */
411 static const char *socket_wrapper_dir(void);
412
413 #define LIBC_NAME "libc.so"
414
415 enum swrap_lib {
416     SWRAP_LIBC,
417     SWRAP_LIBNSL,
418     SWRAP_LIBSOCKET,
419 };
420
421 #ifndef NDEBUG
422 static const char *swrap_str_lib(enum swrap_lib lib)
423 {
424         switch (lib) {
425         case SWRAP_LIBC:
426                 return "libc";
427         case SWRAP_LIBNSL:
428                 return "libnsl";
429         case SWRAP_LIBSOCKET:
430                 return "libsocket";
431         }
432
433         /* Compiler would warn us about unhandled enum value if we get here */
434         return "unknown";
435 }
436 #endif
437
438 static void *swrap_load_lib_handle(enum swrap_lib lib)
439 {
440         int flags = RTLD_LAZY;
441         void *handle = NULL;
442         int i;
443
444 #ifdef RTLD_DEEPBIND
445         flags |= RTLD_DEEPBIND;
446 #endif
447
448         switch (lib) {
449         case SWRAP_LIBNSL:
450                 /* FALL TROUGH */
451         case SWRAP_LIBSOCKET:
452 #ifdef HAVE_LIBSOCKET
453                 handle = swrap.libsocket_handle;
454                 if (handle == NULL) {
455                         for (handle = NULL, i = 10; handle == NULL && i >= 0; i--) {
456                                 char soname[256] = {0};
457
458                                 snprintf(soname, sizeof(soname), "libsocket.so.%d", i);
459                                 handle = dlopen(soname, flags);
460                         }
461
462                         swrap.libsocket_handle = handle;
463                 }
464                 break;
465 #endif
466                 /* FALL TROUGH */
467         case SWRAP_LIBC:
468                 handle = swrap.libc_handle;
469 #ifdef LIBC_SO
470                 if (handle == NULL) {
471                         handle = dlopen(LIBC_SO, flags);
472
473                         swrap.libc_handle = handle;
474                 }
475 #endif
476                 if (handle == NULL) {
477                         for (handle = NULL, i = 10; handle == NULL && i >= 0; i--) {
478                                 char soname[256] = {0};
479
480                                 snprintf(soname, sizeof(soname), "libc.so.%d", i);
481                                 handle = dlopen(soname, flags);
482                         }
483
484                         swrap.libc_handle = handle;
485                 }
486                 break;
487         }
488
489         if (handle == NULL) {
490 #ifdef RTLD_NEXT
491                 handle = swrap.libc_handle = swrap.libsocket_handle = RTLD_NEXT;
492 #else
493                 SWRAP_LOG(SWRAP_LOG_ERROR,
494                           "Failed to dlopen library: %s\n",
495                           dlerror());
496                 exit(-1);
497 #endif
498         }
499
500         return handle;
501 }
502
503 static void *_swrap_load_lib_function(enum swrap_lib lib, const char *fn_name)
504 {
505         void *handle;
506         void *func;
507
508         handle = swrap_load_lib_handle(lib);
509
510         func = dlsym(handle, fn_name);
511         if (func == NULL) {
512                 SWRAP_LOG(SWRAP_LOG_ERROR,
513                                 "Failed to find %s: %s\n",
514                                 fn_name, dlerror());
515                 exit(-1);
516         }
517
518         SWRAP_LOG(SWRAP_LOG_TRACE,
519                         "Loaded %s from %s",
520                         fn_name, swrap_str_lib(lib));
521         return func;
522 }
523
524 #define swrap_load_lib_function(lib, fn_name) \
525         if (swrap.fns.libc_##fn_name == NULL) { \
526                 *(void **) (&swrap.fns.libc_##fn_name) = \
527                         _swrap_load_lib_function(lib, #fn_name); \
528         }
529
530
531 /*
532  * IMPORTANT
533  *
534  * Functions especially from libc need to be loaded individually, you can't load
535  * all at once or gdb will segfault at startup. The same applies to valgrind and
536  * has probably something todo with with the linker.
537  * So we need load each function at the point it is called the first time.
538  */
539 static int libc_accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
540 {
541         swrap_load_lib_function(SWRAP_LIBSOCKET, accept);
542
543         return swrap.fns.libc_accept(sockfd, addr, addrlen);
544 }
545
546 static int libc_bind(int sockfd,
547                      const struct sockaddr *addr,
548                      socklen_t addrlen)
549 {
550         swrap_load_lib_function(SWRAP_LIBSOCKET, bind);
551
552         return swrap.fns.libc_bind(sockfd, addr, addrlen);
553 }
554
555 static int libc_close(int fd)
556 {
557         swrap_load_lib_function(SWRAP_LIBC, close);
558
559         return swrap.fns.libc_close(fd);
560 }
561
562 static int libc_connect(int sockfd,
563                         const struct sockaddr *addr,
564                         socklen_t addrlen)
565 {
566         swrap_load_lib_function(SWRAP_LIBSOCKET, connect);
567
568         return swrap.fns.libc_connect(sockfd, addr, addrlen);
569 }
570
571 static int libc_dup(int fd)
572 {
573         swrap_load_lib_function(SWRAP_LIBC, dup);
574
575         return swrap.fns.libc_dup(fd);
576 }
577
578 static int libc_dup2(int oldfd, int newfd)
579 {
580         swrap_load_lib_function(SWRAP_LIBC, dup2);
581
582         return swrap.fns.libc_dup2(oldfd, newfd);
583 }
584
585 #ifdef HAVE_EVENTFD
586 static int libc_eventfd(int count, int flags)
587 {
588         swrap_load_lib_function(SWRAP_LIBC, eventfd);
589
590         return swrap.fns.libc_eventfd(count, flags);
591 }
592 #endif
593
594 static int libc_getpeername(int sockfd,
595                             struct sockaddr *addr,
596                             socklen_t *addrlen)
597 {
598         swrap_load_lib_function(SWRAP_LIBSOCKET, getpeername);
599
600         return swrap.fns.libc_getpeername(sockfd, addr, addrlen);
601 }
602
603 static int libc_getsockname(int sockfd,
604                             struct sockaddr *addr,
605                             socklen_t *addrlen)
606 {
607         swrap_load_lib_function(SWRAP_LIBSOCKET, getsockname);
608
609         return swrap.fns.libc_getsockname(sockfd, addr, addrlen);
610 }
611
612 static int libc_getsockopt(int sockfd,
613                            int level,
614                            int optname,
615                            void *optval,
616                            socklen_t *optlen)
617 {
618         swrap_load_lib_function(SWRAP_LIBSOCKET, getsockopt);
619
620         return swrap.fns.libc_getsockopt(sockfd, level, optname, optval, optlen);
621 }
622
623 static int libc_vioctl(int d, unsigned long int request, va_list ap)
624 {
625         long int args[4];
626         int rc;
627         int i;
628
629         swrap_load_lib_function(SWRAP_LIBC, ioctl);
630
631         for (i = 0; i < 4; i++) {
632                 args[i] = va_arg(ap, long int);
633         }
634
635         rc = swrap.fns.libc_ioctl(d,
636                                   request,
637                                   args[0],
638                                   args[1],
639                                   args[2],
640                                   args[3]);
641
642         return rc;
643 }
644
645 static int libc_listen(int sockfd, int backlog)
646 {
647         swrap_load_lib_function(SWRAP_LIBSOCKET, listen);
648
649         return swrap.fns.libc_listen(sockfd, backlog);
650 }
651
652 static int libc_vopen(const char *pathname, int flags, va_list ap)
653 {
654         long int mode = 0;
655         int fd;
656
657         swrap_load_lib_function(SWRAP_LIBC, open);
658
659         mode = va_arg(ap, long int);
660
661         fd = swrap.fns.libc_open(pathname, flags, (mode_t)mode);
662
663         return fd;
664 }
665
666 static int libc_open(const char *pathname, int flags, ...)
667 {
668         va_list ap;
669         int fd;
670
671         va_start(ap, flags);
672         fd = libc_vopen(pathname, flags, ap);
673         va_end(ap);
674
675         return fd;
676 }
677
678 static int libc_pipe(int pipefd[2])
679 {
680         swrap_load_lib_function(SWRAP_LIBSOCKET, pipe);
681
682         return swrap.fns.libc_pipe(pipefd);
683 }
684
685 static int libc_read(int fd, void *buf, size_t count)
686 {
687         swrap_load_lib_function(SWRAP_LIBC, read);
688
689         return swrap.fns.libc_read(fd, buf, count);
690 }
691
692 static ssize_t libc_readv(int fd, const struct iovec *iov, int iovcnt)
693 {
694         swrap_load_lib_function(SWRAP_LIBSOCKET, readv);
695
696         return swrap.fns.libc_readv(fd, iov, iovcnt);
697 }
698
699 static int libc_recv(int sockfd, void *buf, size_t len, int flags)
700 {
701         swrap_load_lib_function(SWRAP_LIBSOCKET, recv);
702
703         return swrap.fns.libc_recv(sockfd, buf, len, flags);
704 }
705
706 static int libc_recvfrom(int sockfd,
707                          void *buf,
708                          size_t len,
709                          int flags,
710                          struct sockaddr *src_addr,
711                          socklen_t *addrlen)
712 {
713         swrap_load_lib_function(SWRAP_LIBSOCKET, recvfrom);
714
715         return swrap.fns.libc_recvfrom(sockfd, buf, len, flags, src_addr, addrlen);
716 }
717
718 static int libc_recvmsg(int sockfd, struct msghdr *msg, int flags)
719 {
720         swrap_load_lib_function(SWRAP_LIBSOCKET, recvmsg);
721
722         return swrap.fns.libc_recvmsg(sockfd, msg, flags);
723 }
724
725 static int libc_send(int sockfd, const void *buf, size_t len, int flags)
726 {
727         swrap_load_lib_function(SWRAP_LIBSOCKET, send);
728
729         return swrap.fns.libc_send(sockfd, buf, len, flags);
730 }
731
732 static int libc_sendmsg(int sockfd, const struct msghdr *msg, int flags)
733 {
734         swrap_load_lib_function(SWRAP_LIBSOCKET, sendmsg);
735
736         return swrap.fns.libc_sendmsg(sockfd, msg, flags);
737 }
738
739 static int libc_sendto(int sockfd,
740                        const void *buf,
741                        size_t len,
742                        int flags,
743                        const  struct sockaddr *dst_addr,
744                        socklen_t addrlen)
745 {
746         swrap_load_lib_function(SWRAP_LIBSOCKET, sendto);
747
748         return swrap.fns.libc_sendto(sockfd, buf, len, flags, dst_addr, addrlen);
749 }
750
751 static int libc_setsockopt(int sockfd,
752                            int level,
753                            int optname,
754                            const void *optval,
755                            socklen_t optlen)
756 {
757         swrap_load_lib_function(SWRAP_LIBSOCKET, setsockopt);
758
759         return swrap.fns.libc_setsockopt(sockfd, level, optname, optval, optlen);
760 }
761
762 #ifdef HAVE_SIGNALFD
763 static int libc_signalfd(int fd, const sigset_t *mask, int flags)
764 {
765         swrap_load_lib_function(SWRAP_LIBSOCKET, signalfd);
766
767         return swrap.fns.libc_signalfd(fd, mask, flags);
768 }
769 #endif
770
771 static int libc_socket(int domain, int type, int protocol)
772 {
773         swrap_load_lib_function(SWRAP_LIBSOCKET, socket);
774
775         return swrap.fns.libc_socket(domain, type, protocol);
776 }
777
778 static int libc_socketpair(int domain, int type, int protocol, int sv[2])
779 {
780         swrap_load_lib_function(SWRAP_LIBSOCKET, socketpair);
781
782         return swrap.fns.libc_socketpair(domain, type, protocol, sv);
783 }
784
785 #ifdef HAVE_TIMERFD_CREATE
786 static int libc_timerfd_create(int clockid, int flags)
787 {
788         swrap_load_lib_function(SWRAP_LIBC, timerfd_create);
789
790         return swrap.fns.libc_timerfd_create(clockid, flags);
791 }
792 #endif
793
794 static ssize_t libc_writev(int fd, const struct iovec *iov, int iovcnt)
795 {
796         swrap_load_lib_function(SWRAP_LIBSOCKET, writev);
797
798         return swrap.fns.libc_writev(fd, iov, iovcnt);
799 }
800
801 /*********************************************************
802  * SWRAP HELPER FUNCTIONS
803  *********************************************************/
804
805 #ifdef HAVE_IPV6
806 /*
807  * FD00::5357:5FXX
808  */
809 static const struct in6_addr *swrap_ipv6(void)
810 {
811         static struct in6_addr v;
812         static int initialized;
813         int ret;
814
815         if (initialized) {
816                 return &v;
817         }
818         initialized = 1;
819
820         ret = inet_pton(AF_INET6, "FD00::5357:5F00", &v);
821         if (ret <= 0) {
822                 abort();
823         }
824
825         return &v;
826 }
827 #endif
828
829 static struct sockaddr *sockaddr_dup(const void *data, socklen_t len)
830 {
831         struct sockaddr *ret = (struct sockaddr *)malloc(len);
832         memcpy(ret, data, len);
833         return ret;
834 }
835
836 static void set_port(int family, int prt, struct sockaddr *addr)
837 {
838         switch (family) {
839         case AF_INET:
840                 ((struct sockaddr_in *)addr)->sin_port = htons(prt);
841                 break;
842 #ifdef HAVE_IPV6
843         case AF_INET6:
844                 ((struct sockaddr_in6 *)addr)->sin6_port = htons(prt);
845                 break;
846 #endif
847         }
848 }
849
850 static size_t socket_length(int family)
851 {
852         switch (family) {
853         case AF_INET:
854                 return sizeof(struct sockaddr_in);
855 #ifdef HAVE_IPV6
856         case AF_INET6:
857                 return sizeof(struct sockaddr_in6);
858 #endif
859         }
860         return 0;
861 }
862
863 static const char *socket_wrapper_dir(void)
864 {
865         const char *s = getenv("SOCKET_WRAPPER_DIR");
866         if (s == NULL) {
867                 return NULL;
868         }
869         /* TODO use realpath(3) here, when we add support for threads */
870         if (strncmp(s, "./", 2) == 0) {
871                 s += 2;
872         }
873
874         SWRAP_LOG(SWRAP_LOG_TRACE, "socket_wrapper_dir: %s", s);
875         return s;
876 }
877
878 bool socket_wrapper_enabled(void)
879 {
880         const char *s = socket_wrapper_dir();
881
882         return s != NULL ? true : false;
883 }
884
885 static unsigned int socket_wrapper_default_iface(void)
886 {
887         const char *s = getenv("SOCKET_WRAPPER_DEFAULT_IFACE");
888         if (s) {
889                 unsigned int iface;
890                 if (sscanf(s, "%u", &iface) == 1) {
891                         if (iface >= 1 && iface <= MAX_WRAPPED_INTERFACES) {
892                                 return iface;
893                         }
894                 }
895         }
896
897         return 1;/* 127.0.0.1 */
898 }
899
900 static int convert_un_in(const struct sockaddr_un *un, struct sockaddr *in, socklen_t *len)
901 {
902         unsigned int iface;
903         unsigned int prt;
904         const char *p;
905         char type;
906
907         p = strrchr(un->sun_path, '/');
908         if (p) p++; else p = un->sun_path;
909
910         if (sscanf(p, SOCKET_FORMAT, &type, &iface, &prt) != 3) {
911                 errno = EINVAL;
912                 return -1;
913         }
914
915         SWRAP_LOG(SWRAP_LOG_TRACE, "type %c iface %u port %u",
916                         type, iface, prt);
917
918         if (iface == 0 || iface > MAX_WRAPPED_INTERFACES) {
919                 errno = EINVAL;
920                 return -1;
921         }
922
923         if (prt > 0xFFFF) {
924                 errno = EINVAL;
925                 return -1;
926         }
927
928         switch(type) {
929         case SOCKET_TYPE_CHAR_TCP:
930         case SOCKET_TYPE_CHAR_UDP: {
931                 struct sockaddr_in *in2 = (struct sockaddr_in *)(void *)in;
932
933                 if ((*len) < sizeof(*in2)) {
934                     errno = EINVAL;
935                     return -1;
936                 }
937
938                 memset(in2, 0, sizeof(*in2));
939                 in2->sin_family = AF_INET;
940                 in2->sin_addr.s_addr = htonl((127<<24) | iface);
941                 in2->sin_port = htons(prt);
942
943                 *len = sizeof(*in2);
944                 break;
945         }
946 #ifdef HAVE_IPV6
947         case SOCKET_TYPE_CHAR_TCP_V6:
948         case SOCKET_TYPE_CHAR_UDP_V6: {
949                 struct sockaddr_in6 *in2 = (struct sockaddr_in6 *)(void *)in;
950
951                 if ((*len) < sizeof(*in2)) {
952                         errno = EINVAL;
953                         return -1;
954                 }
955
956                 memset(in2, 0, sizeof(*in2));
957                 in2->sin6_family = AF_INET6;
958                 in2->sin6_addr = *swrap_ipv6();
959                 in2->sin6_addr.s6_addr[15] = iface;
960                 in2->sin6_port = htons(prt);
961
962                 *len = sizeof(*in2);
963                 break;
964         }
965 #endif
966         default:
967                 errno = EINVAL;
968                 return -1;
969         }
970
971         return 0;
972 }
973
974 static int convert_in_un_remote(struct socket_info *si, const struct sockaddr *inaddr, struct sockaddr_un *un,
975                                 int *bcast)
976 {
977         char type = '\0';
978         unsigned int prt;
979         unsigned int iface;
980         int is_bcast = 0;
981
982         if (bcast) *bcast = 0;
983
984         switch (inaddr->sa_family) {
985         case AF_INET: {
986                 const struct sockaddr_in *in = 
987                     (const struct sockaddr_in *)(const void *)inaddr;
988                 unsigned int addr = ntohl(in->sin_addr.s_addr);
989                 char u_type = '\0';
990                 char b_type = '\0';
991                 char a_type = '\0';
992
993                 switch (si->type) {
994                 case SOCK_STREAM:
995                         u_type = SOCKET_TYPE_CHAR_TCP;
996                         break;
997                 case SOCK_DGRAM:
998                         u_type = SOCKET_TYPE_CHAR_UDP;
999                         a_type = SOCKET_TYPE_CHAR_UDP;
1000                         b_type = SOCKET_TYPE_CHAR_UDP;
1001                         break;
1002                 default:
1003                         SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!\n");
1004                         errno = ESOCKTNOSUPPORT;
1005                         return -1;
1006                 }
1007
1008                 prt = ntohs(in->sin_port);
1009                 if (a_type && addr == 0xFFFFFFFF) {
1010                         /* 255.255.255.255 only udp */
1011                         is_bcast = 2;
1012                         type = a_type;
1013                         iface = socket_wrapper_default_iface();
1014                 } else if (b_type && addr == 0x7FFFFFFF) {
1015                         /* 127.255.255.255 only udp */
1016                         is_bcast = 1;
1017                         type = b_type;
1018                         iface = socket_wrapper_default_iface();
1019                 } else if ((addr & 0xFFFFFF00) == 0x7F000000) {
1020                         /* 127.0.0.X */
1021                         is_bcast = 0;
1022                         type = u_type;
1023                         iface = (addr & 0x000000FF);
1024                 } else {
1025                         errno = ENETUNREACH;
1026                         return -1;
1027                 }
1028                 if (bcast) *bcast = is_bcast;
1029                 break;
1030         }
1031 #ifdef HAVE_IPV6
1032         case AF_INET6: {
1033                 const struct sockaddr_in6 *in = 
1034                     (const struct sockaddr_in6 *)(const void *)inaddr;
1035                 struct in6_addr cmp1, cmp2;
1036
1037                 switch (si->type) {
1038                 case SOCK_STREAM:
1039                         type = SOCKET_TYPE_CHAR_TCP_V6;
1040                         break;
1041                 case SOCK_DGRAM:
1042                         type = SOCKET_TYPE_CHAR_UDP_V6;
1043                         break;
1044                 default:
1045                         SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!\n");
1046                         errno = ESOCKTNOSUPPORT;
1047                         return -1;
1048                 }
1049
1050                 /* XXX no multicast/broadcast */
1051
1052                 prt = ntohs(in->sin6_port);
1053
1054                 cmp1 = *swrap_ipv6();
1055                 cmp2 = in->sin6_addr;
1056                 cmp2.s6_addr[15] = 0;
1057                 if (IN6_ARE_ADDR_EQUAL(&cmp1, &cmp2)) {
1058                         iface = in->sin6_addr.s6_addr[15];
1059                 } else {
1060                         errno = ENETUNREACH;
1061                         return -1;
1062                 }
1063
1064                 break;
1065         }
1066 #endif
1067         default:
1068                 SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown address family!\n");
1069                 errno = ENETUNREACH;
1070                 return -1;
1071         }
1072
1073         if (prt == 0) {
1074                 SWRAP_LOG(SWRAP_LOG_WARN, "Port not set\n");
1075                 errno = EINVAL;
1076                 return -1;
1077         }
1078
1079         if (is_bcast) {
1080                 snprintf(un->sun_path, sizeof(un->sun_path), "%s/EINVAL", 
1081                          socket_wrapper_dir());
1082                 SWRAP_LOG(SWRAP_LOG_DEBUG, "un path [%s]", un->sun_path);
1083                 /* the caller need to do more processing */
1084                 return 0;
1085         }
1086
1087         snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT, 
1088                  socket_wrapper_dir(), type, iface, prt);
1089         SWRAP_LOG(SWRAP_LOG_DEBUG, "un path [%s]", un->sun_path);
1090
1091         return 0;
1092 }
1093
1094 static int convert_in_un_alloc(struct socket_info *si, const struct sockaddr *inaddr, struct sockaddr_un *un,
1095                                int *bcast)
1096 {
1097         char type = '\0';
1098         unsigned int prt;
1099         unsigned int iface;
1100         struct stat st;
1101         int is_bcast = 0;
1102
1103         if (bcast) *bcast = 0;
1104
1105         switch (si->family) {
1106         case AF_INET: {
1107                 const struct sockaddr_in *in = 
1108                     (const struct sockaddr_in *)(const void *)inaddr;
1109                 unsigned int addr = ntohl(in->sin_addr.s_addr);
1110                 char u_type = '\0';
1111                 char d_type = '\0';
1112                 char b_type = '\0';
1113                 char a_type = '\0';
1114
1115                 prt = ntohs(in->sin_port);
1116
1117                 switch (si->type) {
1118                 case SOCK_STREAM:
1119                         u_type = SOCKET_TYPE_CHAR_TCP;
1120                         d_type = SOCKET_TYPE_CHAR_TCP;
1121                         break;
1122                 case SOCK_DGRAM:
1123                         u_type = SOCKET_TYPE_CHAR_UDP;
1124                         d_type = SOCKET_TYPE_CHAR_UDP;
1125                         a_type = SOCKET_TYPE_CHAR_UDP;
1126                         b_type = SOCKET_TYPE_CHAR_UDP;
1127                         break;
1128                 default:
1129                         SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!\n");
1130                         errno = ESOCKTNOSUPPORT;
1131                         return -1;
1132                 }
1133
1134                 if (addr == 0) {
1135                         /* 0.0.0.0 */
1136                         is_bcast = 0;
1137                         type = d_type;
1138                         iface = socket_wrapper_default_iface();
1139                 } else if (a_type && addr == 0xFFFFFFFF) {
1140                         /* 255.255.255.255 only udp */
1141                         is_bcast = 2;
1142                         type = a_type;
1143                         iface = socket_wrapper_default_iface();
1144                 } else if (b_type && addr == 0x7FFFFFFF) {
1145                         /* 127.255.255.255 only udp */
1146                         is_bcast = 1;
1147                         type = b_type;
1148                         iface = socket_wrapper_default_iface();
1149                 } else if ((addr & 0xFFFFFF00) == 0x7F000000) {
1150                         /* 127.0.0.X */
1151                         is_bcast = 0;
1152                         type = u_type;
1153                         iface = (addr & 0x000000FF);
1154                 } else {
1155                         errno = EADDRNOTAVAIL;
1156                         return -1;
1157                 }
1158
1159                 /* Store the bind address for connect() */
1160                 if (si->bindname == NULL) {
1161                         struct sockaddr_in bind_in;
1162                         socklen_t blen = sizeof(struct sockaddr_in);
1163
1164                         ZERO_STRUCT(bind_in);
1165                         bind_in.sin_family = in->sin_family;
1166                         bind_in.sin_port = in->sin_port;
1167                         bind_in.sin_addr.s_addr = htonl(0x7F000000 | iface);
1168
1169                         si->bindname = sockaddr_dup(&bind_in, blen);
1170                         si->bindname_len = blen;
1171                 }
1172
1173                 break;
1174         }
1175 #ifdef HAVE_IPV6
1176         case AF_INET6: {
1177                 const struct sockaddr_in6 *in = 
1178                     (const struct sockaddr_in6 *)(const void *)inaddr;
1179                 struct in6_addr cmp1, cmp2;
1180
1181                 switch (si->type) {
1182                 case SOCK_STREAM:
1183                         type = SOCKET_TYPE_CHAR_TCP_V6;
1184                         break;
1185                 case SOCK_DGRAM:
1186                         type = SOCKET_TYPE_CHAR_UDP_V6;
1187                         break;
1188                 default:
1189                         SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!\n");
1190                         errno = ESOCKTNOSUPPORT;
1191                         return -1;
1192                 }
1193
1194                 /* XXX no multicast/broadcast */
1195
1196                 prt = ntohs(in->sin6_port);
1197
1198                 cmp1 = *swrap_ipv6();
1199                 cmp2 = in->sin6_addr;
1200                 cmp2.s6_addr[15] = 0;
1201                 if (IN6_IS_ADDR_UNSPECIFIED(&in->sin6_addr)) {
1202                         iface = socket_wrapper_default_iface();
1203                 } else if (IN6_ARE_ADDR_EQUAL(&cmp1, &cmp2)) {
1204                         iface = in->sin6_addr.s6_addr[15];
1205                 } else {
1206                         errno = EADDRNOTAVAIL;
1207                         return -1;
1208                 }
1209
1210                 /* Store the bind address for connect() */
1211                 if (si->bindname == NULL) {
1212                         struct sockaddr_in6 bind_in;
1213                         socklen_t blen = sizeof(struct sockaddr_in6);
1214
1215                         ZERO_STRUCT(bind_in);
1216                         bind_in.sin6_family = in->sin6_family;
1217                         bind_in.sin6_port = in->sin6_port;
1218
1219                         bind_in.sin6_addr = *swrap_ipv6();
1220                         bind_in.sin6_addr.s6_addr[15] = iface;
1221
1222                         si->bindname = sockaddr_dup(&bind_in, blen);
1223                         si->bindname_len = blen;
1224                 }
1225
1226                 break;
1227         }
1228 #endif
1229         default:
1230                 SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown address family\n");
1231                 errno = EADDRNOTAVAIL;
1232                 return -1;
1233         }
1234
1235
1236         if (bcast) *bcast = is_bcast;
1237
1238         if (iface == 0 || iface > MAX_WRAPPED_INTERFACES) {
1239                 errno = EINVAL;
1240                 return -1;
1241         }
1242
1243         if (prt == 0) {
1244                 /* handle auto-allocation of ephemeral ports */
1245                 for (prt = 5001; prt < 10000; prt++) {
1246                         snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT, 
1247                                  socket_wrapper_dir(), type, iface, prt);
1248                         if (stat(un->sun_path, &st) == 0) continue;
1249
1250                         set_port(si->family, prt, si->myname);
1251                         set_port(si->family, prt, si->bindname);
1252
1253                         break;
1254                 }
1255                 if (prt == 10000) {
1256                         errno = ENFILE;
1257                         return -1;
1258                 }
1259         }
1260
1261         snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT, 
1262                  socket_wrapper_dir(), type, iface, prt);
1263         SWRAP_LOG(SWRAP_LOG_DEBUG, "un path [%s]", un->sun_path);
1264         return 0;
1265 }
1266
1267 static struct socket_info *find_socket_info(int fd)
1268 {
1269         struct socket_info *i;
1270
1271         for (i = sockets; i; i = i->next) {
1272                 struct socket_info_fd *f;
1273                 for (f = i->fds; f; f = f->next) {
1274                         if (f->fd == fd) {
1275                                 return i;
1276                         }
1277                 }
1278         }
1279
1280         return NULL;
1281 }
1282
1283 #if 0 /* FIXME */
1284 static bool check_addr_port_in_use(const struct sockaddr *sa, socklen_t len)
1285 {
1286         struct socket_info *s;
1287
1288         /* first catch invalid input */
1289         switch (sa->sa_family) {
1290         case AF_INET:
1291                 if (len < sizeof(struct sockaddr_in)) {
1292                         return false;
1293                 }
1294                 break;
1295 #if HAVE_IPV6
1296         case AF_INET6:
1297                 if (len < sizeof(struct sockaddr_in6)) {
1298                         return false;
1299                 }
1300                 break;
1301 #endif
1302         default:
1303                 return false;
1304                 break;
1305         }
1306
1307         for (s = sockets; s != NULL; s = s->next) {
1308                 if (s->myname == NULL) {
1309                         continue;
1310                 }
1311                 if (s->myname->sa_family != sa->sa_family) {
1312                         continue;
1313                 }
1314                 switch (s->myname->sa_family) {
1315                 case AF_INET: {
1316                         struct sockaddr_in *sin1, *sin2;
1317
1318                         sin1 = (struct sockaddr_in *)s->myname;
1319                         sin2 = (struct sockaddr_in *)sa;
1320
1321                         if (sin1->sin_addr.s_addr == htonl(INADDR_ANY)) {
1322                                 continue;
1323                         }
1324                         if (sin1->sin_port != sin2->sin_port) {
1325                                 continue;
1326                         }
1327                         if (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr) {
1328                                 continue;
1329                         }
1330
1331                         /* found */
1332                         return true;
1333                         break;
1334                 }
1335 #if HAVE_IPV6
1336                 case AF_INET6: {
1337                         struct sockaddr_in6 *sin1, *sin2;
1338
1339                         sin1 = (struct sockaddr_in6 *)s->myname;
1340                         sin2 = (struct sockaddr_in6 *)sa;
1341
1342                         if (sin1->sin6_port != sin2->sin6_port) {
1343                                 continue;
1344                         }
1345                         if (!IN6_ARE_ADDR_EQUAL(&sin1->sin6_addr,
1346                                                 &sin2->sin6_addr))
1347                         {
1348                                 continue;
1349                         }
1350
1351                         /* found */
1352                         return true;
1353                         break;
1354                 }
1355 #endif
1356                 default:
1357                         continue;
1358                         break;
1359
1360                 }
1361         }
1362
1363         return false;
1364 }
1365 #endif
1366
1367 static void swrap_remove_stale(int fd)
1368 {
1369         struct socket_info *si = find_socket_info(fd);
1370         struct socket_info_fd *fi;
1371
1372         if (si != NULL) {
1373                 for (fi = si->fds; fi; fi = fi->next) {
1374                         if (fi->fd == fd) {
1375                                 SWRAP_LOG(SWRAP_LOG_TRACE, "remove stale wrapper for %d", fd);
1376                                 SWRAP_DLIST_REMOVE(si->fds, fi);
1377                                 free(fi);
1378                                 break;
1379                         }
1380                 }
1381
1382                 if (si->fds == NULL) {
1383                         SWRAP_DLIST_REMOVE(sockets, si);
1384                 }
1385         }
1386 }
1387
1388 static int sockaddr_convert_to_un(struct socket_info *si,
1389                                   const struct sockaddr *in_addr,
1390                                   socklen_t in_len,
1391                                   struct sockaddr_un *out_addr,
1392                                   int alloc_sock,
1393                                   int *bcast)
1394 {
1395         struct sockaddr *out = (struct sockaddr *)(void *)out_addr;
1396
1397         (void) in_len; /* unused */
1398
1399         if (out_addr == NULL) {
1400                 return 0;
1401         }
1402
1403         out->sa_family = AF_UNIX;
1404 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
1405         out->sa_len = sizeof(*out_addr);
1406 #endif
1407
1408         switch (in_addr->sa_family) {
1409         case AF_UNSPEC: {
1410                 const struct sockaddr_in *sin;
1411                 if (si->family != AF_INET) {
1412                         break;
1413                 }
1414                 if (in_len < sizeof(struct sockaddr_in)) {
1415                         break;
1416                 }
1417                 sin = (const struct sockaddr_in *)in_addr;
1418                 if(sin->sin_addr.s_addr != htonl(INADDR_ANY)) {
1419                         break;
1420                 }
1421
1422                 /*
1423                  * Note: in the special case of AF_UNSPEC and INADDR_ANY,
1424                  * AF_UNSPEC is mapped to AF_INET and must be treated here.
1425                  */
1426
1427                 /* FALL THROUGH */
1428         }
1429         case AF_INET:
1430 #ifdef HAVE_IPV6
1431         case AF_INET6:
1432 #endif
1433                 switch (si->type) {
1434                 case SOCK_STREAM:
1435                 case SOCK_DGRAM:
1436                         break;
1437                 default:
1438                         SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!\n");
1439                         errno = ESOCKTNOSUPPORT;
1440                         return -1;
1441                 }
1442                 if (alloc_sock) {
1443                         return convert_in_un_alloc(si, in_addr, out_addr, bcast);
1444                 } else {
1445                         return convert_in_un_remote(si, in_addr, out_addr, bcast);
1446                 }
1447         default:
1448                 break;
1449         }
1450
1451         errno = EAFNOSUPPORT;
1452         SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown address family\n");
1453         return -1;
1454 }
1455
1456 static int sockaddr_convert_from_un(const struct socket_info *si, 
1457                                     const struct sockaddr_un *in_addr, 
1458                                     socklen_t un_addrlen,
1459                                     int family,
1460                                     struct sockaddr *out_addr,
1461                                     socklen_t *out_addrlen)
1462 {
1463         int ret;
1464
1465         if (out_addr == NULL || out_addrlen == NULL) 
1466                 return 0;
1467
1468         if (un_addrlen == 0) {
1469                 *out_addrlen = 0;
1470                 return 0;
1471         }
1472
1473         switch (family) {
1474         case AF_INET:
1475 #ifdef HAVE_IPV6
1476         case AF_INET6:
1477 #endif
1478                 switch (si->type) {
1479                 case SOCK_STREAM:
1480                 case SOCK_DGRAM:
1481                         break;
1482                 default:
1483                         SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!\n");
1484                         errno = ESOCKTNOSUPPORT;
1485                         return -1;
1486                 }
1487                 ret = convert_un_in(in_addr, out_addr, out_addrlen);
1488 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
1489                 out_addr->sa_len = *out_addrlen;
1490 #endif
1491                 return ret;
1492         default:
1493                 break;
1494         }
1495
1496         SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown address family\n");
1497         errno = EAFNOSUPPORT;
1498         return -1;
1499 }
1500
1501 enum swrap_packet_type {
1502         SWRAP_CONNECT_SEND,
1503         SWRAP_CONNECT_UNREACH,
1504         SWRAP_CONNECT_RECV,
1505         SWRAP_CONNECT_ACK,
1506         SWRAP_ACCEPT_SEND,
1507         SWRAP_ACCEPT_RECV,
1508         SWRAP_ACCEPT_ACK,
1509         SWRAP_RECVFROM,
1510         SWRAP_SENDTO,
1511         SWRAP_SENDTO_UNREACH,
1512         SWRAP_PENDING_RST,
1513         SWRAP_RECV,
1514         SWRAP_RECV_RST,
1515         SWRAP_SEND,
1516         SWRAP_SEND_RST,
1517         SWRAP_CLOSE_SEND,
1518         SWRAP_CLOSE_RECV,
1519         SWRAP_CLOSE_ACK,
1520 };
1521
1522 struct swrap_file_hdr {
1523         uint32_t        magic;
1524         uint16_t        version_major;
1525         uint16_t        version_minor;
1526         int32_t         timezone;
1527         uint32_t        sigfigs;
1528         uint32_t        frame_max_len;
1529 #define SWRAP_FRAME_LENGTH_MAX 0xFFFF
1530         uint32_t        link_type;
1531 };
1532 #define SWRAP_FILE_HDR_SIZE 24
1533
1534 struct swrap_packet_frame {
1535         uint32_t seconds;
1536         uint32_t micro_seconds;
1537         uint32_t recorded_length;
1538         uint32_t full_length;
1539 };
1540 #define SWRAP_PACKET_FRAME_SIZE 16
1541
1542 union swrap_packet_ip {
1543         struct {
1544                 uint8_t         ver_hdrlen;
1545                 uint8_t         tos;
1546                 uint16_t        packet_length;
1547                 uint16_t        identification;
1548                 uint8_t         flags;
1549                 uint8_t         fragment;
1550                 uint8_t         ttl;
1551                 uint8_t         protocol;
1552                 uint16_t        hdr_checksum;
1553                 uint32_t        src_addr;
1554                 uint32_t        dest_addr;
1555         } v4;
1556 #define SWRAP_PACKET_IP_V4_SIZE 20
1557         struct {
1558                 uint8_t         ver_prio;
1559                 uint8_t         flow_label_high;
1560                 uint16_t        flow_label_low;
1561                 uint16_t        payload_length;
1562                 uint8_t         next_header;
1563                 uint8_t         hop_limit;
1564                 uint8_t         src_addr[16];
1565                 uint8_t         dest_addr[16];
1566         } v6;
1567 #define SWRAP_PACKET_IP_V6_SIZE 40
1568 };
1569 #define SWRAP_PACKET_IP_SIZE 40
1570
1571 union swrap_packet_payload {
1572         struct {
1573                 uint16_t        source_port;
1574                 uint16_t        dest_port;
1575                 uint32_t        seq_num;
1576                 uint32_t        ack_num;
1577                 uint8_t         hdr_length;
1578                 uint8_t         control;
1579                 uint16_t        window;
1580                 uint16_t        checksum;
1581                 uint16_t        urg;
1582         } tcp;
1583 #define SWRAP_PACKET_PAYLOAD_TCP_SIZE 20
1584         struct {
1585                 uint16_t        source_port;
1586                 uint16_t        dest_port;
1587                 uint16_t        length;
1588                 uint16_t        checksum;
1589         } udp;
1590 #define SWRAP_PACKET_PAYLOAD_UDP_SIZE 8
1591         struct {
1592                 uint8_t         type;
1593                 uint8_t         code;
1594                 uint16_t        checksum;
1595                 uint32_t        unused;
1596         } icmp4;
1597 #define SWRAP_PACKET_PAYLOAD_ICMP4_SIZE 8
1598         struct {
1599                 uint8_t         type;
1600                 uint8_t         code;
1601                 uint16_t        checksum;
1602                 uint32_t        unused;
1603         } icmp6;
1604 #define SWRAP_PACKET_PAYLOAD_ICMP6_SIZE 8
1605 };
1606 #define SWRAP_PACKET_PAYLOAD_SIZE 20
1607
1608 #define SWRAP_PACKET_MIN_ALLOC \
1609         (SWRAP_PACKET_FRAME_SIZE + \
1610          SWRAP_PACKET_IP_SIZE + \
1611          SWRAP_PACKET_PAYLOAD_SIZE)
1612
1613 static const char *swrap_pcap_init_file(void)
1614 {
1615         static int initialized = 0;
1616         static const char *s = NULL;
1617         static const struct swrap_file_hdr h;
1618         static const struct swrap_packet_frame f;
1619         static const union swrap_packet_ip i;
1620         static const union swrap_packet_payload p;
1621
1622         if (initialized == 1) {
1623                 return s;
1624         }
1625         initialized = 1;
1626
1627         /*
1628          * TODO: don't use the structs use plain buffer offsets
1629          *       and PUSH_U8(), PUSH_U16() and PUSH_U32()
1630          * 
1631          * for now make sure we disable PCAP support
1632          * if the struct has alignment!
1633          */
1634         if (sizeof(h) != SWRAP_FILE_HDR_SIZE) {
1635                 return NULL;
1636         }
1637         if (sizeof(f) != SWRAP_PACKET_FRAME_SIZE) {
1638                 return NULL;
1639         }
1640         if (sizeof(i) != SWRAP_PACKET_IP_SIZE) {
1641                 return NULL;
1642         }
1643         if (sizeof(i.v4) != SWRAP_PACKET_IP_V4_SIZE) {
1644                 return NULL;
1645         }
1646         if (sizeof(i.v6) != SWRAP_PACKET_IP_V6_SIZE) {
1647                 return NULL;
1648         }
1649         if (sizeof(p) != SWRAP_PACKET_PAYLOAD_SIZE) {
1650                 return NULL;
1651         }
1652         if (sizeof(p.tcp) != SWRAP_PACKET_PAYLOAD_TCP_SIZE) {
1653                 return NULL;
1654         }
1655         if (sizeof(p.udp) != SWRAP_PACKET_PAYLOAD_UDP_SIZE) {
1656                 return NULL;
1657         }
1658         if (sizeof(p.icmp4) != SWRAP_PACKET_PAYLOAD_ICMP4_SIZE) {
1659                 return NULL;
1660         }
1661         if (sizeof(p.icmp6) != SWRAP_PACKET_PAYLOAD_ICMP6_SIZE) {
1662                 return NULL;
1663         }
1664
1665         s = getenv("SOCKET_WRAPPER_PCAP_FILE");
1666         if (s == NULL) {
1667                 return NULL;
1668         }
1669         if (strncmp(s, "./", 2) == 0) {
1670                 s += 2;
1671         }
1672         return s;
1673 }
1674
1675 static uint8_t *swrap_pcap_packet_init(struct timeval *tval,
1676                                        const struct sockaddr *src,
1677                                        const struct sockaddr *dest,
1678                                        int socket_type,
1679                                        const uint8_t *payload,
1680                                        size_t payload_len,
1681                                        unsigned long tcp_seqno,
1682                                        unsigned long tcp_ack,
1683                                        unsigned char tcp_ctl,
1684                                        int unreachable,
1685                                        size_t *_packet_len)
1686 {
1687         uint8_t *base;
1688         uint8_t *buf;
1689         struct swrap_packet_frame *frame;
1690         union swrap_packet_ip *ip;
1691         union swrap_packet_payload *pay;
1692         size_t packet_len;
1693         size_t alloc_len;
1694         size_t nonwire_len = sizeof(*frame);
1695         size_t wire_hdr_len = 0;
1696         size_t wire_len = 0;
1697         size_t ip_hdr_len = 0;
1698         size_t icmp_hdr_len = 0;
1699         size_t icmp_truncate_len = 0;
1700         uint8_t protocol = 0, icmp_protocol = 0;
1701         const struct sockaddr_in *src_in = NULL;
1702         const struct sockaddr_in *dest_in = NULL;
1703 #ifdef HAVE_IPV6
1704         const struct sockaddr_in6 *src_in6 = NULL;
1705         const struct sockaddr_in6 *dest_in6 = NULL;
1706 #endif
1707         uint16_t src_port;
1708         uint16_t dest_port;
1709
1710         switch (src->sa_family) {
1711         case AF_INET:
1712                 src_in = (const struct sockaddr_in *)src;
1713                 dest_in = (const struct sockaddr_in *)dest;
1714                 src_port = src_in->sin_port;
1715                 dest_port = dest_in->sin_port;
1716                 ip_hdr_len = sizeof(ip->v4);
1717                 break;
1718 #ifdef HAVE_IPV6
1719         case AF_INET6:
1720                 src_in6 = (const struct sockaddr_in6 *)src;
1721                 dest_in6 = (const struct sockaddr_in6 *)dest;
1722                 src_port = src_in6->sin6_port;
1723                 dest_port = dest_in6->sin6_port;
1724                 ip_hdr_len = sizeof(ip->v6);
1725                 break;
1726 #endif
1727         default:
1728                 return NULL;
1729         }
1730
1731         switch (socket_type) {
1732         case SOCK_STREAM:
1733                 protocol = 0x06; /* TCP */
1734                 wire_hdr_len = ip_hdr_len + sizeof(pay->tcp);
1735                 wire_len = wire_hdr_len + payload_len;
1736                 break;
1737
1738         case SOCK_DGRAM:
1739                 protocol = 0x11; /* UDP */
1740                 wire_hdr_len = ip_hdr_len + sizeof(pay->udp);
1741                 wire_len = wire_hdr_len + payload_len;
1742                 break;
1743
1744         default:
1745                 return NULL;
1746         }
1747
1748         if (unreachable) {
1749                 icmp_protocol = protocol;
1750                 switch (src->sa_family) {
1751                 case AF_INET:
1752                         protocol = 0x01; /* ICMPv4 */
1753                         icmp_hdr_len = ip_hdr_len + sizeof(pay->icmp4);
1754                         break;
1755 #ifdef HAVE_IPV6
1756                 case AF_INET6:
1757                         protocol = 0x3A; /* ICMPv6 */
1758                         icmp_hdr_len = ip_hdr_len + sizeof(pay->icmp6);
1759                         break;
1760 #endif
1761                 }
1762                 if (wire_len > 64 ) {
1763                         icmp_truncate_len = wire_len - 64;
1764                 }
1765                 wire_hdr_len += icmp_hdr_len;
1766                 wire_len += icmp_hdr_len;
1767         }
1768
1769         packet_len = nonwire_len + wire_len;
1770         alloc_len = packet_len;
1771         if (alloc_len < SWRAP_PACKET_MIN_ALLOC) {
1772                 alloc_len = SWRAP_PACKET_MIN_ALLOC;
1773         }
1774
1775         base = (uint8_t *)malloc(alloc_len);
1776         if (base == NULL) {
1777                 return NULL;
1778         }
1779         memset(base, 0x0, alloc_len);
1780
1781         buf = base;
1782
1783         frame = (struct swrap_packet_frame *)buf;
1784         frame->seconds          = tval->tv_sec;
1785         frame->micro_seconds    = tval->tv_usec;
1786         frame->recorded_length  = wire_len - icmp_truncate_len;
1787         frame->full_length      = wire_len - icmp_truncate_len;
1788         buf += SWRAP_PACKET_FRAME_SIZE;
1789
1790         ip = (union swrap_packet_ip *)buf;
1791         switch (src->sa_family) {
1792         case AF_INET:
1793                 ip->v4.ver_hdrlen       = 0x45; /* version 4 and 5 * 32 bit words */
1794                 ip->v4.tos              = 0x00;
1795                 ip->v4.packet_length    = htons(wire_len - icmp_truncate_len);
1796                 ip->v4.identification   = htons(0xFFFF);
1797                 ip->v4.flags            = 0x40; /* BIT 1 set - means don't fragment */
1798                 ip->v4.fragment         = htons(0x0000);
1799                 ip->v4.ttl              = 0xFF;
1800                 ip->v4.protocol         = protocol;
1801                 ip->v4.hdr_checksum     = htons(0x0000);
1802                 ip->v4.src_addr         = src_in->sin_addr.s_addr;
1803                 ip->v4.dest_addr        = dest_in->sin_addr.s_addr;
1804                 buf += SWRAP_PACKET_IP_V4_SIZE;
1805                 break;
1806 #ifdef HAVE_IPV6
1807         case AF_INET6:
1808                 ip->v6.ver_prio         = 0x60; /* version 4 and 5 * 32 bit words */
1809                 ip->v6.flow_label_high  = 0x00;
1810                 ip->v6.flow_label_low   = 0x0000;
1811                 ip->v6.payload_length   = htons(wire_len - icmp_truncate_len); /* TODO */
1812                 ip->v6.next_header      = protocol;
1813                 memcpy(ip->v6.src_addr, src_in6->sin6_addr.s6_addr, 16);
1814                 memcpy(ip->v6.dest_addr, dest_in6->sin6_addr.s6_addr, 16);
1815                 buf += SWRAP_PACKET_IP_V6_SIZE;
1816                 break;
1817 #endif
1818         }
1819
1820         if (unreachable) {
1821                 pay = (union swrap_packet_payload *)buf;
1822                 switch (src->sa_family) {
1823                 case AF_INET:
1824                         pay->icmp4.type         = 0x03; /* destination unreachable */
1825                         pay->icmp4.code         = 0x01; /* host unreachable */
1826                         pay->icmp4.checksum     = htons(0x0000);
1827                         pay->icmp4.unused       = htonl(0x00000000);
1828                         buf += SWRAP_PACKET_PAYLOAD_ICMP4_SIZE;
1829
1830                         /* set the ip header in the ICMP payload */
1831                         ip = (union swrap_packet_ip *)buf;
1832                         ip->v4.ver_hdrlen       = 0x45; /* version 4 and 5 * 32 bit words */
1833                         ip->v4.tos              = 0x00;
1834                         ip->v4.packet_length    = htons(wire_len - icmp_hdr_len);
1835                         ip->v4.identification   = htons(0xFFFF);
1836                         ip->v4.flags            = 0x40; /* BIT 1 set - means don't fragment */
1837                         ip->v4.fragment         = htons(0x0000);
1838                         ip->v4.ttl              = 0xFF;
1839                         ip->v4.protocol         = icmp_protocol;
1840                         ip->v4.hdr_checksum     = htons(0x0000);
1841                         ip->v4.src_addr         = dest_in->sin_addr.s_addr;
1842                         ip->v4.dest_addr        = src_in->sin_addr.s_addr;
1843                         buf += SWRAP_PACKET_IP_V4_SIZE;
1844
1845                         src_port = dest_in->sin_port;
1846                         dest_port = src_in->sin_port;
1847                         break;
1848 #ifdef HAVE_IPV6
1849                 case AF_INET6:
1850                         pay->icmp6.type         = 0x01; /* destination unreachable */
1851                         pay->icmp6.code         = 0x03; /* address unreachable */
1852                         pay->icmp6.checksum     = htons(0x0000);
1853                         pay->icmp6.unused       = htonl(0x00000000);
1854                         buf += SWRAP_PACKET_PAYLOAD_ICMP6_SIZE;
1855
1856                         /* set the ip header in the ICMP payload */
1857                         ip = (union swrap_packet_ip *)buf;
1858                         ip->v6.ver_prio         = 0x60; /* version 4 and 5 * 32 bit words */
1859                         ip->v6.flow_label_high  = 0x00;
1860                         ip->v6.flow_label_low   = 0x0000;
1861                         ip->v6.payload_length   = htons(wire_len - icmp_truncate_len); /* TODO */
1862                         ip->v6.next_header      = protocol;
1863                         memcpy(ip->v6.src_addr, dest_in6->sin6_addr.s6_addr, 16);
1864                         memcpy(ip->v6.dest_addr, src_in6->sin6_addr.s6_addr, 16);
1865                         buf += SWRAP_PACKET_IP_V6_SIZE;
1866
1867                         src_port = dest_in6->sin6_port;
1868                         dest_port = src_in6->sin6_port;
1869                         break;
1870 #endif
1871                 }
1872         }
1873
1874         pay = (union swrap_packet_payload *)buf;
1875
1876         switch (socket_type) {
1877         case SOCK_STREAM:
1878                 pay->tcp.source_port    = src_port;
1879                 pay->tcp.dest_port      = dest_port;
1880                 pay->tcp.seq_num        = htonl(tcp_seqno);
1881                 pay->tcp.ack_num        = htonl(tcp_ack);
1882                 pay->tcp.hdr_length     = 0x50; /* 5 * 32 bit words */
1883                 pay->tcp.control        = tcp_ctl;
1884                 pay->tcp.window         = htons(0x7FFF);
1885                 pay->tcp.checksum       = htons(0x0000);
1886                 pay->tcp.urg            = htons(0x0000);
1887                 buf += SWRAP_PACKET_PAYLOAD_TCP_SIZE;
1888
1889                 break;
1890
1891         case SOCK_DGRAM:
1892                 pay->udp.source_port    = src_port;
1893                 pay->udp.dest_port      = dest_port;
1894                 pay->udp.length         = htons(8 + payload_len);
1895                 pay->udp.checksum       = htons(0x0000);
1896                 buf += SWRAP_PACKET_PAYLOAD_UDP_SIZE;
1897
1898                 break;
1899         }
1900
1901         if (payload && payload_len > 0) {
1902                 memcpy(buf, payload, payload_len);
1903         }
1904
1905         *_packet_len = packet_len - icmp_truncate_len;
1906         return base;
1907 }
1908
1909 static int swrap_get_pcap_fd(const char *fname)
1910 {
1911         static int fd = -1;
1912
1913         if (fd != -1) return fd;
1914
1915         fd = libc_open(fname, O_WRONLY|O_CREAT|O_EXCL|O_APPEND, 0644);
1916         if (fd != -1) {
1917                 struct swrap_file_hdr file_hdr;
1918                 file_hdr.magic          = 0xA1B2C3D4;
1919                 file_hdr.version_major  = 0x0002;       
1920                 file_hdr.version_minor  = 0x0004;
1921                 file_hdr.timezone       = 0x00000000;
1922                 file_hdr.sigfigs        = 0x00000000;
1923                 file_hdr.frame_max_len  = SWRAP_FRAME_LENGTH_MAX;
1924                 file_hdr.link_type      = 0x0065; /* 101 RAW IP */
1925
1926                 if (write(fd, &file_hdr, sizeof(file_hdr)) != sizeof(file_hdr)) {
1927                         close(fd);
1928                         fd = -1;
1929                 }
1930                 return fd;
1931         }
1932
1933         fd = libc_open(fname, O_WRONLY|O_APPEND, 0644);
1934
1935         return fd;
1936 }
1937
1938 static uint8_t *swrap_marshall_packet(struct socket_info *si,
1939                                       const struct sockaddr *addr,
1940                                       enum swrap_packet_type type,
1941                                       const void *buf, size_t len,
1942                                       size_t *packet_len)
1943 {
1944         const struct sockaddr *src_addr;
1945         const struct sockaddr *dest_addr;
1946         unsigned long tcp_seqno = 0;
1947         unsigned long tcp_ack = 0;
1948         unsigned char tcp_ctl = 0;
1949         int unreachable = 0;
1950
1951         struct timeval tv;
1952
1953         switch (si->family) {
1954         case AF_INET:
1955                 break;
1956 #ifdef HAVE_IPV6
1957         case AF_INET6:
1958                 break;
1959 #endif
1960         default:
1961                 return NULL;
1962         }
1963
1964         switch (type) {
1965         case SWRAP_CONNECT_SEND:
1966                 if (si->type != SOCK_STREAM) return NULL;
1967
1968                 src_addr = si->myname;
1969                 dest_addr = addr;
1970
1971                 tcp_seqno = si->io.pck_snd;
1972                 tcp_ack = si->io.pck_rcv;
1973                 tcp_ctl = 0x02; /* SYN */
1974
1975                 si->io.pck_snd += 1;
1976
1977                 break;
1978
1979         case SWRAP_CONNECT_RECV:
1980                 if (si->type != SOCK_STREAM) return NULL;
1981
1982                 dest_addr = si->myname;
1983                 src_addr = addr;
1984
1985                 tcp_seqno = si->io.pck_rcv;
1986                 tcp_ack = si->io.pck_snd;
1987                 tcp_ctl = 0x12; /** SYN,ACK */
1988
1989                 si->io.pck_rcv += 1;
1990
1991                 break;
1992
1993         case SWRAP_CONNECT_UNREACH:
1994                 if (si->type != SOCK_STREAM) return NULL;
1995
1996                 dest_addr = si->myname;
1997                 src_addr = addr;
1998
1999                 /* Unreachable: resend the data of SWRAP_CONNECT_SEND */
2000                 tcp_seqno = si->io.pck_snd - 1;
2001                 tcp_ack = si->io.pck_rcv;
2002                 tcp_ctl = 0x02; /* SYN */
2003                 unreachable = 1;
2004
2005                 break;
2006
2007         case SWRAP_CONNECT_ACK:
2008                 if (si->type != SOCK_STREAM) return NULL;
2009
2010                 src_addr = si->myname;
2011                 dest_addr = addr;
2012
2013                 tcp_seqno = si->io.pck_snd;
2014                 tcp_ack = si->io.pck_rcv;
2015                 tcp_ctl = 0x10; /* ACK */
2016
2017                 break;
2018
2019         case SWRAP_ACCEPT_SEND:
2020                 if (si->type != SOCK_STREAM) return NULL;
2021
2022                 dest_addr = si->myname;
2023                 src_addr = addr;
2024
2025                 tcp_seqno = si->io.pck_rcv;
2026                 tcp_ack = si->io.pck_snd;
2027                 tcp_ctl = 0x02; /* SYN */
2028
2029                 si->io.pck_rcv += 1;
2030
2031                 break;
2032
2033         case SWRAP_ACCEPT_RECV:
2034                 if (si->type != SOCK_STREAM) return NULL;
2035
2036                 src_addr = si->myname;
2037                 dest_addr = addr;
2038
2039                 tcp_seqno = si->io.pck_snd;
2040                 tcp_ack = si->io.pck_rcv;
2041                 tcp_ctl = 0x12; /* SYN,ACK */
2042
2043                 si->io.pck_snd += 1;
2044
2045                 break;
2046
2047         case SWRAP_ACCEPT_ACK:
2048                 if (si->type != SOCK_STREAM) return NULL;
2049
2050                 dest_addr = si->myname;
2051                 src_addr = addr;
2052
2053                 tcp_seqno = si->io.pck_rcv;
2054                 tcp_ack = si->io.pck_snd;
2055                 tcp_ctl = 0x10; /* ACK */
2056
2057                 break;
2058
2059         case SWRAP_SEND:
2060                 src_addr = si->myname;
2061                 dest_addr = si->peername;
2062
2063                 tcp_seqno = si->io.pck_snd;
2064                 tcp_ack = si->io.pck_rcv;
2065                 tcp_ctl = 0x18; /* PSH,ACK */
2066
2067                 si->io.pck_snd += len;
2068
2069                 break;
2070
2071         case SWRAP_SEND_RST:
2072                 dest_addr = si->myname;
2073                 src_addr = si->peername;
2074
2075                 if (si->type == SOCK_DGRAM) {
2076                         return swrap_marshall_packet(si, si->peername,
2077                                           SWRAP_SENDTO_UNREACH,
2078                                           buf, len, packet_len);
2079                 }
2080
2081                 tcp_seqno = si->io.pck_rcv;
2082                 tcp_ack = si->io.pck_snd;
2083                 tcp_ctl = 0x14; /** RST,ACK */
2084
2085                 break;
2086
2087         case SWRAP_PENDING_RST:
2088                 dest_addr = si->myname;
2089                 src_addr = si->peername;
2090
2091                 if (si->type == SOCK_DGRAM) {
2092                         return NULL;
2093                 }
2094
2095                 tcp_seqno = si->io.pck_rcv;
2096                 tcp_ack = si->io.pck_snd;
2097                 tcp_ctl = 0x14; /* RST,ACK */
2098
2099                 break;
2100
2101         case SWRAP_RECV:
2102                 dest_addr = si->myname;
2103                 src_addr = si->peername;
2104
2105                 tcp_seqno = si->io.pck_rcv;
2106                 tcp_ack = si->io.pck_snd;
2107                 tcp_ctl = 0x18; /* PSH,ACK */
2108
2109                 si->io.pck_rcv += len;
2110
2111                 break;
2112
2113         case SWRAP_RECV_RST:
2114                 dest_addr = si->myname;
2115                 src_addr = si->peername;
2116
2117                 if (si->type == SOCK_DGRAM) {
2118                         return NULL;
2119                 }
2120
2121                 tcp_seqno = si->io.pck_rcv;
2122                 tcp_ack = si->io.pck_snd;
2123                 tcp_ctl = 0x14; /* RST,ACK */
2124
2125                 break;
2126
2127         case SWRAP_SENDTO:
2128                 src_addr = si->myname;
2129                 dest_addr = addr;
2130
2131                 si->io.pck_snd += len;
2132
2133                 break;
2134
2135         case SWRAP_SENDTO_UNREACH:
2136                 dest_addr = si->myname;
2137                 src_addr = addr;
2138
2139                 unreachable = 1;
2140
2141                 break;
2142
2143         case SWRAP_RECVFROM:
2144                 dest_addr = si->myname;
2145                 src_addr = addr;
2146
2147                 si->io.pck_rcv += len;
2148
2149                 break;
2150
2151         case SWRAP_CLOSE_SEND:
2152                 if (si->type != SOCK_STREAM) return NULL;
2153
2154                 src_addr = si->myname;
2155                 dest_addr = si->peername;
2156
2157                 tcp_seqno = si->io.pck_snd;
2158                 tcp_ack = si->io.pck_rcv;
2159                 tcp_ctl = 0x11; /* FIN, ACK */
2160
2161                 si->io.pck_snd += 1;
2162
2163                 break;
2164
2165         case SWRAP_CLOSE_RECV:
2166                 if (si->type != SOCK_STREAM) return NULL;
2167
2168                 dest_addr = si->myname;
2169                 src_addr = si->peername;
2170
2171                 tcp_seqno = si->io.pck_rcv;
2172                 tcp_ack = si->io.pck_snd;
2173                 tcp_ctl = 0x11; /* FIN,ACK */
2174
2175                 si->io.pck_rcv += 1;
2176
2177                 break;
2178
2179         case SWRAP_CLOSE_ACK:
2180                 if (si->type != SOCK_STREAM) return NULL;
2181
2182                 src_addr = si->myname;
2183                 dest_addr = si->peername;
2184
2185                 tcp_seqno = si->io.pck_snd;
2186                 tcp_ack = si->io.pck_rcv;
2187                 tcp_ctl = 0x10; /* ACK */
2188
2189                 break;
2190         default:
2191                 return NULL;
2192         }
2193
2194         swrapGetTimeOfDay(&tv);
2195
2196         return swrap_pcap_packet_init(&tv,
2197                                       src_addr,
2198                                       dest_addr,
2199                                       si->type,
2200                                       (const uint8_t *)buf,
2201                                       len,
2202                                       tcp_seqno,
2203                                       tcp_ack,
2204                                       tcp_ctl,
2205                                       unreachable,
2206                                       packet_len);
2207 }
2208
2209 static void swrap_dump_packet(struct socket_info *si,
2210                               const struct sockaddr *addr,
2211                               enum swrap_packet_type type,
2212                               const void *buf, size_t len)
2213 {
2214         const char *file_name;
2215         uint8_t *packet;
2216         size_t packet_len = 0;
2217         int fd;
2218
2219         file_name = swrap_pcap_init_file();
2220         if (!file_name) {
2221                 return;
2222         }
2223
2224         packet = swrap_marshall_packet(si, addr, type, buf, len, &packet_len);
2225         if (!packet) {
2226                 return;
2227         }
2228
2229         fd = swrap_get_pcap_fd(file_name);
2230         if (fd != -1) {
2231                 if (write(fd, packet, packet_len) != (ssize_t)packet_len) {
2232                         free(packet);
2233                         return;
2234                 }
2235         }
2236
2237         free(packet);
2238 }
2239
2240 /****************************************************************************
2241  *   SIGNALFD
2242  ***************************************************************************/
2243
2244 #ifdef HAVE_SIGNALFD
2245 static int swrap_signalfd(int fd, const sigset_t *mask, int flags)
2246 {
2247         int rc;
2248
2249         rc = libc_signalfd(fd, mask, flags);
2250         if (rc != -1) {
2251                 swrap_remove_stale(fd);
2252         }
2253
2254         return rc;
2255 }
2256
2257 int signalfd(int fd, const sigset_t *mask, int flags)
2258 {
2259         return swrap_signalfd(fd, mask, flags);
2260 }
2261 #endif
2262
2263 /****************************************************************************
2264  *   SOCKET
2265  ***************************************************************************/
2266
2267 static int swrap_socket(int family, int type, int protocol)
2268 {
2269         struct socket_info *si;
2270         struct socket_info_fd *fi;
2271         int fd;
2272         int real_type = type;
2273
2274         /*
2275          * Remove possible addition flags passed to socket() so
2276          * do not fail checking the type.
2277          * See https://lwn.net/Articles/281965/
2278          */
2279 #ifdef SOCK_CLOEXEC
2280         real_type &= ~SOCK_CLOEXEC;
2281 #endif
2282 #ifdef SOCK_NONBLOCK
2283         real_type &= ~SOCK_NONBLOCK;
2284 #endif
2285
2286         if (!socket_wrapper_enabled()) {
2287                 return libc_socket(family, type, protocol);
2288         }
2289
2290         switch (family) {
2291         case AF_INET:
2292 #ifdef HAVE_IPV6
2293         case AF_INET6:
2294 #endif
2295                 break;
2296         case AF_UNIX:
2297                 return libc_socket(family, type, protocol);
2298         default:
2299                 errno = EAFNOSUPPORT;
2300                 return -1;
2301         }
2302
2303         switch (real_type) {
2304         case SOCK_STREAM:
2305                 break;
2306         case SOCK_DGRAM:
2307                 break;
2308         default:
2309                 errno = EPROTONOSUPPORT;
2310                 return -1;
2311         }
2312
2313         switch (protocol) {
2314         case 0:
2315                 break;
2316         case 6:
2317                 if (real_type == SOCK_STREAM) {
2318                         break;
2319                 }
2320                 /*fall through*/
2321         case 17:
2322                 if (real_type == SOCK_DGRAM) {
2323                         break;
2324                 }
2325                 /*fall through*/
2326         default:
2327                 errno = EPROTONOSUPPORT;
2328                 return -1;
2329         }
2330
2331         /*
2332          * We must call libc_socket with type, from the caller, not the version
2333          * we removed SOCK_CLOEXEC and SOCK_NONBLOCK from
2334          */
2335         fd = libc_socket(AF_UNIX, type, 0);
2336
2337         if (fd == -1) {
2338                 return -1;
2339         }
2340
2341         /* Check if we have a stale fd and remove it */
2342         si = find_socket_info(fd);
2343         if (si != NULL) {
2344                 swrap_remove_stale(fd);
2345         }
2346
2347         si = (struct socket_info *)malloc(sizeof(struct socket_info));
2348         memset(si, 0, sizeof(struct socket_info));
2349         if (si == NULL) {
2350                 errno = ENOMEM;
2351                 return -1;
2352         }
2353
2354         si->family = family;
2355
2356         /* however, the rest of the socket_wrapper code expects just
2357          * the type, not the flags */
2358         si->type = real_type;
2359         si->protocol = protocol;
2360
2361         /*
2362          * Setup myname so getsockname() can succeed to find out the socket
2363          * type.
2364          */
2365         switch(si->family) {
2366         case AF_INET: {
2367                 struct sockaddr_in sin = {
2368                         .sin_family = AF_INET,
2369                 };
2370
2371                 si->myname_len = sizeof(struct sockaddr_in);
2372                 si->myname = sockaddr_dup(&sin, si->myname_len);
2373                 break;
2374         }
2375         case AF_INET6: {
2376                 struct sockaddr_in6 sin6 = {
2377                         .sin6_family = AF_INET6,
2378                 };
2379
2380                 si->myname_len = sizeof(struct sockaddr_in6);
2381                 si->myname = sockaddr_dup(&sin6, si->myname_len);
2382                 break;
2383         }
2384         default:
2385                 free(si);
2386                 errno = EINVAL;
2387                 return -1;
2388         }
2389
2390         fi = (struct socket_info_fd *)calloc(1, sizeof(struct socket_info_fd));
2391         if (fi == NULL) {
2392                 if (si->myname != NULL) {
2393                         free (si->myname);
2394                 }
2395                 free(si);
2396                 errno = ENOMEM;
2397                 return -1;
2398         }
2399
2400         fi->fd = fd;
2401
2402         SWRAP_DLIST_ADD(si->fds, fi);
2403         SWRAP_DLIST_ADD(sockets, si);
2404
2405         return fd;
2406 }
2407
2408 int socket(int family, int type, int protocol)
2409 {
2410         return swrap_socket(family, type, protocol);
2411 }
2412
2413 /****************************************************************************
2414  *   SOCKETPAIR
2415  ***************************************************************************/
2416
2417 static int swrap_socketpair(int family, int type, int protocol, int sv[2])
2418 {
2419         int rc;
2420
2421         rc = libc_socketpair(family, type, protocol, sv);
2422         if (rc != -1) {
2423                 swrap_remove_stale(sv[0]);
2424                 swrap_remove_stale(sv[1]);
2425         }
2426
2427         return rc;
2428 }
2429
2430 int socketpair(int family, int type, int protocol, int sv[2])
2431 {
2432         return swrap_socketpair(family, type, protocol, sv);
2433 }
2434
2435 /****************************************************************************
2436  *   SOCKETPAIR
2437  ***************************************************************************/
2438
2439 #ifdef HAVE_TIMERFD_CREATE
2440 static int swrap_timerfd_create(int clockid, int flags)
2441 {
2442         int fd;
2443
2444         fd = libc_timerfd_create(clockid, flags);
2445         if (fd != -1) {
2446                 swrap_remove_stale(fd);
2447         }
2448
2449         return fd;
2450 }
2451
2452 int timerfd_create(int clockid, int flags)
2453 {
2454         return swrap_timerfd_create(clockid, flags);
2455 }
2456 #endif
2457
2458 /****************************************************************************
2459  *   PIPE
2460  ***************************************************************************/
2461
2462 static int swrap_pipe(int pipefd[2])
2463 {
2464         int rc;
2465
2466         rc = libc_pipe(pipefd);
2467         if (rc != -1) {
2468                 swrap_remove_stale(pipefd[0]);
2469                 swrap_remove_stale(pipefd[1]);
2470         }
2471
2472         return rc;
2473 }
2474
2475 int pipe(int pipefd[2])
2476 {
2477         return swrap_pipe(pipefd);
2478 }
2479
2480 /****************************************************************************
2481  *   ACCEPT
2482  ***************************************************************************/
2483
2484 static int swrap_accept(int s, struct sockaddr *addr, socklen_t *addrlen)
2485 {
2486         struct socket_info *parent_si, *child_si;
2487         struct socket_info_fd *child_fi;
2488         int fd;
2489         struct swrap_address un_addr = {
2490                 .sa_socklen = sizeof(struct sockaddr_un),
2491         };
2492         struct swrap_address un_my_addr = {
2493                 .sa_socklen = sizeof(struct sockaddr_un),
2494         };
2495         struct sockaddr *my_addr;
2496         socklen_t my_addrlen, len;
2497         int ret;
2498
2499         parent_si = find_socket_info(s);
2500         if (!parent_si) {
2501                 return libc_accept(s, addr, addrlen);
2502         }
2503
2504         /* 
2505          * assume out sockaddr have the same size as the in parent
2506          * socket family
2507          */
2508         my_addrlen = socket_length(parent_si->family);
2509         if (my_addrlen <= 0) {
2510                 errno = EINVAL;
2511                 return -1;
2512         }
2513
2514         my_addr = (struct sockaddr *)malloc(my_addrlen);
2515         if (my_addr == NULL) {
2516                 return -1;
2517         }
2518
2519         ret = libc_accept(s, &un_addr.sa.s, &un_addr.sa_socklen);
2520         if (ret == -1) {
2521                 if (errno == ENOTSOCK) {
2522                         /* Remove stale fds */
2523                         swrap_remove_stale(s);
2524                 }
2525                 free(my_addr);
2526                 return ret;
2527         }
2528
2529         fd = ret;
2530
2531         len = my_addrlen;
2532         ret = sockaddr_convert_from_un(parent_si,
2533                                        &un_addr.sa.un,
2534                                        un_addr.sa_socklen,
2535                                        parent_si->family,
2536                                        my_addr,
2537                                        &len);
2538         if (ret == -1) {
2539                 free(my_addr);
2540                 close(fd);
2541                 return ret;
2542         }
2543
2544         child_si = (struct socket_info *)malloc(sizeof(struct socket_info));
2545         memset(child_si, 0, sizeof(struct socket_info));
2546
2547         child_fi = (struct socket_info_fd *)calloc(1, sizeof(struct socket_info_fd));
2548         if (child_fi == NULL) {
2549                 free(child_si);
2550                 free(my_addr);
2551                 close(fd);
2552                 errno = ENOMEM;
2553                 return -1;
2554         }
2555
2556         child_fi->fd = fd;
2557
2558         SWRAP_DLIST_ADD(child_si->fds, child_fi);
2559
2560         child_si->family = parent_si->family;
2561         child_si->type = parent_si->type;
2562         child_si->protocol = parent_si->protocol;
2563         child_si->bound = 1;
2564         child_si->is_server = 1;
2565         child_si->connected = 1;
2566
2567         child_si->peername_len = len;
2568         child_si->peername = sockaddr_dup(my_addr, len);
2569
2570         if (addr != NULL && addrlen != NULL) {
2571                 size_t copy_len = MIN(*addrlen, len);
2572                 if (copy_len > 0) {
2573                         memcpy(addr, my_addr, copy_len);
2574                 }
2575                 *addrlen = len;
2576         }
2577
2578         ret = libc_getsockname(fd,
2579                                &un_my_addr.sa.s,
2580                                &un_my_addr.sa_socklen);
2581         if (ret == -1) {
2582                 free(child_fi);
2583                 free(child_si);
2584                 free(my_addr);
2585                 close(fd);
2586                 return ret;
2587         }
2588
2589         len = my_addrlen;
2590         ret = sockaddr_convert_from_un(child_si,
2591                                        &un_my_addr.sa.un,
2592                                        un_my_addr.sa_socklen,
2593                                        child_si->family,
2594                                        my_addr,
2595                                        &len);
2596         if (ret == -1) {
2597                 free(child_fi);
2598                 free(child_si);
2599                 free(my_addr);
2600                 close(fd);
2601                 return ret;
2602         }
2603
2604         SWRAP_LOG(SWRAP_LOG_TRACE,
2605                   "accept() path=%s, fd=%d",
2606                   un_my_addr.sa.un.sun_path, s);
2607
2608         child_si->myname_len = len;
2609         child_si->myname = sockaddr_dup(my_addr, len);
2610         free(my_addr);
2611
2612         SWRAP_DLIST_ADD(sockets, child_si);
2613
2614         if (addr != NULL) {
2615                 swrap_dump_packet(child_si, addr, SWRAP_ACCEPT_SEND, NULL, 0);
2616                 swrap_dump_packet(child_si, addr, SWRAP_ACCEPT_RECV, NULL, 0);
2617                 swrap_dump_packet(child_si, addr, SWRAP_ACCEPT_ACK, NULL, 0);
2618         }
2619
2620         return fd;
2621 }
2622
2623 #ifdef HAVE_ACCEPT_PSOCKLEN_T
2624 int accept(int s, struct sockaddr *addr, Psocklen_t addrlen)
2625 #else
2626 int accept(int s, struct sockaddr *addr, socklen_t *addrlen)
2627 #endif
2628 {
2629         return swrap_accept(s, addr, (socklen_t *)addrlen);
2630 }
2631
2632 static int autobind_start_init;
2633 static int autobind_start;
2634
2635 /* using sendto() or connect() on an unbound socket would give the
2636    recipient no way to reply, as unlike UDP and TCP, a unix domain
2637    socket can't auto-assign ephemeral port numbers, so we need to
2638    assign it here.
2639    Note: this might change the family from ipv6 to ipv4
2640 */
2641 static int swrap_auto_bind(int fd, struct socket_info *si, int family)
2642 {
2643         struct swrap_address un_addr = {
2644                 .sa_socklen = sizeof(struct sockaddr_un),
2645         };
2646         int i;
2647         char type;
2648         int ret;
2649         int port;
2650         struct stat st;
2651
2652         if (autobind_start_init != 1) {
2653                 autobind_start_init = 1;
2654                 autobind_start = getpid();
2655                 autobind_start %= 50000;
2656                 autobind_start += 10000;
2657         }
2658
2659         un_addr.sa.un.sun_family = AF_UNIX;
2660
2661         switch (family) {
2662         case AF_INET: {
2663                 struct sockaddr_in in;
2664
2665                 switch (si->type) {
2666                 case SOCK_STREAM:
2667                         type = SOCKET_TYPE_CHAR_TCP;
2668                         break;
2669                 case SOCK_DGRAM:
2670                         type = SOCKET_TYPE_CHAR_UDP;
2671                         break;
2672                 default:
2673                     errno = ESOCKTNOSUPPORT;
2674                     return -1;
2675                 }
2676
2677                 memset(&in, 0, sizeof(in));
2678                 in.sin_family = AF_INET;
2679                 in.sin_addr.s_addr = htonl(127<<24 | 
2680                                            socket_wrapper_default_iface());
2681
2682                 free(si->myname);
2683                 si->myname_len = sizeof(in);
2684                 si->myname = sockaddr_dup(&in, si->myname_len);
2685                 break;
2686         }
2687 #ifdef HAVE_IPV6
2688         case AF_INET6: {
2689                 struct sockaddr_in6 in6;
2690
2691                 if (si->family != family) {
2692                         errno = ENETUNREACH;
2693                         return -1;
2694                 }
2695
2696                 switch (si->type) {
2697                 case SOCK_STREAM:
2698                         type = SOCKET_TYPE_CHAR_TCP_V6;
2699                         break;
2700                 case SOCK_DGRAM:
2701                         type = SOCKET_TYPE_CHAR_UDP_V6;
2702                         break;
2703                 default:
2704                         errno = ESOCKTNOSUPPORT;
2705                         return -1;
2706                 }
2707
2708                 memset(&in6, 0, sizeof(in6));
2709                 in6.sin6_family = AF_INET6;
2710                 in6.sin6_addr = *swrap_ipv6();
2711                 in6.sin6_addr.s6_addr[15] = socket_wrapper_default_iface();
2712                 free(si->myname);
2713                 si->myname_len = sizeof(in6);
2714                 si->myname = sockaddr_dup(&in6, si->myname_len);
2715                 break;
2716         }
2717 #endif
2718         default:
2719                 errno = ESOCKTNOSUPPORT;
2720                 return -1;
2721         }
2722
2723         if (autobind_start > 60000) {
2724                 autobind_start = 10000;
2725         }
2726
2727         for (i = 0; i < SOCKET_MAX_SOCKETS; i++) {
2728                 port = autobind_start + i;
2729                 snprintf(un_addr.sa.un.sun_path, un_addr.sa_socklen,
2730                          "%s/"SOCKET_FORMAT, socket_wrapper_dir(),
2731                          type, socket_wrapper_default_iface(), port);
2732                 if (stat(un_addr.sa.un.sun_path, &st) == 0) continue;
2733
2734                 ret = libc_bind(fd, &un_addr.sa.s, un_addr.sa_socklen);
2735                 if (ret == -1) return ret;
2736
2737                 si->tmp_path = strdup(un_addr.sa.un.sun_path);
2738                 si->bound = 1;
2739                 autobind_start = port + 1;
2740                 break;
2741         }
2742         if (i == SOCKET_MAX_SOCKETS) {
2743                 SWRAP_LOG(SWRAP_LOG_ERROR, "Too many open unix sockets (%u) for "
2744                                            "interface "SOCKET_FORMAT,
2745                                            SOCKET_MAX_SOCKETS,
2746                                            type,
2747                                            socket_wrapper_default_iface(),
2748                                            0);
2749                 errno = ENFILE;
2750                 return -1;
2751         }
2752
2753         si->family = family;
2754         set_port(si->family, port, si->myname);
2755
2756         return 0;
2757 }
2758
2759 /****************************************************************************
2760  *   CONNECT
2761  ***************************************************************************/
2762
2763 static int swrap_connect(int s, const struct sockaddr *serv_addr,
2764                          socklen_t addrlen)
2765 {
2766         int ret;
2767         struct swrap_address un_addr = {
2768                 .sa_socklen = sizeof(struct sockaddr_un),
2769         };
2770         struct socket_info *si = find_socket_info(s);
2771         int bcast = 0;
2772
2773         if (!si) {
2774                 return libc_connect(s, serv_addr, addrlen);
2775         }
2776
2777         if (si->bound == 0) {
2778                 ret = swrap_auto_bind(s, si, serv_addr->sa_family);
2779                 if (ret == -1) return -1;
2780         }
2781
2782         if (si->family != serv_addr->sa_family) {
2783                 errno = EINVAL;
2784                 return -1;
2785         }
2786
2787         ret = sockaddr_convert_to_un(si, serv_addr,
2788                                      addrlen, &un_addr.sa.un, 0, &bcast);
2789         if (ret == -1) return -1;
2790
2791         if (bcast) {
2792                 errno = ENETUNREACH;
2793                 return -1;
2794         }
2795
2796         if (si->type == SOCK_DGRAM) {
2797                 si->defer_connect = 1;
2798                 ret = 0;
2799         } else {
2800                 swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_SEND, NULL, 0);
2801
2802                 ret = libc_connect(s,
2803                                    &un_addr.sa.s,
2804                                    un_addr.sa_socklen);
2805         }
2806
2807         SWRAP_LOG(SWRAP_LOG_TRACE,
2808                   "connect() path=%s, fd=%d",
2809                   un_addr.un.sun_path, s);
2810
2811
2812         /* to give better errors */
2813         if (ret == -1 && errno == ENOENT) {
2814                 errno = EHOSTUNREACH;
2815         }
2816
2817         if (ret == 0) {
2818                 si->peername_len = addrlen;
2819                 si->peername = sockaddr_dup(serv_addr, addrlen);
2820                 si->connected = 1;
2821
2822                 /*
2823                  * When we connect() on a socket than we have to bind the
2824                  * outgoing connection on the interface we use for the
2825                  * transport. We already bound it on the right interface
2826                  * but here we have to update the name so getsockname()
2827                  * returns correct information.
2828                  */
2829                 if (si->bindname != NULL) {
2830                         free(si->myname);
2831
2832                         si->myname = si->bindname;
2833                         si->myname_len = si->bindname_len;
2834
2835                         si->bindname = NULL;
2836                         si->bindname_len = 0;
2837                 }
2838
2839                 swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_RECV, NULL, 0);
2840                 swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_ACK, NULL, 0);
2841         } else {
2842                 swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_UNREACH, NULL, 0);
2843         }
2844
2845         return ret;
2846 }
2847
2848 int connect(int s, const struct sockaddr *serv_addr, socklen_t addrlen)
2849 {
2850         return swrap_connect(s, serv_addr, addrlen);
2851 }
2852
2853 /****************************************************************************
2854  *   BIND
2855  ***************************************************************************/
2856
2857 static int swrap_bind(int s, const struct sockaddr *myaddr, socklen_t addrlen)
2858 {
2859         int ret;
2860         struct swrap_address un_addr = {
2861                 .sa_socklen = sizeof(struct sockaddr_un),
2862         };
2863         struct socket_info *si = find_socket_info(s);
2864         int bind_error = 0;
2865 #if 0 /* FIXME */
2866         bool in_use;
2867 #endif
2868
2869         if (!si) {
2870                 return libc_bind(s, myaddr, addrlen);
2871         }
2872
2873         switch (si->family) {
2874         case AF_INET: {
2875                 const struct sockaddr_in *sin;
2876                 if (addrlen < sizeof(struct sockaddr_in)) {
2877                         bind_error = EINVAL;
2878                         break;
2879                 }
2880
2881                 sin = (const struct sockaddr_in *)myaddr;
2882
2883                 if (sin->sin_family != AF_INET) {
2884                         bind_error = EAFNOSUPPORT;
2885                 }
2886
2887                 /* special case for AF_UNSPEC */
2888                 if (sin->sin_family == AF_UNSPEC &&
2889                     (sin->sin_addr.s_addr == htonl(INADDR_ANY)))
2890                 {
2891                         bind_error = 0;
2892                 }
2893
2894                 break;
2895         }
2896 #ifdef HAVE_IPV6
2897         case AF_INET6: {
2898                 const struct sockaddr_in6 *sin6;
2899                 if (addrlen < sizeof(struct sockaddr_in6)) {
2900                         bind_error = EINVAL;
2901                         break;
2902                 }
2903
2904                 sin6 = (const struct sockaddr_in6 *)myaddr;
2905
2906                 if (sin6->sin6_family != AF_INET6) {
2907                         bind_error = EAFNOSUPPORT;
2908                 }
2909
2910                 break;
2911         }
2912 #endif
2913         default:
2914                 bind_error = EINVAL;
2915                 break;
2916         }
2917
2918         if (bind_error != 0) {
2919                 errno = bind_error;
2920                 return -1;
2921         }
2922
2923 #if 0 /* FIXME */
2924         in_use = check_addr_port_in_use(myaddr, addrlen);
2925         if (in_use) {
2926                 errno = EADDRINUSE;
2927                 return -1;
2928         }
2929 #endif
2930
2931         free(si->myname);
2932         si->myname_len = addrlen;
2933         si->myname = sockaddr_dup(myaddr, addrlen);
2934
2935         ret = sockaddr_convert_to_un(si,
2936                                      myaddr,
2937                                      addrlen,
2938                                      &un_addr.sa.un,
2939                                      1,
2940                                      &si->bcast);
2941         if (ret == -1) return -1;
2942
2943         unlink(un_addr.sa.un.sun_path);
2944
2945         ret = libc_bind(s, &un_addr.sa.s, un_addr.sa_socklen);
2946
2947         SWRAP_LOG(SWRAP_LOG_TRACE,
2948                   "bind() path=%s, fd=%d",
2949                   un_addr.sa_un.sun_path, s);
2950
2951         if (ret == 0) {
2952                 si->bound = 1;
2953         }
2954
2955         return ret;
2956 }
2957
2958 int bind(int s, const struct sockaddr *myaddr, socklen_t addrlen)
2959 {
2960         return swrap_bind(s, myaddr, addrlen);
2961 }
2962
2963 /****************************************************************************
2964  *   BINDRESVPORT
2965  ***************************************************************************/
2966
2967 #ifdef HAVE_BINDRESVPORT
2968 static int swrap_getsockname(int s, struct sockaddr *name, socklen_t *addrlen);
2969
2970 static int swrap_bindresvport_sa(int sd, struct sockaddr *sa)
2971 {
2972         struct swrap_address myaddr = {
2973                 .sa_socklen = sizeof(struct sockaddr_storage),
2974         };
2975         socklen_t salen;
2976         static uint16_t port;
2977         uint16_t i;
2978         int rc = -1;
2979         int af;
2980
2981 #define SWRAP_STARTPORT 600
2982 #define SWRAP_ENDPORT (IPPORT_RESERVED - 1)
2983 #define SWRAP_NPORTS (SWRAP_ENDPORT - SWRAP_STARTPORT + 1)
2984
2985         if (port == 0) {
2986                 port = (getpid() % SWRAP_NPORTS) + SWRAP_STARTPORT;
2987         }
2988
2989         if (sa == NULL) {
2990                 salen = myaddr.sa_socklen;
2991                 sa = &myaddr.sa.s;
2992
2993                 rc = swrap_getsockname(sd, &myaddr.sa.s, &salen);
2994                 if (rc < 0) {
2995                         return -1;
2996                 }
2997
2998                 af = sa->sa_family;
2999                 memset(&myaddr.sa.ss, 0, salen);
3000         } else {
3001                 af = sa->sa_family;
3002         }
3003
3004         for (i = 0; i < SWRAP_NPORTS; i++, port++) {
3005                 switch(af) {
3006                 case AF_INET: {
3007                         struct sockaddr_in *sinp = (struct sockaddr_in *)(void *)sa;
3008
3009                         salen = sizeof(struct sockaddr_in);
3010                         sinp->sin_port = htons(port);
3011                         break;
3012                 }
3013                 case AF_INET6: {
3014                         struct sockaddr_in6 *sin6p = (struct sockaddr_in6 *)sa;
3015
3016                         salen = sizeof(struct sockaddr_in6);
3017                         sin6p->sin6_port = htons(port);
3018                         break;
3019                 }
3020                 default:
3021                         errno = EAFNOSUPPORT;
3022                         return -1;
3023                 }
3024                 sa->sa_family = af;
3025
3026                 if (port > SWRAP_ENDPORT) {
3027                         port = SWRAP_STARTPORT;
3028                 }
3029
3030                 rc = swrap_bind(sd, (struct sockaddr *)sa, salen);
3031                 if (rc == 0 || errno != EADDRINUSE) {
3032                         break;
3033                 }
3034         }
3035
3036         return rc;
3037 }
3038
3039 int bindresvport(int sockfd, struct sockaddr_in *sinp)
3040 {
3041         return swrap_bindresvport_sa(sockfd, (struct sockaddr *)sinp);
3042 }
3043 #endif
3044
3045 /****************************************************************************
3046  *   LISTEN
3047  ***************************************************************************/
3048
3049 static int swrap_listen(int s, int backlog)
3050 {
3051         int ret;
3052         struct socket_info *si = find_socket_info(s);
3053
3054         if (!si) {
3055                 return libc_listen(s, backlog);
3056         }
3057
3058         ret = libc_listen(s, backlog);
3059
3060         return ret;
3061 }
3062
3063 int listen(int s, int backlog)
3064 {
3065         return swrap_listen(s, backlog);
3066 }
3067
3068 /****************************************************************************
3069  *   OPEN
3070  ***************************************************************************/
3071
3072 static int swrap_vopen(const char *pathname, int flags, va_list ap)
3073 {
3074         int ret;
3075