Merge branch 'master' of ssh://git.samba.org/data/git/samba
[ira/wip.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 {
640         struct {
641                 uint32_t seconds;
642                 uint32_t micro_seconds;
643                 uint32_t recorded_length;
644                 uint32_t full_length;
645         } frame;
646 #define SWRAP_PACKET__FRAME_SIZE 16
647
648         struct {
649                 struct {
650                         uint8_t         ver_hdrlen;
651                         uint8_t         tos;
652                         uint16_t        packet_length;
653                         uint16_t        identification;
654                         uint8_t         flags;
655                         uint8_t         fragment;
656                         uint8_t         ttl;
657                         uint8_t         protocol;
658                         uint16_t        hdr_checksum;
659                         uint32_t        src_addr;
660                         uint32_t        dest_addr;
661                 } hdr;
662 #define SWRAP_PACKET__IP_HDR_SIZE 20
663
664                 union {
665                         struct {
666                                 uint16_t        source_port;
667                                 uint16_t        dest_port;
668                                 uint32_t        seq_num;
669                                 uint32_t        ack_num;
670                                 uint8_t         hdr_length;
671                                 uint8_t         control;
672                                 uint16_t        window;
673                                 uint16_t        checksum;
674                                 uint16_t        urg;
675                         } tcp;
676 #define SWRAP_PACKET__IP_P_TCP_SIZE 20
677                         struct {
678                                 uint16_t        source_port;
679                                 uint16_t        dest_port;
680                                 uint16_t        length;
681                                 uint16_t        checksum;
682                         } udp;
683 #define SWRAP_PACKET__IP_P_UDP_SIZE 8
684                         struct {
685                                 uint8_t         type;
686                                 uint8_t         code;
687                                 uint16_t        checksum;
688                                 uint32_t        unused;
689                         } icmp;
690 #define SWRAP_PACKET__IP_P_ICMP_SIZE 8
691                 } p;
692         } ip;
693 };
694 #define SWRAP_PACKET_SIZE 56
695
696 static const char *socket_wrapper_pcap_file(void)
697 {
698         static int initialized = 0;
699         static const char *s = NULL;
700         static const struct swrap_file_hdr h = { 0, };
701         static const struct swrap_packet p = { { 0, }, { { 0, }, { { 0, } } } };
702
703         if (initialized == 1) {
704                 return s;
705         }
706         initialized = 1;
707
708         /*
709          * TODO: don't use the structs use plain buffer offsets
710          *       and PUSH_U8(), PUSH_U16() and PUSH_U32()
711          * 
712          * for now make sure we disable PCAP support
713          * if the struct has alignment!
714          */
715         if (sizeof(h) != SWRAP_FILE_HDR_SIZE) {
716                 return NULL;
717         }
718         if (sizeof(p) != SWRAP_PACKET_SIZE) {
719                 return NULL;
720         }
721         if (sizeof(p.frame) != SWRAP_PACKET__FRAME_SIZE) {
722                 return NULL;
723         }
724         if (sizeof(p.ip.hdr) != SWRAP_PACKET__IP_HDR_SIZE) {
725                 return NULL;
726         }
727         if (sizeof(p.ip.p.tcp) != SWRAP_PACKET__IP_P_TCP_SIZE) {
728                 return NULL;
729         }
730         if (sizeof(p.ip.p.udp) != SWRAP_PACKET__IP_P_UDP_SIZE) {
731                 return NULL;
732         }
733         if (sizeof(p.ip.p.icmp) != SWRAP_PACKET__IP_P_ICMP_SIZE) {
734                 return NULL;
735         }
736
737         s = getenv("SOCKET_WRAPPER_PCAP_FILE");
738         if (s == NULL) {
739                 return NULL;
740         }
741         if (strncmp(s, "./", 2) == 0) {
742                 s += 2;
743         }
744         return s;
745 }
746
747 static struct swrap_packet *swrap_packet_init(struct timeval *tval,
748                                               const struct sockaddr_in *src_addr,
749                                               const struct sockaddr_in *dest_addr,
750                                               int socket_type,
751                                               const unsigned char *payload,
752                                               size_t payload_len,
753                                               unsigned long tcp_seqno,
754                                               unsigned long tcp_ack,
755                                               unsigned char tcp_ctl,
756                                               int unreachable,
757                                               size_t *_packet_len)
758 {
759         struct swrap_packet *ret;
760         struct swrap_packet *packet;
761         size_t packet_len;
762         size_t alloc_len;
763         size_t nonwire_len = sizeof(packet->frame);
764         size_t wire_hdr_len = 0;
765         size_t wire_len = 0;
766         size_t icmp_hdr_len = 0;
767         size_t icmp_truncate_len = 0;
768         unsigned char protocol = 0, icmp_protocol = 0;
769         unsigned short src_port = src_addr->sin_port;
770         unsigned short dest_port = dest_addr->sin_port;
771
772         switch (socket_type) {
773         case SOCK_STREAM:
774                 protocol = 0x06; /* TCP */
775                 wire_hdr_len = sizeof(packet->ip.hdr) + sizeof(packet->ip.p.tcp);
776                 wire_len = wire_hdr_len + payload_len;
777                 break;
778
779         case SOCK_DGRAM:
780                 protocol = 0x11; /* UDP */
781                 wire_hdr_len = sizeof(packet->ip.hdr) + sizeof(packet->ip.p.udp);
782                 wire_len = wire_hdr_len + payload_len;
783                 break;
784
785         default:
786                 return NULL;
787         }
788
789         if (unreachable) {
790                 icmp_protocol = protocol;
791                 protocol = 0x01; /* ICMP */
792                 if (wire_len > 64 ) {
793                         icmp_truncate_len = wire_len - 64;
794                 }
795                 icmp_hdr_len = sizeof(packet->ip.hdr) + sizeof(packet->ip.p.icmp);
796                 wire_hdr_len += icmp_hdr_len;
797                 wire_len += icmp_hdr_len;
798         }
799
800         packet_len = nonwire_len + wire_len;
801         alloc_len = packet_len;
802         if (alloc_len < sizeof(struct swrap_packet)) {
803                 alloc_len = sizeof(struct swrap_packet);
804         }
805         ret = (struct swrap_packet *)malloc(alloc_len);
806         if (!ret) return NULL;
807
808         packet = ret;
809
810         packet->frame.seconds           = tval->tv_sec;
811         packet->frame.micro_seconds     = tval->tv_usec;
812         packet->frame.recorded_length   = wire_len - icmp_truncate_len;
813         packet->frame.full_length       = wire_len - icmp_truncate_len;
814
815         packet->ip.hdr.ver_hdrlen       = 0x45; /* version 4 and 5 * 32 bit words */
816         packet->ip.hdr.tos              = 0x00;
817         packet->ip.hdr.packet_length    = htons(wire_len - icmp_truncate_len);
818         packet->ip.hdr.identification   = htons(0xFFFF);
819         packet->ip.hdr.flags            = 0x40; /* BIT 1 set - means don't fraqment */
820         packet->ip.hdr.fragment         = htons(0x0000);
821         packet->ip.hdr.ttl              = 0xFF;
822         packet->ip.hdr.protocol         = protocol;
823         packet->ip.hdr.hdr_checksum     = htons(0x0000);
824         packet->ip.hdr.src_addr         = src_addr->sin_addr.s_addr;
825         packet->ip.hdr.dest_addr        = dest_addr->sin_addr.s_addr;
826
827         if (unreachable) {
828                 packet->ip.p.icmp.type          = 0x03; /* destination unreachable */
829                 packet->ip.p.icmp.code          = 0x01; /* host unreachable */
830                 packet->ip.p.icmp.checksum      = htons(0x0000);
831                 packet->ip.p.icmp.unused        = htonl(0x00000000);
832
833                 /* set the ip header in the ICMP payload */
834                 packet = (struct swrap_packet *)(((unsigned char *)ret) + icmp_hdr_len);
835                 packet->ip.hdr.ver_hdrlen       = 0x45; /* version 4 and 5 * 32 bit words */
836                 packet->ip.hdr.tos              = 0x00;
837                 packet->ip.hdr.packet_length    = htons(wire_len - icmp_hdr_len);
838                 packet->ip.hdr.identification   = htons(0xFFFF);
839                 packet->ip.hdr.flags            = 0x40; /* BIT 1 set - means don't fraqment */
840                 packet->ip.hdr.fragment         = htons(0x0000);
841                 packet->ip.hdr.ttl              = 0xFF;
842                 packet->ip.hdr.protocol         = icmp_protocol;
843                 packet->ip.hdr.hdr_checksum     = htons(0x0000);
844                 packet->ip.hdr.src_addr         = dest_addr->sin_addr.s_addr;
845                 packet->ip.hdr.dest_addr        = src_addr->sin_addr.s_addr;
846
847                 src_port = dest_addr->sin_port;
848                 dest_port = src_addr->sin_port;
849         }
850
851         switch (socket_type) {
852         case SOCK_STREAM:
853                 packet->ip.p.tcp.source_port    = src_port;
854                 packet->ip.p.tcp.dest_port      = dest_port;
855                 packet->ip.p.tcp.seq_num        = htonl(tcp_seqno);
856                 packet->ip.p.tcp.ack_num        = htonl(tcp_ack);
857                 packet->ip.p.tcp.hdr_length     = 0x50; /* 5 * 32 bit words */
858                 packet->ip.p.tcp.control        = tcp_ctl;
859                 packet->ip.p.tcp.window         = htons(0x7FFF);
860                 packet->ip.p.tcp.checksum       = htons(0x0000);
861                 packet->ip.p.tcp.urg            = htons(0x0000);
862
863                 break;
864
865         case SOCK_DGRAM:
866                 packet->ip.p.udp.source_port    = src_addr->sin_port;
867                 packet->ip.p.udp.dest_port      = dest_addr->sin_port;
868                 packet->ip.p.udp.length         = htons(8 + payload_len);
869                 packet->ip.p.udp.checksum       = htons(0x0000);
870
871                 break;
872         }
873
874         if (payload && payload_len > 0) {
875                 unsigned char *p = (unsigned char *)ret;
876                 p += nonwire_len;
877                 p += wire_hdr_len;
878                 memcpy(p, payload, payload_len);
879         }
880
881         *_packet_len = packet_len - icmp_truncate_len;
882         return ret;
883 }
884
885 static int swrap_get_pcap_fd(const char *fname)
886 {
887         static int fd = -1;
888
889         if (fd != -1) return fd;
890
891         fd = open(fname, O_WRONLY|O_CREAT|O_EXCL|O_APPEND, 0644);
892         if (fd != -1) {
893                 struct swrap_file_hdr file_hdr;
894                 file_hdr.magic          = 0xA1B2C3D4;
895                 file_hdr.version_major  = 0x0002;       
896                 file_hdr.version_minor  = 0x0004;
897                 file_hdr.timezone       = 0x00000000;
898                 file_hdr.sigfigs        = 0x00000000;
899                 file_hdr.frame_max_len  = SWRAP_FRAME_LENGTH_MAX;
900                 file_hdr.link_type      = 0x0065; /* 101 RAW IP */
901
902                 if (write(fd, &file_hdr, sizeof(file_hdr)) != sizeof(file_hdr)) {
903                         close(fd);
904                         return -1;
905                 }
906                 return fd;
907         }
908
909         fd = open(fname, O_WRONLY|O_APPEND, 0644);
910
911         return fd;
912 }
913
914 static struct swrap_packet *swrap_marshall_packet(struct socket_info *si,
915                                                                   const struct sockaddr *addr,
916                                                                   enum swrap_packet_type type,
917                                                                   const void *buf, size_t len,
918                                                                   size_t *packet_len)
919 {
920         const struct sockaddr_in *src_addr;
921         const struct sockaddr_in *dest_addr;
922         unsigned long tcp_seqno = 0;
923         unsigned long tcp_ack = 0;
924         unsigned char tcp_ctl = 0;
925         int unreachable = 0;
926
927         struct timeval tv;
928
929         switch (si->family) {
930         case AF_INET:
931                 break;
932         default:
933                 return NULL;
934         }
935
936         switch (type) {
937         case SWRAP_CONNECT_SEND:
938                 if (si->type != SOCK_STREAM) return NULL;
939
940                 src_addr = (const struct sockaddr_in *)si->myname;
941                 dest_addr = (const struct sockaddr_in *)addr;
942
943                 tcp_seqno = si->io.pck_snd;
944                 tcp_ack = si->io.pck_rcv;
945                 tcp_ctl = 0x02; /* SYN */
946
947                 si->io.pck_snd += 1;
948
949                 break;
950
951         case SWRAP_CONNECT_RECV:
952                 if (si->type != SOCK_STREAM) return NULL;
953
954                 dest_addr = (const struct sockaddr_in *)si->myname;
955                 src_addr = (const struct sockaddr_in *)addr;
956
957                 tcp_seqno = si->io.pck_rcv;
958                 tcp_ack = si->io.pck_snd;
959                 tcp_ctl = 0x12; /** SYN,ACK */
960
961                 si->io.pck_rcv += 1;
962
963                 break;
964
965         case SWRAP_CONNECT_UNREACH:
966                 if (si->type != SOCK_STREAM) return NULL;
967
968                 dest_addr = (const struct sockaddr_in *)si->myname;
969                 src_addr = (const struct sockaddr_in *)addr;
970
971                 /* Unreachable: resend the data of SWRAP_CONNECT_SEND */
972                 tcp_seqno = si->io.pck_snd - 1;
973                 tcp_ack = si->io.pck_rcv;
974                 tcp_ctl = 0x02; /* SYN */
975                 unreachable = 1;
976
977                 break;
978
979         case SWRAP_CONNECT_ACK:
980                 if (si->type != SOCK_STREAM) return NULL;
981
982                 src_addr = (const struct sockaddr_in *)si->myname;
983                 dest_addr = (const struct sockaddr_in *)addr;
984
985                 tcp_seqno = si->io.pck_snd;
986                 tcp_ack = si->io.pck_rcv;
987                 tcp_ctl = 0x10; /* ACK */
988
989                 break;
990
991         case SWRAP_ACCEPT_SEND:
992                 if (si->type != SOCK_STREAM) return NULL;
993
994                 dest_addr = (const struct sockaddr_in *)si->myname;
995                 src_addr = (const struct sockaddr_in *)addr;
996
997                 tcp_seqno = si->io.pck_rcv;
998                 tcp_ack = si->io.pck_snd;
999                 tcp_ctl = 0x02; /* SYN */
1000
1001                 si->io.pck_rcv += 1;
1002
1003                 break;
1004
1005         case SWRAP_ACCEPT_RECV:
1006                 if (si->type != SOCK_STREAM) return NULL;
1007
1008                 src_addr = (const struct sockaddr_in *)si->myname;
1009                 dest_addr = (const struct sockaddr_in *)addr;
1010
1011                 tcp_seqno = si->io.pck_snd;
1012                 tcp_ack = si->io.pck_rcv;
1013                 tcp_ctl = 0x12; /* SYN,ACK */
1014
1015                 si->io.pck_snd += 1;
1016
1017                 break;
1018
1019         case SWRAP_ACCEPT_ACK:
1020                 if (si->type != SOCK_STREAM) return NULL;
1021
1022                 dest_addr = (const struct sockaddr_in *)si->myname;
1023                 src_addr = (const struct sockaddr_in *)addr;
1024
1025                 tcp_seqno = si->io.pck_rcv;
1026                 tcp_ack = si->io.pck_snd;
1027                 tcp_ctl = 0x10; /* ACK */
1028
1029                 break;
1030
1031         case SWRAP_SEND:
1032                 src_addr = (const struct sockaddr_in *)si->myname;
1033                 dest_addr = (const struct sockaddr_in *)si->peername;
1034
1035                 tcp_seqno = si->io.pck_snd;
1036                 tcp_ack = si->io.pck_rcv;
1037                 tcp_ctl = 0x18; /* PSH,ACK */
1038
1039                 si->io.pck_snd += len;
1040
1041                 break;
1042
1043         case SWRAP_SEND_RST:
1044                 dest_addr = (const struct sockaddr_in *)si->myname;
1045                 src_addr = (const struct sockaddr_in *)si->peername;
1046
1047                 if (si->type == SOCK_DGRAM) {
1048                         return swrap_marshall_packet(si, si->peername,
1049                                           SWRAP_SENDTO_UNREACH,
1050                                           buf, len, packet_len);
1051                 }
1052
1053                 tcp_seqno = si->io.pck_rcv;
1054                 tcp_ack = si->io.pck_snd;
1055                 tcp_ctl = 0x14; /** RST,ACK */
1056
1057                 break;
1058
1059         case SWRAP_PENDING_RST:
1060                 dest_addr = (const struct sockaddr_in *)si->myname;
1061                 src_addr = (const struct sockaddr_in *)si->peername;
1062
1063                 if (si->type == SOCK_DGRAM) {
1064                         return NULL;
1065                 }
1066
1067                 tcp_seqno = si->io.pck_rcv;
1068                 tcp_ack = si->io.pck_snd;
1069                 tcp_ctl = 0x14; /* RST,ACK */
1070
1071                 break;
1072
1073         case SWRAP_RECV:
1074                 dest_addr = (const struct sockaddr_in *)si->myname;
1075                 src_addr = (const struct sockaddr_in *)si->peername;
1076
1077                 tcp_seqno = si->io.pck_rcv;
1078                 tcp_ack = si->io.pck_snd;
1079                 tcp_ctl = 0x18; /* PSH,ACK */
1080
1081                 si->io.pck_rcv += len;
1082
1083                 break;
1084
1085         case SWRAP_RECV_RST:
1086                 dest_addr = (const struct sockaddr_in *)si->myname;
1087                 src_addr = (const struct sockaddr_in *)si->peername;
1088
1089                 if (si->type == SOCK_DGRAM) {
1090                         return NULL;
1091                 }
1092
1093                 tcp_seqno = si->io.pck_rcv;
1094                 tcp_ack = si->io.pck_snd;
1095                 tcp_ctl = 0x14; /* RST,ACK */
1096
1097                 break;
1098
1099         case SWRAP_SENDTO:
1100                 src_addr = (const struct sockaddr_in *)si->myname;
1101                 dest_addr = (const struct sockaddr_in *)addr;
1102
1103                 si->io.pck_snd += len;
1104
1105                 break;
1106
1107         case SWRAP_SENDTO_UNREACH:
1108                 dest_addr = (const struct sockaddr_in *)si->myname;
1109                 src_addr = (const struct sockaddr_in *)addr;
1110
1111                 unreachable = 1;
1112
1113                 break;
1114
1115         case SWRAP_RECVFROM:
1116                 dest_addr = (const struct sockaddr_in *)si->myname;
1117                 src_addr = (const struct sockaddr_in *)addr;
1118
1119                 si->io.pck_rcv += len;
1120
1121                 break;
1122
1123         case SWRAP_CLOSE_SEND:
1124                 if (si->type != SOCK_STREAM) return NULL;
1125
1126                 src_addr = (const struct sockaddr_in *)si->myname;
1127                 dest_addr = (const struct sockaddr_in *)si->peername;
1128
1129                 tcp_seqno = si->io.pck_snd;
1130                 tcp_ack = si->io.pck_rcv;
1131                 tcp_ctl = 0x11; /* FIN, ACK */
1132
1133                 si->io.pck_snd += 1;
1134
1135                 break;
1136
1137         case SWRAP_CLOSE_RECV:
1138                 if (si->type != SOCK_STREAM) return NULL;
1139
1140                 dest_addr = (const struct sockaddr_in *)si->myname;
1141                 src_addr = (const struct sockaddr_in *)si->peername;
1142
1143                 tcp_seqno = si->io.pck_rcv;
1144                 tcp_ack = si->io.pck_snd;
1145                 tcp_ctl = 0x11; /* FIN,ACK */
1146
1147                 si->io.pck_rcv += 1;
1148
1149                 break;
1150
1151         case SWRAP_CLOSE_ACK:
1152                 if (si->type != SOCK_STREAM) return NULL;
1153
1154                 src_addr = (const struct sockaddr_in *)si->myname;
1155                 dest_addr = (const struct sockaddr_in *)si->peername;
1156
1157                 tcp_seqno = si->io.pck_snd;
1158                 tcp_ack = si->io.pck_rcv;
1159                 tcp_ctl = 0x10; /* ACK */
1160
1161                 break;
1162         default:
1163                 return NULL;
1164         }
1165
1166         swrapGetTimeOfDay(&tv);
1167
1168         return swrap_packet_init(&tv, src_addr, dest_addr, si->type,
1169                                    (const unsigned char *)buf, len,
1170                                    tcp_seqno, tcp_ack, tcp_ctl, unreachable,
1171                                    packet_len);
1172 }
1173
1174 static void swrap_dump_packet(struct socket_info *si, 
1175                                                           const struct sockaddr *addr,
1176                                                           enum swrap_packet_type type,
1177                                                           const void *buf, size_t len)
1178 {
1179         const char *file_name;
1180         struct swrap_packet *packet;
1181         size_t packet_len = 0;
1182         int fd;
1183
1184         file_name = socket_wrapper_pcap_file();
1185         if (!file_name) {
1186                 return;
1187         }
1188
1189         packet = swrap_marshall_packet(si, addr, type, buf, len, &packet_len);
1190         if (!packet) {
1191                 return;
1192         }
1193
1194         fd = swrap_get_pcap_fd(file_name);
1195         if (fd != -1) {
1196                 if (write(fd, packet, packet_len) != packet_len) {
1197                         close(fd);
1198                         free(packet);
1199                         return;
1200                 }
1201                 close(fd);
1202         }
1203
1204         free(packet);
1205 }
1206
1207 _PUBLIC_ int swrap_socket(int family, int type, int protocol)
1208 {
1209         struct socket_info *si;
1210         int fd;
1211
1212         if (!socket_wrapper_dir()) {
1213                 return real_socket(family, type, protocol);
1214         }
1215
1216         switch (family) {
1217         case AF_INET:
1218 #ifdef HAVE_IPV6
1219         case AF_INET6:
1220 #endif
1221                 break;
1222         case AF_UNIX:
1223                 return real_socket(family, type, protocol);
1224         default:
1225                 errno = EAFNOSUPPORT;
1226                 return -1;
1227         }
1228
1229         switch (type) {
1230         case SOCK_STREAM:
1231                 break;
1232         case SOCK_DGRAM:
1233                 break;
1234         default:
1235                 errno = EPROTONOSUPPORT;
1236                 return -1;
1237         }
1238
1239         switch (protocol) {
1240         case 0:
1241                 break;
1242         case 6:
1243                 if (type == SOCK_STREAM) {
1244                         break;
1245                 }
1246                 /*fall through*/
1247         case 17:
1248                 if (type == SOCK_DGRAM) {
1249                         break;
1250                 }
1251                 /*fall through*/
1252         default:
1253                 errno = EPROTONOSUPPORT;
1254                 return -1;
1255         }
1256
1257         fd = real_socket(AF_UNIX, type, 0);
1258
1259         if (fd == -1) return -1;
1260
1261         si = (struct socket_info *)calloc(1, sizeof(struct socket_info));
1262
1263         si->family = family;
1264         si->type = type;
1265         si->protocol = protocol;
1266         si->fd = fd;
1267
1268         SWRAP_DLIST_ADD(sockets, si);
1269
1270         return si->fd;
1271 }
1272
1273 _PUBLIC_ int swrap_accept(int s, struct sockaddr *addr, socklen_t *addrlen)
1274 {
1275         struct socket_info *parent_si, *child_si;
1276         int fd;
1277         struct sockaddr_un un_addr;
1278         socklen_t un_addrlen = sizeof(un_addr);
1279         struct sockaddr_un un_my_addr;
1280         socklen_t un_my_addrlen = sizeof(un_my_addr);
1281         struct sockaddr *my_addr;
1282         socklen_t my_addrlen, len;
1283         int ret;
1284
1285         parent_si = find_socket_info(s);
1286         if (!parent_si) {
1287                 return real_accept(s, addr, addrlen);
1288         }
1289
1290         /* 
1291          * assume out sockaddr have the same size as the in parent
1292          * socket family
1293          */
1294         my_addrlen = socket_length(parent_si->family);
1295         if (my_addrlen <= 0) {
1296                 errno = EINVAL;
1297                 return -1;
1298         }
1299
1300         my_addr = (struct sockaddr *)malloc(my_addrlen);
1301         if (my_addr == NULL) {
1302                 return -1;
1303         }
1304
1305         memset(&un_addr, 0, sizeof(un_addr));
1306         memset(&un_my_addr, 0, sizeof(un_my_addr));
1307
1308         ret = real_accept(s, (struct sockaddr *)&un_addr, &un_addrlen);
1309         if (ret == -1) {
1310                 free(my_addr);
1311                 return ret;
1312         }
1313
1314         fd = ret;
1315
1316         len = my_addrlen;
1317         ret = sockaddr_convert_from_un(parent_si, &un_addr, un_addrlen,
1318                                        parent_si->family, my_addr, &len);
1319         if (ret == -1) {
1320                 free(my_addr);
1321                 close(fd);
1322                 return ret;
1323         }
1324
1325         child_si = (struct socket_info *)malloc(sizeof(struct socket_info));
1326         memset(child_si, 0, sizeof(*child_si));
1327
1328         child_si->fd = fd;
1329         child_si->family = parent_si->family;
1330         child_si->type = parent_si->type;
1331         child_si->protocol = parent_si->protocol;
1332         child_si->bound = 1;
1333         child_si->is_server = 1;
1334
1335         child_si->peername_len = len;
1336         child_si->peername = sockaddr_dup(my_addr, len);
1337
1338         if (addr != NULL && addrlen != NULL) {
1339             *addrlen = len;
1340             if (*addrlen >= len)
1341                 memcpy(addr, my_addr, len);
1342             *addrlen = 0;
1343         }
1344
1345         ret = real_getsockname(fd, (struct sockaddr *)&un_my_addr, &un_my_addrlen);
1346         if (ret == -1) {
1347                 free(child_si);
1348                 close(fd);
1349                 return ret;
1350         }
1351
1352         len = my_addrlen;
1353         ret = sockaddr_convert_from_un(child_si, &un_my_addr, un_my_addrlen,
1354                                        child_si->family, my_addr, &len);
1355         if (ret == -1) {
1356                 free(child_si);
1357                 free(my_addr);
1358                 close(fd);
1359                 return ret;
1360         }
1361
1362         child_si->myname_len = len;
1363         child_si->myname = sockaddr_dup(my_addr, len);
1364         free(my_addr);
1365
1366         SWRAP_DLIST_ADD(sockets, child_si);
1367
1368         swrap_dump_packet(child_si, addr, SWRAP_ACCEPT_SEND, NULL, 0);
1369         swrap_dump_packet(child_si, addr, SWRAP_ACCEPT_RECV, NULL, 0);
1370         swrap_dump_packet(child_si, addr, SWRAP_ACCEPT_ACK, NULL, 0);
1371
1372         return fd;
1373 }
1374
1375 static int autobind_start_init;
1376 static int autobind_start;
1377
1378 /* using sendto() or connect() on an unbound socket would give the
1379    recipient no way to reply, as unlike UDP and TCP, a unix domain
1380    socket can't auto-assign emphemeral port numbers, so we need to
1381    assign it here */
1382 static int swrap_auto_bind(struct socket_info *si)
1383 {
1384         struct sockaddr_un un_addr;
1385         int i;
1386         char type;
1387         int ret;
1388         int port;
1389         struct stat st;
1390
1391         if (autobind_start_init != 1) {
1392                 autobind_start_init = 1;
1393                 autobind_start = getpid();
1394                 autobind_start %= 50000;
1395                 autobind_start += 10000;
1396         }
1397
1398         un_addr.sun_family = AF_UNIX;
1399
1400         switch (si->family) {
1401         case AF_INET: {
1402                 struct sockaddr_in in;
1403
1404                 switch (si->type) {
1405                 case SOCK_STREAM:
1406                         type = SOCKET_TYPE_CHAR_TCP;
1407                         break;
1408                 case SOCK_DGRAM:
1409                         type = SOCKET_TYPE_CHAR_UDP;
1410                         break;
1411                 default:
1412                     errno = ESOCKTNOSUPPORT;
1413                     return -1;
1414                 }
1415
1416                 memset(&in, 0, sizeof(in));
1417                 in.sin_family = AF_INET;
1418                 in.sin_addr.s_addr = htonl(127<<24 | 
1419                                            socket_wrapper_default_iface());
1420
1421                 si->myname_len = sizeof(in);
1422                 si->myname = sockaddr_dup(&in, si->myname_len);
1423                 break;
1424         }
1425 #ifdef HAVE_IPV6
1426         case AF_INET6: {
1427                 struct sockaddr_in6 in6;
1428
1429                 switch (si->type) {
1430                 case SOCK_STREAM:
1431                         type = SOCKET_TYPE_CHAR_TCP_V6;
1432                         break;
1433                 case SOCK_DGRAM:
1434                         type = SOCKET_TYPE_CHAR_UDP_V6;
1435                         break;
1436                 default:
1437                     errno = ESOCKTNOSUPPORT;
1438                     return -1;
1439                 }
1440
1441                 memset(&in6, 0, sizeof(in6));
1442                 in6.sin6_family = AF_INET6;
1443                 in6.sin6_addr.s6_addr[0] = SW_IPV6_ADDRESS;
1444                 si->myname_len = sizeof(in6);
1445                 si->myname = sockaddr_dup(&in6, si->myname_len);
1446                 break;
1447         }
1448 #endif
1449         default:
1450                 errno = ESOCKTNOSUPPORT;
1451                 return -1;
1452         }
1453
1454         if (autobind_start > 60000) {
1455                 autobind_start = 10000;
1456         }
1457
1458         for (i=0;i<1000;i++) {
1459                 port = autobind_start + i;
1460                 snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), 
1461                          "%s/"SOCKET_FORMAT, socket_wrapper_dir(),
1462                          type, socket_wrapper_default_iface(), port);
1463                 if (stat(un_addr.sun_path, &st) == 0) continue;
1464                 
1465                 ret = real_bind(si->fd, (struct sockaddr *)&un_addr, sizeof(un_addr));
1466                 if (ret == -1) return ret;
1467
1468                 si->tmp_path = strdup(un_addr.sun_path);
1469                 si->bound = 1;
1470                 autobind_start = port + 1;
1471                 break;
1472         }
1473         if (i == 1000) {
1474                 errno = ENFILE;
1475                 return -1;
1476         }
1477
1478         set_port(si->family, port, si->myname);
1479
1480         return 0;
1481 }
1482
1483
1484 _PUBLIC_ int swrap_connect(int s, const struct sockaddr *serv_addr, socklen_t addrlen)
1485 {
1486         int ret;
1487         struct sockaddr_un un_addr;
1488         struct socket_info *si = find_socket_info(s);
1489
1490         if (!si) {
1491                 return real_connect(s, serv_addr, addrlen);
1492         }
1493
1494         if (si->bound == 0) {
1495                 ret = swrap_auto_bind(si);
1496                 if (ret == -1) return -1;
1497         }
1498
1499         if (si->family != serv_addr->sa_family) {
1500                 errno = EINVAL;
1501                 return -1;
1502         }
1503
1504         ret = sockaddr_convert_to_un(si, (const struct sockaddr *)serv_addr, addrlen, &un_addr, 0, NULL);
1505         if (ret == -1) return -1;
1506
1507         swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_SEND, NULL, 0);
1508
1509         ret = real_connect(s, (struct sockaddr *)&un_addr, 
1510                            sizeof(struct sockaddr_un));
1511
1512         /* to give better errors */
1513         if (ret == -1 && errno == ENOENT) {
1514                 errno = EHOSTUNREACH;
1515         }
1516
1517         if (ret == 0) {
1518                 si->peername_len = addrlen;
1519                 si->peername = sockaddr_dup(serv_addr, addrlen);
1520
1521                 swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_RECV, NULL, 0);
1522                 swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_ACK, NULL, 0);
1523         } else {
1524                 swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_UNREACH, NULL, 0);
1525         }
1526
1527         return ret;
1528 }
1529
1530 _PUBLIC_ int swrap_bind(int s, const struct sockaddr *myaddr, socklen_t addrlen)
1531 {
1532         int ret;
1533         struct sockaddr_un un_addr;
1534         struct socket_info *si = find_socket_info(s);
1535
1536         if (!si) {
1537                 return real_bind(s, myaddr, addrlen);
1538         }
1539
1540         si->myname_len = addrlen;
1541         si->myname = sockaddr_dup(myaddr, addrlen);
1542
1543         ret = sockaddr_convert_to_un(si, (const struct sockaddr *)myaddr, addrlen, &un_addr, 1, &si->bcast);
1544         if (ret == -1) return -1;
1545
1546         unlink(un_addr.sun_path);
1547
1548         ret = real_bind(s, (struct sockaddr *)&un_addr,
1549                         sizeof(struct sockaddr_un));
1550
1551         if (ret == 0) {
1552                 si->bound = 1;
1553         }
1554
1555         return ret;
1556 }
1557
1558 _PUBLIC_ int swrap_listen(int s, int backlog)
1559 {
1560         int ret;
1561         struct socket_info *si = find_socket_info(s);
1562
1563         if (!si) {
1564                 return real_listen(s, backlog);
1565         }
1566
1567         ret = real_listen(s, backlog);
1568
1569         return ret;
1570 }
1571
1572 _PUBLIC_ int swrap_getpeername(int s, struct sockaddr *name, socklen_t *addrlen)
1573 {
1574         struct socket_info *si = find_socket_info(s);
1575
1576         if (!si) {
1577                 return real_getpeername(s, name, addrlen);
1578         }
1579
1580         if (!si->peername)
1581         {
1582                 errno = ENOTCONN;
1583                 return -1;
1584         }
1585
1586         memcpy(name, si->peername, si->peername_len);
1587         *addrlen = si->peername_len;
1588
1589         return 0;
1590 }
1591
1592 _PUBLIC_ int swrap_getsockname(int s, struct sockaddr *name, socklen_t *addrlen)
1593 {
1594         struct socket_info *si = find_socket_info(s);
1595
1596         if (!si) {
1597                 return real_getsockname(s, name, addrlen);
1598         }
1599
1600         memcpy(name, si->myname, si->myname_len);
1601         *addrlen = si->myname_len;
1602
1603         return 0;
1604 }
1605
1606 _PUBLIC_ int swrap_getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen)
1607 {
1608         struct socket_info *si = find_socket_info(s);
1609
1610         if (!si) {
1611                 return real_getsockopt(s, level, optname, optval, optlen);
1612         }
1613
1614         if (level == SOL_SOCKET) {
1615                 return real_getsockopt(s, level, optname, optval, optlen);
1616         } 
1617
1618         errno = ENOPROTOOPT;
1619         return -1;
1620 }
1621
1622 _PUBLIC_ int swrap_setsockopt(int s, int  level,  int  optname,  const  void  *optval, socklen_t optlen)
1623 {
1624         struct socket_info *si = find_socket_info(s);
1625
1626         if (!si) {
1627                 return real_setsockopt(s, level, optname, optval, optlen);
1628         }
1629
1630         if (level == SOL_SOCKET) {
1631                 return real_setsockopt(s, level, optname, optval, optlen);
1632         }
1633
1634         switch (si->family) {
1635         case AF_INET:
1636                 return 0;
1637         default:
1638                 errno = ENOPROTOOPT;
1639                 return -1;
1640         }
1641 }
1642
1643 _PUBLIC_ ssize_t swrap_recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen)
1644 {
1645         struct sockaddr_un un_addr;
1646         socklen_t un_addrlen = sizeof(un_addr);
1647         int ret;
1648         struct socket_info *si = find_socket_info(s);
1649
1650         if (!si) {
1651                 return real_recvfrom(s, buf, len, flags, from, fromlen);
1652         }
1653
1654         len = MIN(len, 1500);
1655
1656         /* irix 6.4 forgets to null terminate the sun_path string :-( */
1657         memset(&un_addr, 0, sizeof(un_addr));
1658         ret = real_recvfrom(s, buf, len, flags, (struct sockaddr *)&un_addr, &un_addrlen);
1659         if (ret == -1) 
1660                 return ret;
1661
1662         if (sockaddr_convert_from_un(si, &un_addr, un_addrlen,
1663                                      si->family, from, fromlen) == -1) {
1664                 return -1;
1665         }
1666
1667         swrap_dump_packet(si, from, SWRAP_RECVFROM, buf, ret);
1668
1669         return ret;
1670 }
1671
1672
1673 _PUBLIC_ ssize_t swrap_sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen)
1674 {
1675         struct sockaddr_un un_addr;
1676         int ret;
1677         struct socket_info *si = find_socket_info(s);
1678         int bcast = 0;
1679
1680         if (!si) {
1681                 return real_sendto(s, buf, len, flags, to, tolen);
1682         }
1683
1684         len = MIN(len, 1500);
1685
1686         switch (si->type) {
1687         case SOCK_STREAM:
1688                 ret = real_send(s, buf, len, flags);
1689                 break;
1690         case SOCK_DGRAM:
1691                 if (si->bound == 0) {
1692                         ret = swrap_auto_bind(si);
1693                         if (ret == -1) return -1;
1694                 }
1695                 
1696                 ret = sockaddr_convert_to_un(si, to, tolen, &un_addr, 0, &bcast);
1697                 if (ret == -1) return -1;
1698                 
1699                 if (bcast) {
1700                         struct stat st;
1701                         unsigned int iface;
1702                         unsigned int prt = ntohs(((const struct sockaddr_in *)to)->sin_port);
1703                         char type;
1704                         
1705                         type = SOCKET_TYPE_CHAR_UDP;
1706                         
1707                         for(iface=0; iface <= MAX_WRAPPED_INTERFACES; iface++) {
1708                                 snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s/"SOCKET_FORMAT, 
1709                                          socket_wrapper_dir(), type, iface, prt);
1710                                 if (stat(un_addr.sun_path, &st) != 0) continue;
1711                                 
1712                                 /* ignore the any errors in broadcast sends */
1713                                 real_sendto(s, buf, len, flags, (struct sockaddr *)&un_addr, sizeof(un_addr));
1714                         }
1715                         
1716                         swrap_dump_packet(si, to, SWRAP_SENDTO, buf, len);
1717                         
1718                         return len;
1719                 }
1720                 
1721                 ret = real_sendto(s, buf, len, flags, (struct sockaddr *)&un_addr, sizeof(un_addr));
1722                 break;
1723         default:
1724                 ret = -1;
1725                 errno = EHOSTUNREACH;
1726                 break;
1727         }
1728                 
1729         /* to give better errors */
1730         if (ret == -1 && errno == ENOENT) {
1731                 errno = EHOSTUNREACH;
1732         }
1733
1734         if (ret == -1) {
1735                 swrap_dump_packet(si, to, SWRAP_SENDTO, buf, len);
1736                 swrap_dump_packet(si, to, SWRAP_SENDTO_UNREACH, buf, len);
1737         } else {
1738                 swrap_dump_packet(si, to, SWRAP_SENDTO, buf, ret);
1739         }
1740
1741         return ret;
1742 }
1743
1744 _PUBLIC_ int swrap_ioctl(int s, int r, void *p)
1745 {
1746         int ret;
1747         struct socket_info *si = find_socket_info(s);
1748         int value;
1749
1750         if (!si) {
1751                 return real_ioctl(s, r, p);
1752         }
1753
1754         ret = real_ioctl(s, r, p);
1755
1756         switch (r) {
1757         case FIONREAD:
1758                 value = *((int *)p);
1759                 if (ret == -1 && errno != EAGAIN && errno != ENOBUFS) {
1760                         swrap_dump_packet(si, NULL, SWRAP_PENDING_RST, NULL, 0);
1761                 } else if (value == 0) { /* END OF FILE */
1762                         swrap_dump_packet(si, NULL, SWRAP_PENDING_RST, NULL, 0);
1763                 }
1764                 break;
1765         }
1766
1767         return ret;
1768 }
1769
1770 _PUBLIC_ ssize_t swrap_recv(int s, void *buf, size_t len, int flags)
1771 {
1772         int ret;
1773         struct socket_info *si = find_socket_info(s);
1774
1775         if (!si) {
1776                 return real_recv(s, buf, len, flags);
1777         }
1778
1779         len = MIN(len, 1500);
1780
1781         ret = real_recv(s, buf, len, flags);
1782         if (ret == -1 && errno != EAGAIN && errno != ENOBUFS) {
1783                 swrap_dump_packet(si, NULL, SWRAP_RECV_RST, NULL, 0);
1784         } else if (ret == 0) { /* END OF FILE */
1785                 swrap_dump_packet(si, NULL, SWRAP_RECV_RST, NULL, 0);
1786         } else {
1787                 swrap_dump_packet(si, NULL, SWRAP_RECV, buf, ret);
1788         }
1789
1790         return ret;
1791 }
1792
1793
1794 _PUBLIC_ ssize_t swrap_send(int s, const void *buf, size_t len, int flags)
1795 {
1796         int ret;
1797         struct socket_info *si = find_socket_info(s);
1798
1799         if (!si) {
1800                 return real_send(s, buf, len, flags);
1801         }
1802
1803         len = MIN(len, 1500);
1804
1805         ret = real_send(s, buf, len, flags);
1806
1807         if (ret == -1) {
1808                 swrap_dump_packet(si, NULL, SWRAP_SEND, buf, len);
1809                 swrap_dump_packet(si, NULL, SWRAP_SEND_RST, NULL, 0);
1810         } else {
1811                 swrap_dump_packet(si, NULL, SWRAP_SEND, buf, ret);
1812         }
1813
1814         return ret;
1815 }
1816
1817 _PUBLIC_ int swrap_close(int fd)
1818 {
1819         struct socket_info *si = find_socket_info(fd);
1820         int ret;
1821
1822         if (!si) {
1823                 return real_close(fd);
1824         }
1825
1826         SWRAP_DLIST_REMOVE(sockets, si);
1827
1828         if (si->myname && si->peername) {
1829                 swrap_dump_packet(si, NULL, SWRAP_CLOSE_SEND, NULL, 0);
1830         }
1831
1832         ret = real_close(fd);
1833
1834         if (si->myname && si->peername) {
1835                 swrap_dump_packet(si, NULL, SWRAP_CLOSE_RECV, NULL, 0);
1836                 swrap_dump_packet(si, NULL, SWRAP_CLOSE_ACK, NULL, 0);
1837         }
1838
1839         if (si->path) free(si->path);
1840         if (si->myname) free(si->myname);
1841         if (si->peername) free(si->peername);
1842         if (si->tmp_path) {
1843                 unlink(si->tmp_path);
1844                 free(si->tmp_path);
1845         }
1846         free(si);
1847
1848         return ret;
1849 }