This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Conditionally set sa_len-type fields when packing sockaddr addresses
[perl5.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 #include <stddef.h>
7
8 #ifndef VMS
9 # ifdef I_SYS_TYPES
10 #  include <sys/types.h>
11 # endif
12 # if !defined(ultrix) /* Avoid double definition. */
13 #   include <sys/socket.h>
14 # endif
15 # if defined(USE_SOCKS) && defined(I_SOCKS)
16 #   include <socks.h>
17 # endif
18 # ifdef MPE
19 #  define PF_INET AF_INET
20 #  define PF_UNIX AF_UNIX
21 #  define SOCK_RAW 3
22 # endif
23 # ifdef I_SYS_UN
24 #  include <sys/un.h>
25 # endif
26 /* XXX Configure test for <netinet/in_systm.h needed XXX */
27 # if defined(NeXT) || defined(__NeXT__)
28 #  include <netinet/in_systm.h>
29 # endif
30 # if defined(__sgi) && !defined(AF_LINK) && defined(PF_LINK) && PF_LINK == AF_LNK
31 #  undef PF_LINK
32 # endif
33 # if defined(I_NETINET_IN) || defined(__ultrix__)
34 #  include <netinet/in.h>
35 # endif
36 # ifdef I_NETDB
37 #  if !defined(ultrix)  /* Avoid double definition. */
38 #   include <netdb.h>
39 #  endif
40 # endif
41 # ifdef I_ARPA_INET
42 #  include <arpa/inet.h>
43 # endif
44 # ifdef I_NETINET_TCP
45 #  include <netinet/tcp.h>
46 # endif
47 #else
48 # include "sockadapt.h"
49 #endif
50
51 #ifdef NETWARE
52 NETDB_DEFINE_CONTEXT
53 NETINET_DEFINE_CONTEXT
54 #endif
55
56 #ifdef I_SYSUIO
57 # include <sys/uio.h>
58 #endif
59
60 #ifndef AF_NBS
61 # undef PF_NBS
62 #endif
63
64 #ifndef AF_X25
65 # undef PF_X25
66 #endif
67
68 #ifndef INADDR_NONE
69 # define INADDR_NONE    0xffffffff
70 #endif /* INADDR_NONE */
71 #ifndef INADDR_BROADCAST
72 # define INADDR_BROADCAST       0xffffffff
73 #endif /* INADDR_BROADCAST */
74 #ifndef INADDR_LOOPBACK
75 # define INADDR_LOOPBACK         0x7F000001
76 #endif /* INADDR_LOOPBACK */
77
78 #ifndef HAS_INET_ATON
79
80 /*
81  * Check whether "cp" is a valid ascii representation
82  * of an Internet address and convert to a binary address.
83  * Returns 1 if the address is valid, 0 if not.
84  * This replaces inet_addr, the return value from which
85  * cannot distinguish between failure and a local broadcast address.
86  */
87 static int
88 my_inet_aton(register const char *cp, struct in_addr *addr)
89 {
90         dTHX;
91         register U32 val;
92         register int base;
93         register char c;
94         int nparts;
95         const char *s;
96         unsigned int parts[4];
97         register unsigned int *pp = parts;
98
99        if (!cp || !*cp)
100                 return 0;
101         for (;;) {
102                 /*
103                  * Collect number up to ``.''.
104                  * Values are specified as for C:
105                  * 0x=hex, 0=octal, other=decimal.
106                  */
107                 val = 0; base = 10;
108                 if (*cp == '0') {
109                         if (*++cp == 'x' || *cp == 'X')
110                                 base = 16, cp++;
111                         else
112                                 base = 8;
113                 }
114                 while ((c = *cp) != '\0') {
115                         if (isDIGIT(c)) {
116                                 val = (val * base) + (c - '0');
117                                 cp++;
118                                 continue;
119                         }
120                         if (base == 16 && (s=strchr(PL_hexdigit,c))) {
121                                 val = (val << 4) +
122                                         ((s - PL_hexdigit) & 15);
123                                 cp++;
124                                 continue;
125                         }
126                         break;
127                 }
128                 if (*cp == '.') {
129                         /*
130                          * Internet format:
131                          *      a.b.c.d
132                          *      a.b.c   (with c treated as 16-bits)
133                          *      a.b     (with b treated as 24 bits)
134                          */
135                         if (pp >= parts + 3 || val > 0xff)
136                                 return 0;
137                         *pp++ = val, cp++;
138                 } else
139                         break;
140         }
141         /*
142          * Check for trailing characters.
143          */
144         if (*cp && !isSPACE(*cp))
145                 return 0;
146         /*
147          * Concoct the address according to
148          * the number of parts specified.
149          */
150         nparts = pp - parts + 1;        /* force to an int for switch() */
151         switch (nparts) {
152
153         case 1:                         /* a -- 32 bits */
154                 break;
155
156         case 2:                         /* a.b -- 8.24 bits */
157                 if (val > 0xffffff)
158                         return 0;
159                 val |= parts[0] << 24;
160                 break;
161
162         case 3:                         /* a.b.c -- 8.8.16 bits */
163                 if (val > 0xffff)
164                         return 0;
165                 val |= (parts[0] << 24) | (parts[1] << 16);
166                 break;
167
168         case 4:                         /* a.b.c.d -- 8.8.8.8 bits */
169                 if (val > 0xff)
170                         return 0;
171                 val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
172                 break;
173         }
174         addr->s_addr = htonl(val);
175         return 1;
176 }
177
178 #undef inet_aton
179 #define inet_aton my_inet_aton
180
181 #endif /* ! HAS_INET_ATON */
182
183
184 static int
185 not_here(const char *s)
186 {
187     croak("Socket::%s not implemented on this architecture", s);
188     return -1;
189 }
190
191 #define PERL_IN_ADDR_S_ADDR_SIZE 4
192
193 /*
194 * Bad assumptions possible here.
195 *
196 * Bad Assumption 1: struct in_addr has no other fields
197 * than the s_addr (which is the field we care about
198 * in here, really). However, we can be fed either 4-byte
199 * addresses (from pack("N", ...), or va.b.c.d, or ...),
200 * or full struct in_addrs (from e.g. pack_sockaddr_in()),
201 * which may or may not be 4 bytes in size.
202 *
203 * Bad Assumption 2: the s_addr field is a simple type
204 * (such as an int, u_int32_t).  It can be a bit field,
205 * in which case using & (address-of) on it or taking sizeof()
206 * wouldn't go over too well.  (Those are not attempted
207 * now but in case someone thinks to change the below code
208 * to use addr.s_addr instead of addr, you have been warned.)
209 *
210 * Bad Assumption 3: the s_addr is the first field in
211 * an in_addr, or that its bytes are the first bytes in
212 * an in_addr.
213 *
214 * These bad assumptions are wrong in UNICOS which has
215 * struct in_addr { struct { u_long  st_addr:32; } s_da };
216 * #define s_addr s_da.st_addr
217 * and u_long is 64 bits.
218 *
219 * --jhi */
220
221 #include "const-c.inc"
222
223 MODULE = Socket         PACKAGE = Socket
224
225 INCLUDE: const-xs.inc
226
227 void
228 inet_aton(host)
229         char *  host
230         CODE:
231         {
232         struct in_addr ip_address;
233         struct hostent * phe;
234         int ok = (*host != '\0') && inet_aton(host, &ip_address);
235
236         if (!ok && (phe = gethostbyname(host)) &&
237                         phe->h_addrtype == AF_INET && phe->h_length == 4) {
238                 Copy( phe->h_addr, &ip_address, phe->h_length, char );
239                 ok = 1;
240         }
241
242         ST(0) = sv_newmortal();
243         if (ok)
244                 sv_setpvn( ST(0), (char *)&ip_address, sizeof ip_address );
245         }
246
247 void
248 inet_ntoa(ip_address_sv)
249         SV *    ip_address_sv
250         CODE:
251         {
252         STRLEN addrlen;
253         struct in_addr addr;
254         char * ip_address;
255         if (DO_UTF8(ip_address_sv) && !sv_utf8_downgrade(ip_address_sv, 1))
256              croak("Wide character in %s", "Socket::inet_ntoa");
257         ip_address = SvPVbyte(ip_address_sv, addrlen);
258         if (addrlen == sizeof(addr) || addrlen == 4)
259                 addr.s_addr =
260                     (ip_address[0] & 0xFF) << 24 |
261                     (ip_address[1] & 0xFF) << 16 |
262                     (ip_address[2] & 0xFF) <<  8 |
263                     (ip_address[3] & 0xFF);
264         else
265                 croak("Bad arg length for %s, length is %d, should be %d",
266                       "Socket::inet_ntoa",
267                       addrlen, sizeof(addr));
268         /* We could use inet_ntoa() but that is broken
269          * in HP-UX + GCC + 64bitint (returns "0.0.0.0"),
270          * so let's use this sprintf() workaround everywhere.
271          * This is also more threadsafe than using inet_ntoa(). */
272         ST(0) = sv_2mortal(Perl_newSVpvf(aTHX_ "%d.%d.%d.%d", /* IPv6? */
273                                          ((addr.s_addr >> 24) & 0xFF),
274                                          ((addr.s_addr >> 16) & 0xFF),
275                                          ((addr.s_addr >>  8) & 0xFF),
276                                          ( addr.s_addr        & 0xFF)));
277         }
278
279 void
280 sockaddr_family(sockaddr)
281         SV *    sockaddr
282         PREINIT:
283         STRLEN sockaddr_len;
284         char *sockaddr_pv = SvPVbyte(sockaddr, sockaddr_len);
285         CODE:
286         if (sockaddr_len < offsetof(struct sockaddr, sa_data)) {
287             croak("Bad arg length for %s, length is %d, should be at least %d",
288                   "Socket::sockaddr_family", sockaddr_len,
289                   offsetof(struct sockaddr, sa_data));
290         }
291         ST(0) = sv_2mortal(newSViv(((struct sockaddr*)sockaddr_pv)->sa_family));
292
293 void
294 pack_sockaddr_un(pathname)
295         SV *    pathname
296         CODE:
297         {
298 #ifdef I_SYS_UN
299         struct sockaddr_un sun_ad; /* fear using sun */
300         STRLEN len;
301         char * pathname_pv;
302         int addr_len;
303
304         Zero( &sun_ad, sizeof sun_ad, char );
305         sun_ad.sun_family = AF_UNIX;
306         pathname_pv = SvPV(pathname,len);
307         if (len > sizeof(sun_ad.sun_path))
308             len = sizeof(sun_ad.sun_path);
309 #  ifdef OS2    /* Name should start with \socket\ and contain backslashes! */
310         {
311             int off;
312             char *s, *e;
313
314             if (pathname_pv[0] != '/' && pathname_pv[0] != '\\')
315                 croak("Relative UNIX domain socket name '%s' unsupported",
316                         pathname_pv);
317             else if (len < 8
318                      || pathname_pv[7] != '/' && pathname_pv[7] != '\\'
319                      || !strnicmp(pathname_pv + 1, "socket", 6))
320                 off = 7;
321             else
322                 off = 0;                /* Preserve names starting with \socket\ */
323             Copy( "\\socket", sun_ad.sun_path, off, char);
324             Copy( pathname_pv, sun_ad.sun_path + off, len, char );
325
326             s = sun_ad.sun_path + off - 1;
327             e = s + len + 1;
328             while (++s < e)
329                 if (*s = '/')
330                     *s = '\\';
331         }
332 #  else /* !( defined OS2 ) */
333         Copy( pathname_pv, sun_ad.sun_path, len, char );
334 #  endif
335         if (0) not_here("dummy");
336         if (len > 1 && sun_ad.sun_path[0] == '\0') {
337                 /* Linux-style abstract-namespace socket.
338                  * The name is not a file name, but an array of arbitrary
339                  * character, starting with \0 and possibly including \0s,
340                  * therefore the length of the structure must denote the
341                  * end of that character array */
342                 addr_len = (char *)&(sun_ad.sun_path) - (char *)&sun_ad + len;
343         } else {
344                 addr_len = sizeof sun_ad;
345         }
346 #  ifdef HAS_SOCKADDR_SA_LEN
347         sun_ad.sun_len = addr_len;
348 #  endif
349         ST(0) = newSVpvn_flags((char *)&sun_ad, addr_len, SVs_TEMP);
350 #else
351         ST(0) = (SV *) not_here("pack_sockaddr_un");
352 #endif
353         
354         }
355
356 void
357 unpack_sockaddr_un(sun_sv)
358         SV *    sun_sv
359         CODE:
360         {
361 #ifdef I_SYS_UN
362         struct sockaddr_un addr;
363         STRLEN sockaddrlen;
364         char * sun_ad = SvPVbyte(sun_sv,sockaddrlen);
365         int addr_len;
366 #   ifndef __linux__
367         /* On Linux sockaddrlen on sockets returned by accept, recvfrom,
368            getpeername and getsockname is not equal to sizeof(addr). */
369         if (sockaddrlen != sizeof(addr)) {
370             croak("Bad arg length for %s, length is %d, should be %d",
371                         "Socket::unpack_sockaddr_un",
372                         sockaddrlen, sizeof(addr));
373         }
374 #   endif
375
376         Copy( sun_ad, &addr, sizeof addr, char );
377
378         if ( addr.sun_family != AF_UNIX ) {
379             croak("Bad address family for %s, got %d, should be %d",
380                         "Socket::unpack_sockaddr_un",
381                         addr.sun_family,
382                         AF_UNIX);
383         }
384
385         if (addr.sun_path[0] == '\0') {
386                 /* Linux-style abstract socket address begins with a nul
387                  * and can contain nuls. */
388                 addr_len = (char *)&addr - (char *)&(addr.sun_path) + sockaddrlen;
389         } else {
390                 for (addr_len = 0; addr.sun_path[addr_len]
391                      && addr_len < (int)sizeof(addr.sun_path); addr_len++);
392         }
393
394         ST(0) = newSVpvn_flags(addr.sun_path, addr_len, SVs_TEMP);
395 #else
396         ST(0) = (SV *) not_here("unpack_sockaddr_un");
397 #endif
398         }
399
400 void
401 pack_sockaddr_in(port, ip_address_sv)
402         unsigned short  port
403         SV *    ip_address_sv
404         CODE:
405         {
406         struct sockaddr_in sin;
407         struct in_addr addr;
408         STRLEN addrlen;
409         char * ip_address;
410         if (DO_UTF8(ip_address_sv) && !sv_utf8_downgrade(ip_address_sv, 1))
411              croak("Wide character in %s", "Socket::pack_sockaddr_in");
412         ip_address = SvPVbyte(ip_address_sv, addrlen);
413         if (addrlen == sizeof(addr) || addrlen == 4)
414                 addr.s_addr =
415                     (ip_address[0] & 0xFF) << 24 |
416                     (ip_address[1] & 0xFF) << 16 |
417                     (ip_address[2] & 0xFF) <<  8 |
418                     (ip_address[3] & 0xFF);
419         else
420                 croak("Bad arg length for %s, length is %d, should be %d",
421                       "Socket::pack_sockaddr_in",
422                       addrlen, sizeof(addr));
423         Zero( &sin, sizeof sin, char );
424         sin.sin_family = AF_INET;
425         sin.sin_port = htons(port);
426         sin.sin_addr.s_addr = htonl(addr.s_addr);
427 #  ifdef HAS_SOCKADDR_SA_LEN
428         sin.sin_len = sizeof (sin);
429 #  endif
430         ST(0) = newSVpvn_flags((char *)&sin, sizeof (sin), SVs_TEMP);
431         }
432
433 void
434 unpack_sockaddr_in(sin_sv)
435         SV *    sin_sv
436         PPCODE:
437         {
438         STRLEN sockaddrlen;
439         struct sockaddr_in addr;
440         unsigned short  port;
441         struct in_addr  ip_address;
442         char *  sin = SvPVbyte(sin_sv,sockaddrlen);
443         if (sockaddrlen != sizeof(addr)) {
444             croak("Bad arg length for %s, length is %d, should be %d",
445                         "Socket::unpack_sockaddr_in",
446                         sockaddrlen, sizeof(addr));
447         }
448         Copy( sin, &addr,sizeof addr, char );
449         if ( addr.sin_family != AF_INET ) {
450             croak("Bad address family for %s, got %d, should be %d",
451                         "Socket::unpack_sockaddr_in",
452                         addr.sin_family,
453                         AF_INET);
454         }
455         port = ntohs(addr.sin_port);
456         ip_address = addr.sin_addr;
457
458         EXTEND(SP, 2);
459         PUSHs(sv_2mortal(newSViv((IV) port)));
460         PUSHs(newSVpvn_flags((char *)&ip_address, sizeof(ip_address), SVs_TEMP));
461         }
462
463 void
464 pack_sockaddr_in6(port, sin6_addr, scope_id=0, flowinfo=0)
465         unsigned short  port
466         SV *    sin6_addr
467         unsigned long   scope_id
468         unsigned long   flowinfo
469         CODE:
470         {
471 #ifdef AF_INET6
472         struct sockaddr_in6 sin6;
473         char * addrbytes;
474         STRLEN addrlen;
475         if (DO_UTF8(sin6_addr) && !sv_utf8_downgrade(sin6_addr, 1))
476             croak("Wide character in %s", "Socket::pack_sockaddr_in6");
477         addrbytes = SvPVbyte(sin6_addr, addrlen);
478         if(addrlen != sizeof(sin6.sin6_addr))
479             croak("Bad arg length %s, length is %d, should be %d",
480                   "Socket::pack_sockaddr_in6", addrlen, sizeof(sin6.sin6_addr));
481         Zero(&sin6, sizeof(sin6), char);
482         sin6.sin6_family = AF_INET6;
483         sin6.sin6_port = htons(port);
484         sin6.sin6_flowinfo = htonl(flowinfo);
485         Copy(addrbytes, &sin6.sin6_addr, sizeof(sin6.sin6_addr), char);
486 #if !defined(__GLIBC__) || (__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)
487         sin6.sin6_scope_id = scope_id;
488 #endif
489 #  ifdef HAS_SOCKADDR_SA_LEN
490         sin6.sin6_len = sizeof(sin6);
491 #  endif
492         ST(0) = newSVpvn_flags((char *)&sin6, sizeof(sin6), SVs_TEMP);
493 #else
494         ST(0) = (SV*)not_here("pack_sockaddr_in6");
495 #endif
496         }
497
498 void
499 unpack_sockaddr_in6(sin6_sv)
500         SV *    sin6_sv
501         PPCODE:
502         {
503 #ifdef AF_INET6
504         STRLEN addrlen;
505         struct sockaddr_in6 sin6;
506         char * addrbytes = SvPVbyte(sin6_sv, addrlen);
507         if (addrlen != sizeof(sin6))
508             croak("Bad arg length for %s, length is %d, should be %d",
509                     "Socket::unpack_sockaddr_in6",
510                     addrlen, sizeof(sin6));
511         Copy(addrbytes, &sin6, sizeof(sin6), char);
512         if(sin6.sin6_family != AF_INET6)
513             croak("Bad address family for %s, got %d, should be %d",
514                     "Socket::unpack_sockaddr_in6",
515                     sin6.sin6_family, AF_INET6);
516         EXTEND(SP, 4);
517         mPUSHi(ntohs(sin6.sin6_port));
518         mPUSHp((char *)&sin6.sin6_addr, sizeof(sin6.sin6_addr));
519 #if !defined(__GLIBC__) || (__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)
520         mPUSHi(sin6.sin6_scope_id);
521 #else
522         mPUSHi(0);
523 #endif
524         mPUSHi(ntohl(sin6.sin6_flowinfo));
525 #else
526         ST(0) = (SV*)not_here("pack_sockaddr_in6");
527 #endif
528         }
529
530 void
531 inet_ntop(af, ip_address_sv)
532         int     af
533         SV *    ip_address_sv
534         CODE:
535 #ifdef HAS_INETNTOP
536         STRLEN addrlen, struct_size;
537 #ifdef AF_INET6
538         struct in6_addr addr;
539         char str[INET6_ADDRSTRLEN];
540 #else
541         struct in_addr addr;
542         char str[INET_ADDRSTRLEN];
543 #endif
544         char *ip_address = SvPV(ip_address_sv, addrlen);
545
546         struct_size = sizeof(addr);
547
548         if(af != AF_INET
549 #ifdef AF_INET6
550             && af != AF_INET6
551 #endif
552           ) {
553            croak("Bad address family for %s, got %d, should be"
554 #ifdef AF_INET6
555                " either AF_INET or AF_INET6",
556 #else
557                " AF_INET",
558 #endif
559                "Socket::inet_ntop",
560                af);
561         }
562
563         Copy( ip_address, &addr, sizeof addr, char );
564         inet_ntop(af, &addr, str, sizeof str);
565
566         ST(0) = newSVpvn_flags(str, strlen(str), SVs_TEMP);
567 #else
568         ST(0) = (SV *)not_here("inet_ntop");
569 #endif
570
571 void
572 inet_pton(af, host)
573         int           af
574         const char *  host
575         CODE:
576 #ifdef HAS_INETPTON
577         int ok;
578 #ifdef AF_INET6
579         struct in6_addr ip_address;
580 #else
581         struct in_addr ip_address;
582 #endif
583
584         if(af != AF_INET
585 #ifdef AF_INET6
586                 && af != AF_INET6
587 #endif
588           ) {
589                 croak("Bad address family for %s, got %d, should be"
590 #ifdef AF_INET6
591                         " either AF_INET or AF_INET6",
592 #else
593                         " AF_INET",
594 #endif
595                         "Socket::inet_pton",
596                         af);
597         }
598         ok = (*host != '\0') && inet_pton(af, host, &ip_address);
599
600         ST(0) = sv_newmortal();
601         if (ok) {
602                 sv_setpvn( ST(0), (char *)&ip_address, sizeof(ip_address) );
603         }
604 #else
605         ST(0) = (SV *)not_here("inet_pton");
606 #endif