socket_wrapper: pass down sockaddr instead of sockaddr_in to prepare pcap support...
[jra/samba/.git] / lib / socket_wrapper / socket_wrapper.c
1 /*
2  * Copyright (C) Jelmer Vernooij 2005,2008 <jelmer@samba.org>
3  * Copyright (C) Stefan Metzmacher 2006 <metze@samba.org>
4  *
5  * All rights reserved.
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 
18  * 3. Neither the name of the author nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  * 
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  */
35
36 /*
37    Socket wrapper library. Passes all socket communication over
38    unix domain sockets if the environment variable SOCKET_WRAPPER_DIR
39    is set.
40 */
41
42 #ifdef _SAMBA_BUILD_
43
44 #define SOCKET_WRAPPER_NOT_REPLACE
45 #include "../replace/replace.h"
46 #include "system/network.h"
47 #include "system/filesys.h"
48 #include "system/time.h"
49
50 #else /* _SAMBA_BUILD_ */
51
52 #include <sys/types.h>
53 #include <sys/time.h>
54 #include <sys/stat.h>
55 #include <sys/socket.h>
56 #include <sys/ioctl.h>
57 #include <sys/filio.h>
58 #include <errno.h>
59 #include <sys/un.h>
60 #include <netinet/in.h>
61 #include <netinet/tcp.h>
62 #include <fcntl.h>
63 #include <stdlib.h>
64 #include <unistd.h>
65 #include <string.h>
66 #include <stdio.h>
67 #include <stdint.h>
68
69 #endif
70
71 #ifndef _PUBLIC_
72 #define _PUBLIC_
73 #endif
74
75 #define SWRAP_DLIST_ADD(list,item) do { \
76         if (!(list)) { \
77                 (item)->prev    = NULL; \
78                 (item)->next    = NULL; \
79                 (list)          = (item); \
80         } else { \
81                 (item)->prev    = NULL; \
82                 (item)->next    = (list); \
83                 (list)->prev    = (item); \
84                 (list)          = (item); \
85         } \
86 } while (0)
87
88 #define SWRAP_DLIST_REMOVE(list,item) do { \
89         if ((list) == (item)) { \
90                 (list)          = (item)->next; \
91                 if (list) { \
92                         (list)->prev    = NULL; \
93                 } \
94         } else { \
95                 if ((item)->prev) { \
96                         (item)->prev->next      = (item)->next; \
97                 } \
98                 if ((item)->next) { \
99                         (item)->next->prev      = (item)->prev; \
100                 } \
101         } \
102         (item)->prev    = NULL; \
103         (item)->next    = NULL; \
104 } while (0)
105
106 /* LD_PRELOAD doesn't work yet, so REWRITE_CALLS is all we support
107  * for now */
108 #define REWRITE_CALLS 
109
110 #ifdef REWRITE_CALLS
111 #define real_accept accept
112 #define real_connect connect
113 #define real_bind bind
114 #define real_listen listen
115 #define real_getpeername getpeername
116 #define real_getsockname getsockname
117 #define real_getsockopt getsockopt
118 #define real_setsockopt setsockopt
119 #define real_recvfrom recvfrom
120 #define real_sendto sendto
121 #define real_ioctl ioctl
122 #define real_recv recv
123 #define real_send send
124 #define real_socket socket
125 #define real_close close
126 #endif
127
128 #ifdef HAVE_GETTIMEOFDAY_TZ
129 #define swrapGetTimeOfDay(tval) gettimeofday(tval,NULL)
130 #else
131 #define swrapGetTimeOfDay(tval) gettimeofday(tval)
132 #endif
133
134 /* we need to use a very terse format here as IRIX 6.4 silently
135    truncates names to 16 chars, so if we use a longer name then we
136    can't tell which port a packet came from with recvfrom() 
137    
138    with this format we have 8 chars left for the directory name
139 */
140 #define SOCKET_FORMAT "%c%02X%04X"
141 #define SOCKET_TYPE_CHAR_TCP            'T'
142 #define SOCKET_TYPE_CHAR_UDP            'U'
143 #define SOCKET_TYPE_CHAR_TCP_V6         'X'
144 #define SOCKET_TYPE_CHAR_UDP_V6         'Y'
145
146 #define MAX_WRAPPED_INTERFACES 16
147
148 #define SW_IPV6_ADDRESS 1
149
150 static struct sockaddr *sockaddr_dup(const void *data, socklen_t len)
151 {
152         struct sockaddr *ret = (struct sockaddr *)malloc(len);
153         memcpy(ret, data, len);
154         return ret;
155 }
156
157 static void set_port(int family, int prt, struct sockaddr *addr)
158 {
159         switch (family) {
160         case AF_INET:
161                 ((struct sockaddr_in *)addr)->sin_port = htons(prt);
162                 break;
163 #ifdef HAVE_IPV6
164         case AF_INET6:
165                 ((struct sockaddr_in6 *)addr)->sin6_port = htons(prt);
166                 break;
167 #endif
168         }
169 }
170
171 static size_t socket_length(int family)
172 {
173         switch (family) {
174         case AF_INET:
175                 return sizeof(struct sockaddr_in);
176 #ifdef HAVE_IPV6
177         case AF_INET6:
178                 return sizeof(struct sockaddr_in6);
179 #endif
180         }
181         return 0;
182 }
183
184
185
186 struct socket_info
187 {
188         int fd;
189
190         int family;
191         int type;
192         int protocol;
193         int bound;
194         int bcast;
195         int is_server;
196
197         char *path;
198         char *tmp_path;
199
200         struct sockaddr *myname;
201         socklen_t myname_len;
202
203         struct sockaddr *peername;
204         socklen_t peername_len;
205
206         struct {
207                 unsigned long pck_snd;
208                 unsigned long pck_rcv;
209         } io;
210
211         struct socket_info *prev, *next;
212 };
213
214 static struct socket_info *sockets;
215
216 const char *socket_wrapper_dir(void)
217 {
218         const char *s = getenv("SOCKET_WRAPPER_DIR");
219         if (s == NULL) {
220                 return NULL;
221         }
222         if (strncmp(s, "./", 2) == 0) {
223                 s += 2;
224         }
225         return s;
226 }
227
228 unsigned int socket_wrapper_default_iface(void)
229 {
230         const char *s = getenv("SOCKET_WRAPPER_DEFAULT_IFACE");
231         if (s) {
232                 unsigned int iface;
233                 if (sscanf(s, "%u", &iface) == 1) {
234                         if (iface >= 1 && iface <= MAX_WRAPPED_INTERFACES) {
235                                 return iface;
236                         }
237                 }
238         }
239
240         return 1;/* 127.0.0.1 */
241 }
242
243 static int convert_un_in(const struct sockaddr_un *un, struct sockaddr *in, socklen_t *len)
244 {
245         unsigned int iface;
246         unsigned int prt;
247         const char *p;
248         char type;
249
250         p = strrchr(un->sun_path, '/');
251         if (p) p++; else p = un->sun_path;
252
253         if (sscanf(p, SOCKET_FORMAT, &type, &iface, &prt) != 3) {
254                 errno = EINVAL;
255                 return -1;
256         }
257
258         if (iface == 0 || iface > MAX_WRAPPED_INTERFACES) {
259                 errno = EINVAL;
260                 return -1;
261         }
262
263         if (prt > 0xFFFF) {
264                 errno = EINVAL;
265                 return -1;
266         }
267
268         switch(type) {
269         case SOCKET_TYPE_CHAR_TCP:
270         case SOCKET_TYPE_CHAR_UDP: {
271                 struct sockaddr_in *in2 = (struct sockaddr_in *)in;
272                 
273                 if ((*len) < sizeof(*in2)) {
274                     errno = EINVAL;
275                     return -1;
276                 }
277
278                 memset(in2, 0, sizeof(*in2));
279                 in2->sin_family = AF_INET;
280                 in2->sin_addr.s_addr = htonl((127<<24) | iface);
281                 in2->sin_port = htons(prt);
282
283                 *len = sizeof(*in2);
284                 break;
285         }
286 #ifdef HAVE_IPV6
287         case SOCKET_TYPE_CHAR_TCP_V6:
288         case SOCKET_TYPE_CHAR_UDP_V6: {
289                 struct sockaddr_in6 *in2 = (struct sockaddr_in6 *)in;
290                 
291                 if ((*len) < sizeof(*in2)) {
292                         errno = EINVAL;
293                         return -1;
294                 }
295
296                 memset(in2, 0, sizeof(*in2));
297                 in2->sin6_family = AF_INET6;
298                 in2->sin6_addr.s6_addr[0] = SW_IPV6_ADDRESS;
299                 in2->sin6_port = htons(prt);
300
301                 *len = sizeof(*in2);
302                 break;
303         }
304 #endif
305         default:
306                 errno = EINVAL;
307                 return -1;
308         }
309
310         return 0;
311 }
312
313 static int convert_in_un_remote(struct socket_info *si, const struct sockaddr *inaddr, struct sockaddr_un *un,
314                                 int *bcast)
315 {
316         char type = '\0';
317         unsigned int prt;
318         unsigned int iface;
319         int is_bcast = 0;
320
321         if (bcast) *bcast = 0;
322
323         switch (si->family) {
324         case AF_INET: {
325                 const struct sockaddr_in *in = 
326                     (const struct sockaddr_in *)inaddr;
327                 unsigned int addr = ntohl(in->sin_addr.s_addr);
328                 char u_type = '\0';
329                 char b_type = '\0';
330                 char a_type = '\0';
331
332                 switch (si->type) {
333                 case SOCK_STREAM:
334                         u_type = SOCKET_TYPE_CHAR_TCP;
335                         break;
336                 case SOCK_DGRAM:
337                         u_type = SOCKET_TYPE_CHAR_UDP;
338                         a_type = SOCKET_TYPE_CHAR_UDP;
339                         b_type = SOCKET_TYPE_CHAR_UDP;
340                         break;
341                 }
342
343                 prt = ntohs(in->sin_port);
344                 if (a_type && addr == 0xFFFFFFFF) {
345                         /* 255.255.255.255 only udp */
346                         is_bcast = 2;
347                         type = a_type;
348                         iface = socket_wrapper_default_iface();
349                 } else if (b_type && addr == 0x7FFFFFFF) {
350                         /* 127.255.255.255 only udp */
351                         is_bcast = 1;
352                         type = b_type;
353                         iface = socket_wrapper_default_iface();
354                 } else if ((addr & 0xFFFFFF00) == 0x7F000000) {
355                         /* 127.0.0.X */
356                         is_bcast = 0;
357                         type = u_type;
358                         iface = (addr & 0x000000FF);
359                 } else {
360                         errno = ENETUNREACH;
361                         return -1;
362                 }
363                 if (bcast) *bcast = is_bcast;
364                 break;
365         }
366 #ifdef HAVE_IPV6
367         case AF_INET6: {
368                 const struct sockaddr_in6 *in = 
369                     (const struct sockaddr_in6 *)inaddr;
370
371                 switch (si->type) {
372                 case SOCK_STREAM:
373                         type = SOCKET_TYPE_CHAR_TCP_V6;
374                         break;
375                 case SOCK_DGRAM:
376                         type = SOCKET_TYPE_CHAR_UDP_V6;
377                         break;
378                 }
379
380                 /* XXX no multicast/broadcast */
381
382                 prt = ntohs(in->sin6_port);
383                 iface = SW_IPV6_ADDRESS;
384                 
385                 break;
386         }
387 #endif
388         default:
389                 errno = ENETUNREACH;
390                 return -1;
391         }
392
393         if (prt == 0) {
394                 errno = EINVAL;
395                 return -1;
396         }
397
398         if (is_bcast) {
399                 snprintf(un->sun_path, sizeof(un->sun_path), "%s/EINVAL", 
400                          socket_wrapper_dir());
401                 /* the caller need to do more processing */
402                 return 0;
403         }
404
405         snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT, 
406                  socket_wrapper_dir(), type, iface, prt);
407
408         return 0;
409 }
410
411 static int convert_in_un_alloc(struct socket_info *si, const struct sockaddr *inaddr, struct sockaddr_un *un,
412                                int *bcast)
413 {
414         char type = '\0';
415         unsigned int prt;
416         unsigned int iface;
417         struct stat st;
418         int is_bcast = 0;
419
420         if (bcast) *bcast = 0;
421
422         switch (si->family) {
423         case AF_INET: {
424                 const struct sockaddr_in *in = 
425                     (const struct sockaddr_in *)inaddr;
426                 unsigned int addr = ntohl(in->sin_addr.s_addr);
427                 char u_type = '\0';
428                 char d_type = '\0';
429                 char b_type = '\0';
430                 char a_type = '\0';
431
432                 prt = ntohs(in->sin_port);
433
434                 switch (si->type) {
435                 case SOCK_STREAM:
436                         u_type = SOCKET_TYPE_CHAR_TCP;
437                         d_type = SOCKET_TYPE_CHAR_TCP;
438                         break;
439                 case SOCK_DGRAM:
440                         u_type = SOCKET_TYPE_CHAR_UDP;
441                         d_type = SOCKET_TYPE_CHAR_UDP;
442                         a_type = SOCKET_TYPE_CHAR_UDP;
443                         b_type = SOCKET_TYPE_CHAR_UDP;
444                         break;
445                 }
446
447                 if (addr == 0) {
448                         /* 0.0.0.0 */
449                         is_bcast = 0;
450                         type = d_type;
451                         iface = socket_wrapper_default_iface();
452                 } else if (a_type && addr == 0xFFFFFFFF) {
453                         /* 255.255.255.255 only udp */
454                         is_bcast = 2;
455                         type = a_type;
456                         iface = socket_wrapper_default_iface();
457                 } else if (b_type && addr == 0x7FFFFFFF) {
458                         /* 127.255.255.255 only udp */
459                         is_bcast = 1;
460                         type = b_type;
461                         iface = socket_wrapper_default_iface();
462                 } else if ((addr & 0xFFFFFF00) == 0x7F000000) {
463                         /* 127.0.0.X */
464                         is_bcast = 0;
465                         type = u_type;
466                         iface = (addr & 0x000000FF);
467                 } else {
468                         errno = EADDRNOTAVAIL;
469                         return -1;
470                 }
471                 break;
472         }
473 #ifdef HAVE_IPV6
474         case AF_INET6: {
475                 const struct sockaddr_in6 *in = 
476                     (const struct sockaddr_in6 *)inaddr;
477
478                 switch (si->type) {
479                 case SOCK_STREAM:
480                         type = SOCKET_TYPE_CHAR_TCP_V6;
481                         break;
482                 case SOCK_DGRAM:
483                         type = SOCKET_TYPE_CHAR_UDP_V6;
484                         break;
485                 }
486
487                 /* XXX no multicast/broadcast */
488
489                 prt = ntohs(in->sin6_port);
490                 iface = SW_IPV6_ADDRESS;
491                 
492                 break;
493         }
494 #endif
495         default:
496                 errno = ENETUNREACH;
497                 return -1;
498         }
499
500
501         if (bcast) *bcast = is_bcast;
502
503         if (prt == 0) {
504                 /* handle auto-allocation of ephemeral ports */
505                 for (prt = 5001; prt < 10000; prt++) {
506                         snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT, 
507                                  socket_wrapper_dir(), type, iface, prt);
508                         if (stat(un->sun_path, &st) == 0) continue;
509
510                         set_port(si->family, prt, si->myname);
511                         break;
512                 }
513                 if (prt == 10000) {
514                         errno = ENFILE;
515                         return -1;
516                 }
517         }
518
519         snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT, 
520                  socket_wrapper_dir(), type, iface, prt);
521         return 0;
522 }
523
524 static struct socket_info *find_socket_info(int fd)
525 {
526         struct socket_info *i;
527         for (i = sockets; i; i = i->next) {
528                 if (i->fd == fd) 
529                         return i;
530         }
531
532         return NULL;
533 }
534
535 static int sockaddr_convert_to_un(struct socket_info *si, const struct sockaddr *in_addr, socklen_t in_len, 
536                                   struct sockaddr_un *out_addr, int alloc_sock, int *bcast)
537 {
538         if (!out_addr)
539                 return 0;
540
541         out_addr->sun_family = AF_UNIX;
542
543         switch (in_addr->sa_family) {
544         case AF_INET:
545 #ifdef HAVE_IPV6
546         case AF_INET6:
547 #endif
548                 switch (si->type) {
549                 case SOCK_STREAM:
550                 case SOCK_DGRAM:
551                         break;
552                 default:
553                         errno = ESOCKTNOSUPPORT;
554                         return -1;
555                 }
556                 if (alloc_sock) {
557                         return convert_in_un_alloc(si, in_addr, out_addr, bcast);
558                 } else {
559                         return convert_in_un_remote(si, in_addr, out_addr, bcast);
560                 }
561         default:
562                 break;
563         }
564         
565         errno = EAFNOSUPPORT;
566         return -1;
567 }
568
569 static int sockaddr_convert_from_un(const struct socket_info *si, 
570                                     const struct sockaddr_un *in_addr, 
571                                     socklen_t un_addrlen,
572                                     int family,
573                                     struct sockaddr *out_addr,
574                                     socklen_t *out_addrlen)
575 {
576         if (out_addr == NULL || out_addrlen == NULL) 
577                 return 0;
578
579         if (un_addrlen == 0) {
580                 *out_addrlen = 0;
581                 return 0;
582         }
583
584         switch (family) {
585         case AF_INET:
586 #ifdef HAVE_IPV6
587         case AF_INET6:
588 #endif
589                 switch (si->type) {
590                 case SOCK_STREAM:
591                 case SOCK_DGRAM:
592                         break;
593                 default:
594                         errno = ESOCKTNOSUPPORT;
595                         return -1;
596                 }
597                 return convert_un_in(in_addr, out_addr, out_addrlen);
598         default:
599                 break;
600         }
601
602         errno = EAFNOSUPPORT;
603         return -1;
604 }
605
606 enum swrap_packet_type {
607         SWRAP_CONNECT_SEND,
608         SWRAP_CONNECT_UNREACH,
609         SWRAP_CONNECT_RECV,
610         SWRAP_CONNECT_ACK,
611         SWRAP_ACCEPT_SEND,
612         SWRAP_ACCEPT_RECV,
613         SWRAP_ACCEPT_ACK,
614         SWRAP_RECVFROM,
615         SWRAP_SENDTO,
616         SWRAP_SENDTO_UNREACH,
617         SWRAP_PENDING_RST,
618         SWRAP_RECV,
619         SWRAP_RECV_RST,
620         SWRAP_SEND,
621         SWRAP_SEND_RST,
622         SWRAP_CLOSE_SEND,
623         SWRAP_CLOSE_RECV,
624         SWRAP_CLOSE_ACK
625 };
626
627 struct swrap_file_hdr {
628         uint32_t        magic;
629         uint16_t        version_major;
630         uint16_t        version_minor;
631         int32_t         timezone;
632         uint32_t        sigfigs;
633         uint32_t        frame_max_len;
634 #define SWRAP_FRAME_LENGTH_MAX 0xFFFF
635         uint32_t        link_type;
636 };
637 #define SWRAP_FILE_HDR_SIZE 24
638
639 struct swrap_packet_frame {
640         uint32_t seconds;
641         uint32_t micro_seconds;
642         uint32_t recorded_length;
643         uint32_t full_length;
644 };
645 #define SWRAP_PACKET_FRAME_SIZE 16
646
647 union swrap_packet_ip {
648         struct {
649                 uint8_t         ver_hdrlen;
650                 uint8_t         tos;
651                 uint16_t        packet_length;
652                 uint16_t        identification;
653                 uint8_t         flags;
654                 uint8_t         fragment;
655                 uint8_t         ttl;
656                 uint8_t         protocol;
657                 uint16_t        hdr_checksum;
658                 uint32_t        src_addr;
659                 uint32_t        dest_addr;
660         } v4;
661 #define SWRAP_PACKET_IP_V4_SIZE 20
662 };
663 #define SWRAP_PACKET_IP_SIZE 20
664
665 union swrap_packet_payload {
666         struct {
667                 uint16_t        source_port;
668                 uint16_t        dest_port;
669                 uint32_t        seq_num;
670                 uint32_t        ack_num;
671                 uint8_t         hdr_length;
672                 uint8_t         control;
673                 uint16_t        window;
674                 uint16_t        checksum;
675                 uint16_t        urg;
676         } tcp;
677 #define SWRAP_PACKET_PAYLOAD_TCP_SIZE 20
678         struct {
679                 uint16_t        source_port;
680                 uint16_t        dest_port;
681                 uint16_t        length;
682                 uint16_t        checksum;
683         } udp;
684 #define SWRAP_PACKET_PAYLOAD_UDP_SIZE 8
685         struct {
686                 uint8_t         type;
687                 uint8_t         code;
688                 uint16_t        checksum;
689                 uint32_t        unused;
690         } icmp4;
691 #define SWRAP_PACKET_PAYLOAD_ICMP4_SIZE 8
692 };
693 #define SWRAP_PACKET_PAYLOAD_SIZE 20
694
695 #define SWRAP_PACKET_MIN_ALLOC \
696         (SWRAP_PACKET_FRAME_SIZE + \
697          SWRAP_PACKET_IP_SIZE + \
698          SWRAP_PACKET_PAYLOAD_SIZE)
699
700 static const char *socket_wrapper_pcap_file(void)
701 {
702         static int initialized = 0;
703         static const char *s = NULL;
704         static const struct swrap_file_hdr h;
705         static const struct swrap_packet_frame f;
706         static const union swrap_packet_ip i;
707         static const union swrap_packet_payload p;
708
709         if (initialized == 1) {
710                 return s;
711         }
712         initialized = 1;
713
714         /*
715          * TODO: don't use the structs use plain buffer offsets
716          *       and PUSH_U8(), PUSH_U16() and PUSH_U32()
717          * 
718          * for now make sure we disable PCAP support
719          * if the struct has alignment!
720          */
721         if (sizeof(h) != SWRAP_FILE_HDR_SIZE) {
722                 return NULL;
723         }
724         if (sizeof(f) != SWRAP_PACKET_FRAME_SIZE) {
725                 return NULL;
726         }
727         if (sizeof(i) != SWRAP_PACKET_IP_SIZE) {
728                 return NULL;
729         }
730         if (sizeof(i.v4) != SWRAP_PACKET_IP_V4_SIZE) {
731                 return NULL;
732         }
733         if (sizeof(p) != SWRAP_PACKET_PAYLOAD_SIZE) {
734                 return NULL;
735         }
736         if (sizeof(p.tcp) != SWRAP_PACKET_PAYLOAD_TCP_SIZE) {
737                 return NULL;
738         }
739         if (sizeof(p.udp) != SWRAP_PACKET_PAYLOAD_UDP_SIZE) {
740                 return NULL;
741         }
742         if (sizeof(p.icmp4) != SWRAP_PACKET_PAYLOAD_ICMP4_SIZE) {
743                 return NULL;
744         }
745
746         s = getenv("SOCKET_WRAPPER_PCAP_FILE");
747         if (s == NULL) {
748                 return NULL;
749         }
750         if (strncmp(s, "./", 2) == 0) {
751                 s += 2;
752         }
753         return s;
754 }
755
756 static uint8_t *swrap_packet_init(struct timeval *tval,
757                                   const struct sockaddr *src,
758                                   const struct sockaddr *dest,
759                                   int socket_type,
760                                   const uint8_t *payload,
761                                   size_t payload_len,
762                                   unsigned long tcp_seqno,
763                                   unsigned long tcp_ack,
764                                   unsigned char tcp_ctl,
765                                   int unreachable,
766                                   size_t *_packet_len)
767 {
768         uint8_t *base;
769         uint8_t *buf;
770         struct swrap_packet_frame *frame;
771         union swrap_packet_ip *ip;
772         union swrap_packet_payload *pay;
773         size_t packet_len;
774         size_t alloc_len;
775         size_t nonwire_len = sizeof(*frame);
776         size_t wire_hdr_len = 0;
777         size_t wire_len = 0;
778         size_t ip_hdr_len = 0;
779         size_t icmp_hdr_len = 0;
780         size_t icmp_truncate_len = 0;
781         uint8_t protocol = 0, icmp_protocol = 0;
782         const struct sockaddr_in *src_in;
783         const struct sockaddr_in *dest_in;
784         uint16_t src_port;
785         uint16_t dest_port;
786
787         switch (src->sa_family) {
788         case AF_INET:
789                 src_in = (const struct sockaddr_in *)src;
790                 dest_in = (const struct sockaddr_in *)dest;
791                 src_port = src_in->sin_port;
792                 dest_port = dest_in->sin_port;
793                 ip_hdr_len = sizeof(ip->v4);
794                 break;
795         default:
796                 return NULL;
797         }
798
799         switch (socket_type) {
800         case SOCK_STREAM:
801                 protocol = 0x06; /* TCP */
802                 wire_hdr_len = ip_hdr_len + sizeof(pay->tcp);
803                 wire_len = wire_hdr_len + payload_len;
804                 break;
805
806         case SOCK_DGRAM:
807                 protocol = 0x11; /* UDP */
808                 wire_hdr_len = ip_hdr_len + sizeof(pay->udp);
809                 wire_len = wire_hdr_len + payload_len;
810                 break;
811
812         default:
813                 return NULL;
814         }
815
816         if (unreachable) {
817                 icmp_protocol = protocol;
818                 protocol = 0x01; /* ICMP */
819                 if (wire_len > 64 ) {
820                         icmp_truncate_len = wire_len - 64;
821                 }
822                 icmp_hdr_len = ip_hdr_len + sizeof(pay->icmp4);
823                 wire_hdr_len += icmp_hdr_len;
824                 wire_len += icmp_hdr_len;
825         }
826
827         packet_len = nonwire_len + wire_len;
828         alloc_len = packet_len;
829         if (alloc_len < SWRAP_PACKET_MIN_ALLOC) {
830                 alloc_len = SWRAP_PACKET_MIN_ALLOC;
831         }
832
833         base = (uint8_t *)malloc(alloc_len);
834         if (!base) return NULL;
835
836         buf = base;
837
838         frame = (struct swrap_packet_frame *)buf;
839         frame->seconds          = tval->tv_sec;
840         frame->micro_seconds    = tval->tv_usec;
841         frame->recorded_length  = wire_len - icmp_truncate_len;
842         frame->full_length      = wire_len - icmp_truncate_len;
843         buf += SWRAP_PACKET_FRAME_SIZE;
844
845         ip = (union swrap_packet_ip *)buf;
846         switch (src->sa_family) {
847         case AF_INET:
848                 ip->v4.ver_hdrlen       = 0x45; /* version 4 and 5 * 32 bit words */
849                 ip->v4.tos              = 0x00;
850                 ip->v4.packet_length    = htons(wire_len - icmp_truncate_len);
851                 ip->v4.identification   = htons(0xFFFF);
852                 ip->v4.flags            = 0x40; /* BIT 1 set - means don't fraqment */
853                 ip->v4.fragment         = htons(0x0000);
854                 ip->v4.ttl              = 0xFF;
855                 ip->v4.protocol         = protocol;
856                 ip->v4.hdr_checksum     = htons(0x0000);
857                 ip->v4.src_addr         = src_in->sin_addr.s_addr;
858                 ip->v4.dest_addr        = dest_in->sin_addr.s_addr;
859                 buf += SWRAP_PACKET_IP_V4_SIZE;
860                 break;
861         }
862
863         if (unreachable) {
864                 pay = (union swrap_packet_payload *)buf;
865                 switch (src->sa_family) {
866                 case AF_INET:
867                         pay->icmp4.type         = 0x03; /* destination unreachable */
868                         pay->icmp4.code         = 0x01; /* host unreachable */
869                         pay->icmp4.checksum     = htons(0x0000);
870                         pay->icmp4.unused       = htonl(0x00000000);
871                         buf += SWRAP_PACKET_PAYLOAD_ICMP4_SIZE;
872
873                         /* set the ip header in the ICMP payload */
874                         ip = (union swrap_packet_ip *)buf;
875                         ip->v4.ver_hdrlen       = 0x45; /* version 4 and 5 * 32 bit words */
876                         ip->v4.tos              = 0x00;
877                         ip->v4.packet_length    = htons(wire_len - icmp_hdr_len);
878                         ip->v4.identification   = htons(0xFFFF);
879                         ip->v4.flags            = 0x40; /* BIT 1 set - means don't fraqment */
880                         ip->v4.fragment         = htons(0x0000);
881                         ip->v4.ttl              = 0xFF;
882                         ip->v4.protocol         = icmp_protocol;
883                         ip->v4.hdr_checksum     = htons(0x0000);
884                         ip->v4.src_addr         = dest_in->sin_addr.s_addr;
885                         ip->v4.dest_addr        = src_in->sin_addr.s_addr;
886                         buf += SWRAP_PACKET_IP_V4_SIZE;
887
888                         src_port = dest_in->sin_port;
889                         dest_port = src_in->sin_port;
890                         break;
891                 }
892         }
893
894         pay = (union swrap_packet_payload *)buf;
895
896         switch (socket_type) {
897         case SOCK_STREAM:
898                 pay->tcp.source_port    = src_port;
899                 pay->tcp.dest_port      = dest_port;
900                 pay->tcp.seq_num        = htonl(tcp_seqno);
901                 pay->tcp.ack_num        = htonl(tcp_ack);
902                 pay->tcp.hdr_length     = 0x50; /* 5 * 32 bit words */
903                 pay->tcp.control        = tcp_ctl;
904                 pay->tcp.window         = htons(0x7FFF);
905                 pay->tcp.checksum       = htons(0x0000);
906                 pay->tcp.urg            = htons(0x0000);
907                 buf += SWRAP_PACKET_PAYLOAD_TCP_SIZE;
908
909                 break;
910
911         case SOCK_DGRAM:
912                 pay->udp.source_port    = src_port;
913                 pay->udp.dest_port      = dest_port;
914                 pay->udp.length         = htons(8 + payload_len);
915                 pay->udp.checksum       = htons(0x0000);
916                 buf += SWRAP_PACKET_PAYLOAD_UDP_SIZE;
917
918                 break;
919         }
920
921         if (payload && payload_len > 0) {
922                 memcpy(buf, payload, payload_len);
923         }
924
925         *_packet_len = packet_len - icmp_truncate_len;
926         return base;
927 }
928
929 static int swrap_get_pcap_fd(const char *fname)
930 {
931         static int fd = -1;
932
933         if (fd != -1) return fd;
934
935         fd = open(fname, O_WRONLY|O_CREAT|O_EXCL|O_APPEND, 0644);
936         if (fd != -1) {
937                 struct swrap_file_hdr file_hdr;
938                 file_hdr.magic          = 0xA1B2C3D4;
939                 file_hdr.version_major  = 0x0002;       
940                 file_hdr.version_minor  = 0x0004;
941                 file_hdr.timezone       = 0x00000000;
942                 file_hdr.sigfigs        = 0x00000000;
943                 file_hdr.frame_max_len  = SWRAP_FRAME_LENGTH_MAX;
944                 file_hdr.link_type      = 0x0065; /* 101 RAW IP */
945
946                 if (write(fd, &file_hdr, sizeof(file_hdr)) != sizeof(file_hdr)) {
947                         close(fd);
948                         fd = -1;
949                 }
950                 return fd;
951         }
952
953         fd = open(fname, O_WRONLY|O_APPEND, 0644);
954
955         return fd;
956 }
957
958 static uint8_t *swrap_marshall_packet(struct socket_info *si,
959                                       const struct sockaddr *addr,
960                                       enum swrap_packet_type type,
961                                       const void *buf, size_t len,
962                                       size_t *packet_len)
963 {
964         const struct sockaddr *src_addr;
965         const struct sockaddr *dest_addr;
966         unsigned long tcp_seqno = 0;
967         unsigned long tcp_ack = 0;
968         unsigned char tcp_ctl = 0;
969         int unreachable = 0;
970
971         struct timeval tv;
972
973         switch (si->family) {
974         case AF_INET:
975                 break;
976         default:
977                 return NULL;
978         }
979
980         switch (type) {
981         case SWRAP_CONNECT_SEND:
982                 if (si->type != SOCK_STREAM) return NULL;
983
984                 src_addr = si->myname;
985                 dest_addr = addr;
986
987                 tcp_seqno = si->io.pck_snd;
988                 tcp_ack = si->io.pck_rcv;
989                 tcp_ctl = 0x02; /* SYN */
990
991                 si->io.pck_snd += 1;
992
993                 break;
994
995         case SWRAP_CONNECT_RECV:
996                 if (si->type != SOCK_STREAM) return NULL;
997
998                 dest_addr = si->myname;
999                 src_addr = addr;
1000
1001                 tcp_seqno = si->io.pck_rcv;
1002                 tcp_ack = si->io.pck_snd;
1003                 tcp_ctl = 0x12; /** SYN,ACK */
1004
1005                 si->io.pck_rcv += 1;
1006
1007                 break;
1008
1009         case SWRAP_CONNECT_UNREACH:
1010                 if (si->type != SOCK_STREAM) return NULL;
1011
1012                 dest_addr = si->myname;
1013                 src_addr = addr;
1014
1015                 /* Unreachable: resend the data of SWRAP_CONNECT_SEND */
1016                 tcp_seqno = si->io.pck_snd - 1;
1017                 tcp_ack = si->io.pck_rcv;
1018                 tcp_ctl = 0x02; /* SYN */
1019                 unreachable = 1;
1020
1021                 break;
1022
1023         case SWRAP_CONNECT_ACK:
1024                 if (si->type != SOCK_STREAM) return NULL;
1025
1026                 src_addr = si->myname;
1027                 dest_addr = addr;
1028
1029                 tcp_seqno = si->io.pck_snd;
1030                 tcp_ack = si->io.pck_rcv;
1031                 tcp_ctl = 0x10; /* ACK */
1032
1033                 break;
1034
1035         case SWRAP_ACCEPT_SEND:
1036                 if (si->type != SOCK_STREAM) return NULL;
1037
1038                 dest_addr = si->myname;
1039                 src_addr = addr;
1040
1041                 tcp_seqno = si->io.pck_rcv;
1042                 tcp_ack = si->io.pck_snd;
1043                 tcp_ctl = 0x02; /* SYN */
1044
1045                 si->io.pck_rcv += 1;
1046
1047                 break;
1048
1049         case SWRAP_ACCEPT_RECV:
1050                 if (si->type != SOCK_STREAM) return NULL;
1051
1052                 src_addr = si->myname;
1053                 dest_addr = addr;
1054
1055                 tcp_seqno = si->io.pck_snd;
1056                 tcp_ack = si->io.pck_rcv;
1057                 tcp_ctl = 0x12; /* SYN,ACK */
1058
1059                 si->io.pck_snd += 1;
1060
1061                 break;
1062
1063         case SWRAP_ACCEPT_ACK:
1064                 if (si->type != SOCK_STREAM) return NULL;
1065
1066                 dest_addr = si->myname;
1067                 src_addr = addr;
1068
1069                 tcp_seqno = si->io.pck_rcv;
1070                 tcp_ack = si->io.pck_snd;
1071                 tcp_ctl = 0x10; /* ACK */
1072
1073                 break;
1074
1075         case SWRAP_SEND:
1076                 src_addr = si->myname;
1077                 dest_addr = si->peername;
1078
1079                 tcp_seqno = si->io.pck_snd;
1080                 tcp_ack = si->io.pck_rcv;
1081                 tcp_ctl = 0x18; /* PSH,ACK */
1082
1083                 si->io.pck_snd += len;
1084
1085                 break;
1086
1087         case SWRAP_SEND_RST:
1088                 dest_addr = si->myname;
1089                 src_addr = si->peername;
1090
1091                 if (si->type == SOCK_DGRAM) {
1092                         return swrap_marshall_packet(si, si->peername,
1093                                           SWRAP_SENDTO_UNREACH,
1094                                           buf, len, packet_len);
1095                 }
1096
1097                 tcp_seqno = si->io.pck_rcv;
1098                 tcp_ack = si->io.pck_snd;
1099                 tcp_ctl = 0x14; /** RST,ACK */
1100
1101                 break;
1102
1103         case SWRAP_PENDING_RST:
1104                 dest_addr = si->myname;
1105                 src_addr = si->peername;
1106
1107                 if (si->type == SOCK_DGRAM) {
1108                         return NULL;
1109                 }
1110
1111                 tcp_seqno = si->io.pck_rcv;
1112                 tcp_ack = si->io.pck_snd;
1113                 tcp_ctl = 0x14; /* RST,ACK */
1114
1115                 break;
1116
1117         case SWRAP_RECV:
1118                 dest_addr = si->myname;
1119                 src_addr = si->peername;
1120
1121                 tcp_seqno = si->io.pck_rcv;
1122                 tcp_ack = si->io.pck_snd;
1123                 tcp_ctl = 0x18; /* PSH,ACK */
1124
1125                 si->io.pck_rcv += len;
1126
1127                 break;
1128
1129         case SWRAP_RECV_RST:
1130                 dest_addr = si->myname;
1131                 src_addr = si->peername;
1132
1133                 if (si->type == SOCK_DGRAM) {
1134                         return NULL;
1135                 }
1136
1137                 tcp_seqno = si->io.pck_rcv;
1138                 tcp_ack = si->io.pck_snd;
1139                 tcp_ctl = 0x14; /* RST,ACK */
1140
1141                 break;
1142
1143         case SWRAP_SENDTO:
1144                 src_addr = si->myname;
1145                 dest_addr = addr;
1146
1147                 si->io.pck_snd += len;
1148
1149                 break;
1150
1151         case SWRAP_SENDTO_UNREACH:
1152                 dest_addr = si->myname;
1153                 src_addr = addr;
1154
1155                 unreachable = 1;
1156
1157                 break;
1158
1159         case SWRAP_RECVFROM:
1160                 dest_addr = si->myname;
1161                 src_addr = addr;
1162
1163                 si->io.pck_rcv += len;
1164
1165                 break;
1166
1167         case SWRAP_CLOSE_SEND:
1168                 if (si->type != SOCK_STREAM) return NULL;
1169
1170                 src_addr = si->myname;
1171                 dest_addr = si->peername;
1172
1173                 tcp_seqno = si->io.pck_snd;
1174                 tcp_ack = si->io.pck_rcv;
1175                 tcp_ctl = 0x11; /* FIN, ACK */
1176
1177                 si->io.pck_snd += 1;
1178
1179                 break;
1180
1181         case SWRAP_CLOSE_RECV:
1182                 if (si->type != SOCK_STREAM) return NULL;
1183
1184                 dest_addr = si->myname;
1185                 src_addr = si->peername;
1186
1187                 tcp_seqno = si->io.pck_rcv;
1188                 tcp_ack = si->io.pck_snd;
1189                 tcp_ctl = 0x11; /* FIN,ACK */
1190
1191                 si->io.pck_rcv += 1;
1192
1193                 break;
1194
1195         case SWRAP_CLOSE_ACK:
1196                 if (si->type != SOCK_STREAM) return NULL;
1197
1198                 src_addr = si->myname;
1199                 dest_addr = si->peername;
1200
1201                 tcp_seqno = si->io.pck_snd;
1202                 tcp_ack = si->io.pck_rcv;
1203                 tcp_ctl = 0x10; /* ACK */
1204
1205                 break;
1206         default:
1207                 return NULL;
1208         }
1209
1210         swrapGetTimeOfDay(&tv);
1211
1212         return swrap_packet_init(&tv, src_addr, dest_addr, si->type,
1213                                  (const uint8_t *)buf, len,
1214                                  tcp_seqno, tcp_ack, tcp_ctl, unreachable,
1215                                  packet_len);
1216 }
1217
1218 static void swrap_dump_packet(struct socket_info *si,
1219                               const struct sockaddr *addr,
1220                               enum swrap_packet_type type,
1221                               const void *buf, size_t len)
1222 {
1223         const char *file_name;
1224         uint8_t *packet;
1225         size_t packet_len = 0;
1226         int fd;
1227
1228         file_name = socket_wrapper_pcap_file();
1229         if (!file_name) {
1230                 return;
1231         }
1232
1233         packet = swrap_marshall_packet(si, addr, type, buf, len, &packet_len);
1234         if (!packet) {
1235                 return;
1236         }
1237
1238         fd = swrap_get_pcap_fd(file_name);
1239         if (fd != -1) {
1240                 if (write(fd, packet, packet_len) != packet_len) {
1241                         free(packet);
1242                         return;
1243                 }
1244         }
1245
1246         free(packet);
1247 }
1248
1249 _PUBLIC_ int swrap_socket(int family, int type, int protocol)
1250 {
1251         struct socket_info *si;
1252         int fd;
1253
1254         if (!socket_wrapper_dir()) {
1255                 return real_socket(family, type, protocol);
1256         }
1257
1258         switch (family) {
1259         case AF_INET:
1260 #ifdef HAVE_IPV6
1261         case AF_INET6:
1262 #endif
1263                 break;
1264         case AF_UNIX:
1265                 return real_socket(family, type, protocol);
1266         default:
1267                 errno = EAFNOSUPPORT;
1268                 return -1;
1269         }
1270
1271         switch (type) {
1272         case SOCK_STREAM:
1273                 break;
1274         case SOCK_DGRAM:
1275                 break;
1276         default:
1277                 errno = EPROTONOSUPPORT;
1278                 return -1;
1279         }
1280
1281         switch (protocol) {
1282         case 0:
1283                 break;
1284         case 6:
1285                 if (type == SOCK_STREAM) {
1286                         break;
1287                 }
1288                 /*fall through*/
1289         case 17:
1290                 if (type == SOCK_DGRAM) {
1291                         break;
1292                 }
1293                 /*fall through*/
1294         default:
1295                 errno = EPROTONOSUPPORT;
1296                 return -1;
1297         }
1298
1299         fd = real_socket(AF_UNIX, type, 0);
1300
1301         if (fd == -1) return -1;
1302
1303         si = (struct socket_info *)calloc(1, sizeof(struct socket_info));
1304
1305         si->family = family;
1306         si->type = type;
1307         si->protocol = protocol;
1308         si->fd = fd;
1309
1310         SWRAP_DLIST_ADD(sockets, si);
1311
1312         return si->fd;
1313 }
1314
1315 _PUBLIC_ int swrap_accept(int s, struct sockaddr *addr, socklen_t *addrlen)
1316 {
1317         struct socket_info *parent_si, *child_si;
1318         int fd;
1319         struct sockaddr_un un_addr;
1320         socklen_t un_addrlen = sizeof(un_addr);
1321         struct sockaddr_un un_my_addr;
1322         socklen_t un_my_addrlen = sizeof(un_my_addr);
1323         struct sockaddr *my_addr;
1324         socklen_t my_addrlen, len;
1325         int ret;
1326
1327         parent_si = find_socket_info(s);
1328         if (!parent_si) {
1329                 return real_accept(s, addr, addrlen);
1330         }
1331
1332         /* 
1333          * assume out sockaddr have the same size as the in parent
1334          * socket family
1335          */
1336         my_addrlen = socket_length(parent_si->family);
1337         if (my_addrlen <= 0) {
1338                 errno = EINVAL;
1339                 return -1;
1340         }
1341
1342         my_addr = (struct sockaddr *)malloc(my_addrlen);
1343         if (my_addr == NULL) {
1344                 return -1;
1345         }
1346
1347         memset(&un_addr, 0, sizeof(un_addr));
1348         memset(&un_my_addr, 0, sizeof(un_my_addr));
1349
1350         ret = real_accept(s, (struct sockaddr *)&un_addr, &un_addrlen);
1351         if (ret == -1) {
1352                 free(my_addr);
1353                 return ret;
1354         }
1355
1356         fd = ret;
1357
1358         len = my_addrlen;
1359         ret = sockaddr_convert_from_un(parent_si, &un_addr, un_addrlen,
1360                                        parent_si->family, my_addr, &len);
1361         if (ret == -1) {
1362                 free(my_addr);
1363                 close(fd);
1364                 return ret;
1365         }
1366
1367         child_si = (struct socket_info *)malloc(sizeof(struct socket_info));
1368         memset(child_si, 0, sizeof(*child_si));
1369
1370         child_si->fd = fd;
1371         child_si->family = parent_si->family;
1372         child_si->type = parent_si->type;
1373         child_si->protocol = parent_si->protocol;
1374         child_si->bound = 1;
1375         child_si->is_server = 1;
1376
1377         child_si->peername_len = len;
1378         child_si->peername = sockaddr_dup(my_addr, len);
1379
1380         if (addr != NULL && addrlen != NULL) {
1381             *addrlen = len;
1382             if (*addrlen >= len)
1383                 memcpy(addr, my_addr, len);
1384             *addrlen = 0;
1385         }
1386
1387         ret = real_getsockname(fd, (struct sockaddr *)&un_my_addr, &un_my_addrlen);
1388         if (ret == -1) {
1389                 free(child_si);
1390                 close(fd);
1391                 return ret;
1392         }
1393
1394         len = my_addrlen;
1395         ret = sockaddr_convert_from_un(child_si, &un_my_addr, un_my_addrlen,
1396                                        child_si->family, my_addr, &len);
1397         if (ret == -1) {
1398                 free(child_si);
1399                 free(my_addr);
1400                 close(fd);
1401                 return ret;
1402         }
1403
1404         child_si->myname_len = len;
1405         child_si->myname = sockaddr_dup(my_addr, len);
1406         free(my_addr);
1407
1408         SWRAP_DLIST_ADD(sockets, child_si);
1409
1410         swrap_dump_packet(child_si, addr, SWRAP_ACCEPT_SEND, NULL, 0);
1411         swrap_dump_packet(child_si, addr, SWRAP_ACCEPT_RECV, NULL, 0);
1412         swrap_dump_packet(child_si, addr, SWRAP_ACCEPT_ACK, NULL, 0);
1413
1414         return fd;
1415 }
1416
1417 static int autobind_start_init;
1418 static int autobind_start;
1419
1420 /* using sendto() or connect() on an unbound socket would give the
1421    recipient no way to reply, as unlike UDP and TCP, a unix domain
1422    socket can't auto-assign emphemeral port numbers, so we need to
1423    assign it here */
1424 static int swrap_auto_bind(struct socket_info *si)
1425 {
1426         struct sockaddr_un un_addr;
1427         int i;
1428         char type;
1429         int ret;
1430         int port;
1431         struct stat st;
1432
1433         if (autobind_start_init != 1) {
1434                 autobind_start_init = 1;
1435                 autobind_start = getpid();
1436                 autobind_start %= 50000;
1437                 autobind_start += 10000;
1438         }
1439
1440         un_addr.sun_family = AF_UNIX;
1441
1442         switch (si->family) {
1443         case AF_INET: {
1444                 struct sockaddr_in in;
1445
1446                 switch (si->type) {
1447                 case SOCK_STREAM:
1448                         type = SOCKET_TYPE_CHAR_TCP;
1449                         break;
1450                 case SOCK_DGRAM:
1451                         type = SOCKET_TYPE_CHAR_UDP;
1452                         break;
1453                 default:
1454                     errno = ESOCKTNOSUPPORT;
1455                     return -1;
1456                 }
1457
1458                 memset(&in, 0, sizeof(in));
1459                 in.sin_family = AF_INET;
1460                 in.sin_addr.s_addr = htonl(127<<24 | 
1461                                            socket_wrapper_default_iface());
1462
1463                 si->myname_len = sizeof(in);
1464                 si->myname = sockaddr_dup(&in, si->myname_len);
1465                 break;
1466         }
1467 #ifdef HAVE_IPV6
1468         case AF_INET6: {
1469                 struct sockaddr_in6 in6;
1470
1471                 switch (si->type) {
1472                 case SOCK_STREAM:
1473                         type = SOCKET_TYPE_CHAR_TCP_V6;
1474                         break;
1475                 case SOCK_DGRAM:
1476                         type = SOCKET_TYPE_CHAR_UDP_V6;
1477                         break;
1478                 default:
1479                     errno = ESOCKTNOSUPPORT;
1480                     return -1;
1481                 }
1482
1483                 memset(&in6, 0, sizeof(in6));
1484                 in6.sin6_family = AF_INET6;
1485                 in6.sin6_addr.s6_addr[0] = SW_IPV6_ADDRESS;
1486                 si->myname_len = sizeof(in6);
1487                 si->myname = sockaddr_dup(&in6, si->myname_len);
1488                 break;
1489         }
1490 #endif
1491         default:
1492                 errno = ESOCKTNOSUPPORT;
1493                 return -1;
1494         }
1495
1496         if (autobind_start > 60000) {
1497                 autobind_start = 10000;
1498         }
1499
1500         for (i=0;i<1000;i++) {
1501                 port = autobind_start + i;
1502                 snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), 
1503                          "%s/"SOCKET_FORMAT, socket_wrapper_dir(),
1504                          type, socket_wrapper_default_iface(), port);
1505                 if (stat(un_addr.sun_path, &st) == 0) continue;
1506                 
1507                 ret = real_bind(si->fd, (struct sockaddr *)&un_addr, sizeof(un_addr));
1508                 if (ret == -1) return ret;
1509
1510                 si->tmp_path = strdup(un_addr.sun_path);
1511                 si->bound = 1;
1512                 autobind_start = port + 1;
1513                 break;
1514         }
1515         if (i == 1000) {
1516                 errno = ENFILE;
1517                 return -1;
1518         }
1519
1520         set_port(si->family, port, si->myname);
1521
1522         return 0;
1523 }
1524
1525
1526 _PUBLIC_ int swrap_connect(int s, const struct sockaddr *serv_addr, socklen_t addrlen)
1527 {
1528         int ret;
1529         struct sockaddr_un un_addr;
1530         struct socket_info *si = find_socket_info(s);
1531
1532         if (!si) {
1533                 return real_connect(s, serv_addr, addrlen);
1534         }
1535
1536         if (si->bound == 0) {
1537                 ret = swrap_auto_bind(si);
1538                 if (ret == -1) return -1;
1539         }
1540
1541         if (si->family != serv_addr->sa_family) {
1542                 errno = EINVAL;
1543                 return -1;
1544         }
1545
1546         ret = sockaddr_convert_to_un(si, (const struct sockaddr *)serv_addr, addrlen, &un_addr, 0, NULL);
1547         if (ret == -1) return -1;
1548
1549         swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_SEND, NULL, 0);
1550
1551         ret = real_connect(s, (struct sockaddr *)&un_addr, 
1552                            sizeof(struct sockaddr_un));
1553
1554         /* to give better errors */
1555         if (ret == -1 && errno == ENOENT) {
1556                 errno = EHOSTUNREACH;
1557         }
1558
1559         if (ret == 0) {
1560                 si->peername_len = addrlen;
1561                 si->peername = sockaddr_dup(serv_addr, addrlen);
1562
1563                 swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_RECV, NULL, 0);
1564                 swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_ACK, NULL, 0);
1565         } else {
1566                 swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_UNREACH, NULL, 0);
1567         }
1568
1569         return ret;
1570 }
1571
1572 _PUBLIC_ int swrap_bind(int s, const struct sockaddr *myaddr, socklen_t addrlen)
1573 {
1574         int ret;
1575         struct sockaddr_un un_addr;
1576         struct socket_info *si = find_socket_info(s);
1577
1578         if (!si) {
1579                 return real_bind(s, myaddr, addrlen);
1580         }
1581
1582         si->myname_len = addrlen;
1583         si->myname = sockaddr_dup(myaddr, addrlen);
1584
1585         ret = sockaddr_convert_to_un(si, (const struct sockaddr *)myaddr, addrlen, &un_addr, 1, &si->bcast);
1586         if (ret == -1) return -1;
1587
1588         unlink(un_addr.sun_path);
1589
1590         ret = real_bind(s, (struct sockaddr *)&un_addr,
1591                         sizeof(struct sockaddr_un));
1592
1593         if (ret == 0) {
1594                 si->bound = 1;
1595         }
1596
1597         return ret;
1598 }
1599
1600 _PUBLIC_ int swrap_listen(int s, int backlog)
1601 {
1602         int ret;
1603         struct socket_info *si = find_socket_info(s);
1604
1605         if (!si) {
1606                 return real_listen(s, backlog);
1607         }
1608
1609         ret = real_listen(s, backlog);
1610
1611         return ret;
1612 }
1613
1614 _PUBLIC_ int swrap_getpeername(int s, struct sockaddr *name, socklen_t *addrlen)
1615 {
1616         struct socket_info *si = find_socket_info(s);
1617
1618         if (!si) {
1619                 return real_getpeername(s, name, addrlen);
1620         }
1621
1622         if (!si->peername)
1623         {
1624                 errno = ENOTCONN;
1625                 return -1;
1626         }
1627
1628         memcpy(name, si->peername, si->peername_len);
1629         *addrlen = si->peername_len;
1630
1631         return 0;
1632 }
1633
1634 _PUBLIC_ int swrap_getsockname(int s, struct sockaddr *name, socklen_t *addrlen)
1635 {
1636         struct socket_info *si = find_socket_info(s);
1637
1638         if (!si) {
1639                 return real_getsockname(s, name, addrlen);
1640         }
1641
1642         memcpy(name, si->myname, si->myname_len);
1643         *addrlen = si->myname_len;
1644
1645         return 0;
1646 }
1647
1648 _PUBLIC_ int swrap_getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen)
1649 {
1650         struct socket_info *si = find_socket_info(s);
1651
1652         if (!si) {
1653                 return real_getsockopt(s, level, optname, optval, optlen);
1654         }
1655
1656         if (level == SOL_SOCKET) {
1657                 return real_getsockopt(s, level, optname, optval, optlen);
1658         } 
1659
1660         errno = ENOPROTOOPT;
1661         return -1;
1662 }
1663
1664 _PUBLIC_ int swrap_setsockopt(int s, int  level,  int  optname,  const  void  *optval, socklen_t optlen)
1665 {
1666         struct socket_info *si = find_socket_info(s);
1667
1668         if (!si) {
1669                 return real_setsockopt(s, level, optname, optval, optlen);
1670         }
1671
1672         if (level == SOL_SOCKET) {
1673                 return real_setsockopt(s, level, optname, optval, optlen);
1674         }
1675
1676         switch (si->family) {
1677         case AF_INET:
1678                 return 0;
1679         default:
1680                 errno = ENOPROTOOPT;
1681                 return -1;
1682         }
1683 }
1684
1685 _PUBLIC_ ssize_t swrap_recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen)
1686 {
1687         struct sockaddr_un un_addr;
1688         socklen_t un_addrlen = sizeof(un_addr);
1689         int ret;
1690         struct socket_info *si = find_socket_info(s);
1691
1692         if (!si) {
1693                 return real_recvfrom(s, buf, len, flags, from, fromlen);
1694         }
1695
1696         len = MIN(len, 1500);
1697
1698         /* irix 6.4 forgets to null terminate the sun_path string :-( */
1699         memset(&un_addr, 0, sizeof(un_addr));
1700         ret = real_recvfrom(s, buf, len, flags, (struct sockaddr *)&un_addr, &un_addrlen);
1701         if (ret == -1) 
1702                 return ret;
1703
1704         if (sockaddr_convert_from_un(si, &un_addr, un_addrlen,
1705                                      si->family, from, fromlen) == -1) {
1706                 return -1;
1707         }
1708
1709         swrap_dump_packet(si, from, SWRAP_RECVFROM, buf, ret);
1710
1711         return ret;
1712 }
1713
1714
1715 _PUBLIC_ ssize_t swrap_sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen)
1716 {
1717         struct sockaddr_un un_addr;
1718         int ret;
1719         struct socket_info *si = find_socket_info(s);
1720         int bcast = 0;
1721
1722         if (!si) {
1723                 return real_sendto(s, buf, len, flags, to, tolen);
1724         }
1725
1726         len = MIN(len, 1500);
1727
1728         switch (si->type) {
1729         case SOCK_STREAM:
1730                 ret = real_send(s, buf, len, flags);
1731                 break;
1732         case SOCK_DGRAM:
1733                 if (si->bound == 0) {
1734                         ret = swrap_auto_bind(si);
1735                         if (ret == -1) return -1;
1736                 }
1737                 
1738                 ret = sockaddr_convert_to_un(si, to, tolen, &un_addr, 0, &bcast);
1739                 if (ret == -1) return -1;
1740                 
1741                 if (bcast) {
1742                         struct stat st;
1743                         unsigned int iface;
1744                         unsigned int prt = ntohs(((const struct sockaddr_in *)to)->sin_port);
1745                         char type;
1746                         
1747                         type = SOCKET_TYPE_CHAR_UDP;
1748                         
1749                         for(iface=0; iface <= MAX_WRAPPED_INTERFACES; iface++) {
1750                                 snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s/"SOCKET_FORMAT, 
1751                                          socket_wrapper_dir(), type, iface, prt);
1752                                 if (stat(un_addr.sun_path, &st) != 0) continue;
1753                                 
1754                                 /* ignore the any errors in broadcast sends */
1755                                 real_sendto(s, buf, len, flags, (struct sockaddr *)&un_addr, sizeof(un_addr));
1756                         }
1757                         
1758                         swrap_dump_packet(si, to, SWRAP_SENDTO, buf, len);
1759                         
1760                         return len;
1761                 }
1762                 
1763                 ret = real_sendto(s, buf, len, flags, (struct sockaddr *)&un_addr, sizeof(un_addr));
1764                 break;
1765         default:
1766                 ret = -1;
1767                 errno = EHOSTUNREACH;
1768                 break;
1769         }
1770                 
1771         /* to give better errors */
1772         if (ret == -1 && errno == ENOENT) {
1773                 errno = EHOSTUNREACH;
1774         }
1775
1776         if (ret == -1) {
1777                 swrap_dump_packet(si, to, SWRAP_SENDTO, buf, len);
1778                 swrap_dump_packet(si, to, SWRAP_SENDTO_UNREACH, buf, len);
1779         } else {
1780                 swrap_dump_packet(si, to, SWRAP_SENDTO, buf, ret);
1781         }
1782
1783         return ret;
1784 }
1785
1786 _PUBLIC_ int swrap_ioctl(int s, int r, void *p)
1787 {
1788         int ret;
1789         struct socket_info *si = find_socket_info(s);
1790         int value;
1791
1792         if (!si) {
1793                 return real_ioctl(s, r, p);
1794         }
1795
1796         ret = real_ioctl(s, r, p);
1797
1798         switch (r) {
1799         case FIONREAD:
1800                 value = *((int *)p);
1801                 if (ret == -1 && errno != EAGAIN && errno != ENOBUFS) {
1802                         swrap_dump_packet(si, NULL, SWRAP_PENDING_RST, NULL, 0);
1803                 } else if (value == 0) { /* END OF FILE */
1804                         swrap_dump_packet(si, NULL, SWRAP_PENDING_RST, NULL, 0);
1805                 }
1806                 break;
1807         }
1808
1809         return ret;
1810 }
1811
1812 _PUBLIC_ ssize_t swrap_recv(int s, void *buf, size_t len, int flags)
1813 {
1814         int ret;
1815         struct socket_info *si = find_socket_info(s);
1816
1817         if (!si) {
1818                 return real_recv(s, buf, len, flags);
1819         }
1820
1821         len = MIN(len, 1500);
1822
1823         ret = real_recv(s, buf, len, flags);
1824         if (ret == -1 && errno != EAGAIN && errno != ENOBUFS) {
1825                 swrap_dump_packet(si, NULL, SWRAP_RECV_RST, NULL, 0);
1826         } else if (ret == 0) { /* END OF FILE */
1827                 swrap_dump_packet(si, NULL, SWRAP_RECV_RST, NULL, 0);
1828         } else if (ret > 0) {
1829                 swrap_dump_packet(si, NULL, SWRAP_RECV, buf, ret);
1830         }
1831
1832         return ret;
1833 }
1834
1835
1836 _PUBLIC_ ssize_t swrap_send(int s, const void *buf, size_t len, int flags)
1837 {
1838         int ret;
1839         struct socket_info *si = find_socket_info(s);
1840
1841         if (!si) {
1842                 return real_send(s, buf, len, flags);
1843         }
1844
1845         len = MIN(len, 1500);
1846
1847         ret = real_send(s, buf, len, flags);
1848
1849         if (ret == -1) {
1850                 swrap_dump_packet(si, NULL, SWRAP_SEND, buf, len);
1851                 swrap_dump_packet(si, NULL, SWRAP_SEND_RST, NULL, 0);
1852         } else {
1853                 swrap_dump_packet(si, NULL, SWRAP_SEND, buf, ret);
1854         }
1855
1856         return ret;
1857 }
1858
1859 _PUBLIC_ int swrap_close(int fd)
1860 {
1861         struct socket_info *si = find_socket_info(fd);
1862         int ret;
1863
1864         if (!si) {
1865                 return real_close(fd);
1866         }
1867
1868         SWRAP_DLIST_REMOVE(sockets, si);
1869
1870         if (si->myname && si->peername) {
1871                 swrap_dump_packet(si, NULL, SWRAP_CLOSE_SEND, NULL, 0);
1872         }
1873
1874         ret = real_close(fd);
1875
1876         if (si->myname && si->peername) {
1877                 swrap_dump_packet(si, NULL, SWRAP_CLOSE_RECV, NULL, 0);
1878                 swrap_dump_packet(si, NULL, SWRAP_CLOSE_ACK, NULL, 0);
1879         }
1880
1881         if (si->path) free(si->path);
1882         if (si->myname) free(si->myname);
1883         if (si->peername) free(si->peername);
1884         if (si->tmp_path) {
1885                 unlink(si->tmp_path);
1886                 free(si->tmp_path);
1887         }
1888         free(si);
1889
1890         return ret;
1891 }