938d8aeccdb20ec720b60c94e703e08eb59146d8
[p5sagit/p5-mst-13.2.git] / ext / Socket / Socket.xs
1 #define PERL_NO_GET_CONTEXT
2 #include "EXTERN.h"
3 #include "perl.h"
4 #include "XSUB.h"
5
6 #ifndef VMS
7 # ifdef I_SYS_TYPES
8 #  include <sys/types.h>
9 # endif
10 # include <sys/socket.h>
11 # if defined(USE_SOCKS) && defined(I_SOCKS)
12 #   include <socks.h>
13 # endif
14 # ifdef MPE
15 #  define PF_INET AF_INET
16 #  define PF_UNIX AF_UNIX
17 #  define SOCK_RAW 3
18 # endif
19 # ifdef I_SYS_UN
20 #  include <sys/un.h>
21 # endif
22 /* XXX Configure test for <netinet/in_systm.h needed XXX */
23 # if defined(NeXT) || defined(__NeXT__)
24 #  include <netinet/in_systm.h>
25 # endif
26 # ifdef I_NETINET_IN
27 #  include <netinet/in.h>
28 # endif
29 # ifdef I_NETDB
30 #  include <netdb.h>
31 # endif
32 # ifdef I_ARPA_INET
33 #  include <arpa/inet.h>
34 # endif
35 # ifdef I_NETINET_TCP
36 #  include <netinet/tcp.h>
37 # endif
38 #else
39 # include "sockadapt.h"
40 #endif
41
42 #ifdef NETWARE
43 NETDB_DEFINE_CONTEXT
44 NETINET_DEFINE_CONTEXT
45 #endif
46
47 #ifdef I_SYSUIO
48 # include <sys/uio.h>
49 #endif
50
51 #ifndef AF_NBS
52 # undef PF_NBS
53 #endif
54
55 #ifndef AF_X25
56 # undef PF_X25
57 #endif
58
59 #ifndef INADDR_NONE
60 # define INADDR_NONE    0xffffffff
61 #endif /* INADDR_NONE */
62 #ifndef INADDR_BROADCAST
63 # define INADDR_BROADCAST       0xffffffff
64 #endif /* INADDR_BROADCAST */
65 #ifndef INADDR_LOOPBACK
66 # define INADDR_LOOPBACK         0x7F000001
67 #endif /* INADDR_LOOPBACK */
68
69 #ifndef HAS_INET_ATON
70
71 /*
72  * Check whether "cp" is a valid ascii representation
73  * of an Internet address and convert to a binary address.
74  * Returns 1 if the address is valid, 0 if not.
75  * This replaces inet_addr, the return value from which
76  * cannot distinguish between failure and a local broadcast address.
77  */
78 static int
79 my_inet_aton(register const char *cp, struct in_addr *addr)
80 {
81         dTHX;
82         register U32 val;
83         register int base;
84         register char c;
85         int nparts;
86         const char *s;
87         unsigned int parts[4];
88         register unsigned int *pp = parts;
89
90         if (!cp)
91                 return 0;
92         for (;;) {
93                 /*
94                  * Collect number up to ``.''.
95                  * Values are specified as for C:
96                  * 0x=hex, 0=octal, other=decimal.
97                  */
98                 val = 0; base = 10;
99                 if (*cp == '0') {
100                         if (*++cp == 'x' || *cp == 'X')
101                                 base = 16, cp++;
102                         else
103                                 base = 8;
104                 }
105                 while ((c = *cp) != '\0') {
106                         if (isDIGIT(c)) {
107                                 val = (val * base) + (c - '0');
108                                 cp++;
109                                 continue;
110                         }
111                         if (base == 16 && (s=strchr(PL_hexdigit,c))) {
112                                 val = (val << 4) +
113                                         ((s - PL_hexdigit) & 15);
114                                 cp++;
115                                 continue;
116                         }
117                         break;
118                 }
119                 if (*cp == '.') {
120                         /*
121                          * Internet format:
122                          *      a.b.c.d
123                          *      a.b.c   (with c treated as 16-bits)
124                          *      a.b     (with b treated as 24 bits)
125                          */
126                         if (pp >= parts + 3 || val > 0xff)
127                                 return 0;
128                         *pp++ = val, cp++;
129                 } else
130                         break;
131         }
132         /*
133          * Check for trailing characters.
134          */
135         if (*cp && !isSPACE(*cp))
136                 return 0;
137         /*
138          * Concoct the address according to
139          * the number of parts specified.
140          */
141         nparts = pp - parts + 1;        /* force to an int for switch() */
142         switch (nparts) {
143
144         case 1:                         /* a -- 32 bits */
145                 break;
146
147         case 2:                         /* a.b -- 8.24 bits */
148                 if (val > 0xffffff)
149                         return 0;
150                 val |= parts[0] << 24;
151                 break;
152
153         case 3:                         /* a.b.c -- 8.8.16 bits */
154                 if (val > 0xffff)
155                         return 0;
156                 val |= (parts[0] << 24) | (parts[1] << 16);
157                 break;
158
159         case 4:                         /* a.b.c.d -- 8.8.8.8 bits */
160                 if (val > 0xff)
161                         return 0;
162                 val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
163                 break;
164         }
165         addr->s_addr = htonl(val);
166         return 1;
167 }
168
169 #undef inet_aton
170 #define inet_aton my_inet_aton
171
172 #endif /* ! HAS_INET_ATON */
173
174
175 static int
176 not_here(char *s)
177 {
178     croak("Socket::%s not implemented on this architecture", s);
179     return -1;
180 }
181
182 #include "constants.c"
183
184 #define PERL_IN_ADDR_S_ADDR_SIZE 4
185
186 /*
187  * Bad assumptions possible here.
188  *
189  * Bad Assumption 1: struct in_addr has no other fields
190  * than the s_addr (which is the field we care about
191  * in here, really). However, we can be fed either 4-byte
192  * addresses (from pack("N", ...), or va.b.c.d, or ...),
193  * or full struct in_addrs (from e.g. pack_sockaddr_in()),
194  * which may or may not be 4 bytes in size.
195  *
196  * Bad Assumption 2: the s_addr field is a simple type
197  * (such as an int, u_int32_t).  It can be a bit field,
198  * in which case using & (address-of) on it or taking sizeof()
199  * wouldn't go over too well.  (Those are not attempted
200  * now but in case someone thinks to change the below code
201  * to use addr.s_addr instead of addr, you have been warned.)
202  *
203  * Bad Assumption 3: the s_addr is the first field in
204  * an in_addr, or that its bytes are the first bytes in
205  * an in_addr.
206  *
207  * These bad assumptions are wrong in UNICOS which has
208  * struct in_addr { struct { u_long  st_addr:32; } s_da };
209  * #define s_addr s_da.st_addr
210  * and u_long is 64 bits.
211  *
212  * --jhi */
213
214 MODULE = Socket         PACKAGE = Socket
215
216 INCLUDE: constants.xs
217
218 void
219 inet_aton(host)
220         char *  host
221         CODE:
222         {
223         struct in_addr addr;
224         char saddr[PERL_IN_ADDR_S_ADDR_SIZE];
225         struct hostent * phe;
226         int ok;
227
228         ok = inet_aton(host, &addr);
229         if (ok) {
230                 saddr[0] = (addr.s_addr >> 24) & 0xFF;
231                 saddr[1] = (addr.s_addr >> 16) & 0xFF;
232                 saddr[2] = (addr.s_addr >>  8) & 0xFF;
233                 saddr[3] = (addr.s_addr      ) & 0xFF;
234         }
235         else if (phe = gethostbyname(host)) {
236                 Copy( phe->h_addr, saddr, phe->h_length, char );
237                 ok = 1;
238         }
239
240         ST(0) = sv_newmortal();
241         if (ok) {
242                 sv_setpvn( ST(0), saddr, PERL_IN_ADDR_S_ADDR_SIZE);
243         }
244         }
245
246 void
247 inet_ntoa(ip_address_sv)
248         SV *    ip_address_sv
249         CODE:
250         {
251         STRLEN addrlen;
252         struct in_addr addr;
253         char * addr_str;
254         char * ip_address;
255         if (DO_UTF8(ip_address_sv) && !sv_utf8_downgrade(ip_address_sv, 1))
256              croak("Wide character in Socket::inet_ntoa");
257         ip_address = SvPV(ip_address_sv, addrlen);
258         if (addrlen == PERL_IN_ADDR_S_ADDR_SIZE) {
259              /* It must be (better be) a network-order 32-bit integer.
260               * We can't use any fancy casting of ip_address to pointer ofn
261               * some type (int or long) and the dereferencing that sincen
262               * neither int not long is guaranteed to be 32 bits. */
263              addr.s_addr  = (ip_address[0] & 0xFF) << 24;
264              addr.s_addr |= (ip_address[1] & 0xFF) << 16;
265              addr.s_addr |= (ip_address[2] & 0xFF) <<  8;
266              addr.s_addr |= (ip_address[3] & 0xFF);
267         }
268         else {
269              /* It could be a struct in_addr that is not 32 bits. */
270
271              if (addrlen == sizeof(addr))
272                   /* This branch could be optimized away if we knew
273                    * during compile time what size is struct in_addr.
274                    * If it's four, the above code should have worked. */
275                   Copy( ip_address, &addr, sizeof addr, char );
276              else {
277                   if (PERL_IN_ADDR_S_ADDR_SIZE == sizeof(addr))
278                        croak("Bad arg length for %s, length is %d, should be %d",
279                              "Socket::inet_ntoa",
280                              addrlen, PERL_IN_ADDR_S_ADDR_SIZE);
281                   else 
282                        croak("Bad arg length for %s, length is %d, should be %d or %d",
283                              "Socket::inet_ntoa",
284                              addrlen, PERL_IN_ADDR_S_ADDR_SIZE, sizeof(addr));
285              }
286         }
287         /* We could use inet_ntoa() but that is broken
288          * in HP-UX + GCC + 64bitint (returns "0.0.0.0"),
289          * so let's use this sprintf() workaround everywhere. */
290         New(1138, addr_str, 4 * 3 + 3 + 1, char);
291         sprintf(addr_str, "%d.%d.%d.%d",
292                 ((addr.s_addr >> 24) & 0xFF),
293                 ((addr.s_addr >> 16) & 0xFF),
294                 ((addr.s_addr >>  8) & 0xFF),
295                 ( addr.s_addr        & 0xFF));
296         ST(0) = sv_2mortal(newSVpvn(addr_str, strlen(addr_str)));
297         Safefree(addr_str);
298         }
299
300 void
301 pack_sockaddr_un(pathname)
302         char *  pathname
303         CODE:
304         {
305 #ifdef I_SYS_UN
306         struct sockaddr_un sun_ad; /* fear using sun */
307         STRLEN len;
308
309         Zero( &sun_ad, sizeof sun_ad, char );
310         sun_ad.sun_family = AF_UNIX;
311         len = strlen(pathname);
312         if (len > sizeof(sun_ad.sun_path))
313             len = sizeof(sun_ad.sun_path);
314 #  ifdef OS2    /* Name should start with \socket\ and contain backslashes! */
315         {
316             int off;
317             char *s, *e;
318
319             if (pathname[0] != '/' && pathname[0] != '\\')
320                 croak("Relative UNIX domain socket name '%s' unsupported", pathname);
321             else if (len < 8
322                      || pathname[7] != '/' && pathname[7] != '\\'
323                      || !strnicmp(pathname + 1, "socket", 6))
324                 off = 7;
325             else
326                 off = 0;                /* Preserve names starting with \socket\ */
327             Copy( "\\socket", sun_ad.sun_path, off, char);
328             Copy( pathname, sun_ad.sun_path + off, len, char );
329
330             s = sun_ad.sun_path + off - 1;
331             e = s + len + 1;
332             while (++s < e)
333                 if (*s = '/')
334                     *s = '\\';
335         }
336 #  else /* !( defined OS2 ) */
337         Copy( pathname, sun_ad.sun_path, len, char );
338 #  endif
339         if (0) not_here("dummy");
340         ST(0) = sv_2mortal(newSVpvn((char *)&sun_ad, sizeof sun_ad));
341 #else
342         ST(0) = (SV *) not_here("pack_sockaddr_un");
343 #endif
344         
345         }
346
347 void
348 unpack_sockaddr_un(sun_sv)
349         SV *    sun_sv
350         CODE:
351         {
352 #ifdef I_SYS_UN
353         struct sockaddr_un addr;
354         STRLEN sockaddrlen;
355         char * sun_ad = SvPV(sun_sv,sockaddrlen);
356         char * e;
357 #   ifndef __linux__
358         /* On Linux sockaddrlen on sockets returned by accept, recvfrom,
359            getpeername and getsockname is not equal to sizeof(addr). */
360         if (sockaddrlen != sizeof(addr)) {
361             croak("Bad arg length for %s, length is %d, should be %d",
362                         "Socket::unpack_sockaddr_un",
363                         sockaddrlen, sizeof(addr));
364         }
365 #   endif
366
367         Copy( sun_ad, &addr, sizeof addr, char );
368
369         if ( addr.sun_family != AF_UNIX ) {
370             croak("Bad address family for %s, got %d, should be %d",
371                         "Socket::unpack_sockaddr_un",
372                         addr.sun_family,
373                         AF_UNIX);
374         }
375         e = addr.sun_path;
376         while (*e && e < addr.sun_path + sizeof addr.sun_path)
377             ++e;
378         ST(0) = sv_2mortal(newSVpvn(addr.sun_path, e - addr.sun_path));
379 #else
380         ST(0) = (SV *) not_here("unpack_sockaddr_un");
381 #endif
382         }
383
384 void
385 pack_sockaddr_in(port,ip_address)
386         unsigned short  port
387         char *  ip_address
388         CODE:
389         {
390         struct sockaddr_in sin;
391
392         Zero( &sin, sizeof sin, char );
393         sin.sin_family = AF_INET;
394         sin.sin_port = htons(port);
395         Copy( ip_address, &sin.sin_addr, sizeof sin.sin_addr, char );
396
397         ST(0) = sv_2mortal(newSVpvn((char *)&sin, sizeof sin));
398         }
399
400 void
401 unpack_sockaddr_in(sin_sv)
402         SV *    sin_sv
403         PPCODE:
404         {
405         STRLEN sockaddrlen;
406         struct sockaddr_in addr;
407         unsigned short  port;
408         struct in_addr  ip_address;
409         char saddr[PERL_IN_ADDR_S_ADDR_SIZE];
410         char *  sin = SvPV(sin_sv,sockaddrlen);
411         if (sockaddrlen != sizeof(addr)) {
412             croak("Bad arg length for %s, length is %d, should be %d",
413                         "Socket::unpack_sockaddr_in",
414                         sockaddrlen, sizeof(addr));
415         }
416         Copy( sin, &addr,sizeof addr, char );
417         if ( addr.sin_family != AF_INET ) {
418             croak("Bad address family for %s, got %d, should be %d",
419                         "Socket::unpack_sockaddr_in",
420                         addr.sin_family,
421                         AF_INET);
422         }
423         port = ntohs(addr.sin_port);
424         ip_address = addr.sin_addr;
425         saddr[0] = (ip_address.s_addr >> 24) & 0xFF;
426         saddr[1] = (ip_address.s_addr >> 16) & 0xFF;
427         saddr[2] = (ip_address.s_addr >>  8) & 0xFF;
428         saddr[3] = (ip_address.s_addr      ) & 0xFF;
429
430         EXTEND(SP, 2);
431         PUSHs(sv_2mortal(newSViv((IV) port)));
432         PUSHs(sv_2mortal(newSVpvn(saddr, PERL_IN_ADDR_S_ADDR_SIZE)));
433         }