Socket.xs 30 KB
Newer Older
1 2 3 4 5
#define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

6 7
#include <stddef.h>

8
#ifdef I_SYS_TYPES
9
#  include <sys/types.h>
10 11
#endif
#if !defined(ultrix) /* Avoid double definition. */
12
#   include <sys/socket.h>
13 14
#endif
#if defined(USE_SOCKS) && defined(I_SOCKS)
15
#   include <socks.h>
16 17
#endif
#ifdef MPE
18 19 20
#  define PF_INET AF_INET
#  define PF_UNIX AF_UNIX
#  define SOCK_RAW 3
21 22
#endif
#ifdef I_SYS_UN
23
#  include <sys/un.h>
24
#endif
25
/* XXX Configure test for <netinet/in_systm.h needed XXX */
26
#if defined(NeXT) || defined(__NeXT__)
27
#  include <netinet/in_systm.h>
28 29
#endif
#if defined(__sgi) && !defined(AF_LINK) && defined(PF_LINK) && PF_LINK == AF_LNK
30
#  undef PF_LINK
31 32
#endif
#if defined(I_NETINET_IN) || defined(__ultrix__)
33
#  include <netinet/in.h>
34
#endif
35 36 37
#if defined(I_NETINET_IP)
#  include <netinet/ip.h>
#endif
38 39
#ifdef I_NETDB
#  if !defined(ultrix)	/* Avoid double definition. */
40 41
#   include <netdb.h>
#  endif
42 43
#endif
#ifdef I_ARPA_INET
44
#  include <arpa/inet.h>
45 46
#endif
#ifdef I_NETINET_TCP
47 48 49
#  include <netinet/tcp.h>
#endif

50
#if defined(WIN32) && !defined(UNDER_CE)
51 52 53
# include <ws2tcpip.h>
#endif

54 55 56 57 58
#ifdef NETWARE
NETDB_DEFINE_CONTEXT
NETINET_DEFINE_CONTEXT
#endif

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
#ifdef I_SYSUIO
# include <sys/uio.h>
#endif

#ifndef AF_NBS
# undef PF_NBS
#endif

#ifndef AF_X25
# undef PF_X25
#endif

#ifndef INADDR_NONE
# define INADDR_NONE	0xffffffff
#endif /* INADDR_NONE */
#ifndef INADDR_BROADCAST
# define INADDR_BROADCAST	0xffffffff
#endif /* INADDR_BROADCAST */
#ifndef INADDR_LOOPBACK
78
# define INADDR_LOOPBACK	 0x7F000001
79 80
#endif /* INADDR_LOOPBACK */

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
#ifndef C_ARRAY_LENGTH
#define C_ARRAY_LENGTH(arr) (sizeof(arr) / sizeof(*(arr)))
#endif /* !C_ARRAY_LENGTH */

#ifndef PERL_UNUSED_VAR
# define PERL_UNUSED_VAR(x) ((void)x)
#endif /* !PERL_UNUSED_VAR */

#ifndef PERL_UNUSED_ARG
# define PERL_UNUSED_ARG(x) PERL_UNUSED_VAR(x)
#endif /* !PERL_UNUSED_ARG */

#ifndef Newx
# define Newx(v,n,t) New(0,v,n,t)
#endif /* !Newx */

#ifndef croak_sv
# define croak_sv(sv)	croak(SvPV_nolen(sv))
#endif

#ifndef hv_stores
# define hv_stores(hv, keystr, val) \
	hv_store(hv, ""keystr"", sizeof(keystr)-1, val, 0)
#endif /* !hv_stores */

#ifndef newSVpvn_flags
# define newSVpvn_flags(s,len,flags) my_newSVpvn_flags(aTHX_ s,len,flags)
static SV *my_newSVpvn_flags(pTHX_ const char *s, STRLEN len, U32 flags)
{
  SV *sv = newSVpvn(s, len);
  SvFLAGS(sv) |= (flags & SVf_UTF8);
  return (flags & SVs_TEMP) ? sv_2mortal(sv) : sv;
}
#endif /* !newSVpvn_flags */

#ifndef SvRV_set
# define SvRV_set(sv, val) (SvRV(sv) = (val))
#endif /* !SvRV_set */

#ifndef SvPV_nomg
# define SvPV_nomg SvPV
#endif /* !SvPV_nomg */

#ifndef HEK_FLAGS
# define HEK_FLAGS(hek) 0
# define HVhek_UTF8 1
#endif /* !HEK_FLAGS */

#ifndef hv_common
/* These magic numbers are arbitrarily chosen (copied from perl core in fact)
 * and only have to match between this definition and the code that uses them
 */
# define HV_FETCH_ISSTORE 0x04
# define HV_FETCH_LVALUE  0x10
# define hv_common(hv, keysv, key, klen, flags, act, val, hash) \
	my_hv_common(aTHX_ hv, keysv, key, klen, flags, act, val, hash)
static void *my_hv_common(pTHX_ HV *hv, SV *keysv, const char *key, STRLEN klen,
	int flags, int act, SV *val, U32 hash)
{
	/*
	 * This only handles the usage actually made by the code
	 * generated by ExtUtils::Constant.  EU:C really ought to arrange
	 * portability of its generated code itself.
	 */
	if (!keysv) {
		keysv = sv_2mortal(newSVpvn(key, klen));
		if (flags & HVhek_UTF8)
			SvUTF8_on(keysv);
	}
	if (act == HV_FETCH_LVALUE) {
		return (void*)hv_fetch_ent(hv, keysv, 1, hash);
	} else if (act == HV_FETCH_ISSTORE) {
		return (void*)hv_store_ent(hv, keysv, val, hash);
	} else {
		croak("panic: my_hv_common: act=0x%x", act);
	}
}
#endif /* !hv_common */

#ifndef hv_common_key_len
# define hv_common_key_len(hv, key, kl, act, val, hash) \
	my_hv_common_key_len(aTHX_ hv, key, kl, act, val, hash)
static void *my_hv_common_key_len(pTHX_ HV *hv, const char *key, I32 kl,
	int act, SV *val, U32 hash)
{
	STRLEN klen;
	int flags;
	if (kl < 0) {
		klen = -kl;
		flags = HVhek_UTF8;
	} else {
		klen = kl;
		flags = 0;
	}
	return hv_common(hv, NULL, key, klen, flags, act, val, hash);
}
#endif /* !hv_common_key_len */

#ifndef mPUSHi
# define mPUSHi(i) sv_setiv_mg(PUSHs(sv_newmortal()), (IV)(i))
#endif /* !mPUSHi */
#ifndef mPUSHp
# define mPUSHp(p,l) sv_setpvn_mg(PUSHs(sv_newmortal()), (p), (l))
#endif /* !mPUSHp */
185 186 187
#ifndef mPUSHs
# define mPUSHs(s) PUSHs(sv_2mortal(s))
#endif /* !mPUSHs */
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223

#ifndef CvCONST_on
# undef newCONSTSUB
# define newCONSTSUB(stash, name, val) my_newCONSTSUB(aTHX_ stash, name, val)
static CV *my_newCONSTSUB(pTHX_ HV *stash, char *name, SV *val)
{
	/*
	 * This has to satisfy code generated by ExtUtils::Constant.
	 * It depends on the 5.8+ layout of constant subs.  It has
	 * two calls to newCONSTSUB(): one for real constants, and one
	 * for undefined constants.  In the latter case, it turns the
	 * initially-generated constant subs into something else, and
	 * it needs the return value from newCONSTSUB() which Perl 5.6
	 * doesn't provide.
	 */
	GV *gv;
	CV *cv;
	Perl_newCONSTSUB(aTHX_ stash, name, val);
	ENTER;
	SAVESPTR(PL_curstash);
	PL_curstash = stash;
	gv = gv_fetchpv(name, 0, SVt_PVCV);
	cv = GvCV(gv);
	LEAVE;
	CvXSUBANY(cv).any_ptr = &PL_sv_undef;
	return cv;
}
# define CvCONST_off(cv) my_CvCONST_off(aTHX_ cv)
static void my_CvCONST_off(pTHX_ CV *cv)
{
	op_free(CvROOT(cv));
	CvROOT(cv) = NULL;
	CvSTART(cv) = NULL;
}
#endif /* !CvCONST_on */

224 225
#ifndef HAS_INET_ATON

226
/*
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
 * Check whether "cp" is a valid ascii representation
 * of an Internet address and convert to a binary address.
 * Returns 1 if the address is valid, 0 if not.
 * This replaces inet_addr, the return value from which
 * cannot distinguish between failure and a local broadcast address.
 */
static int
my_inet_aton(register const char *cp, struct in_addr *addr)
{
	dTHX;
	register U32 val;
	register int base;
	register char c;
	int nparts;
	const char *s;
	unsigned int parts[4];
	register unsigned int *pp = parts;

245
	if (!cp || !*cp)
246 247 248
		return 0;
	for (;;) {
		/*
249
		 * Collect number up to ".".
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
		 * Values are specified as for C:
		 * 0x=hex, 0=octal, other=decimal.
		 */
		val = 0; base = 10;
		if (*cp == '0') {
			if (*++cp == 'x' || *cp == 'X')
				base = 16, cp++;
			else
				base = 8;
		}
		while ((c = *cp) != '\0') {
			if (isDIGIT(c)) {
				val = (val * base) + (c - '0');
				cp++;
				continue;
			}
			if (base == 16 && (s=strchr(PL_hexdigit,c))) {
267
				val = (val << 4) +
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
					((s - PL_hexdigit) & 15);
				cp++;
				continue;
			}
			break;
		}
		if (*cp == '.') {
			/*
			 * Internet format:
			 *	a.b.c.d
			 *	a.b.c	(with c treated as 16-bits)
			 *	a.b	(with b treated as 24 bits)
			 */
			if (pp >= parts + 3 || val > 0xff)
				return 0;
			*pp++ = val, cp++;
		} else
			break;
	}
	/*
	 * Check for trailing characters.
	 */
	if (*cp && !isSPACE(*cp))
		return 0;
	/*
	 * Concoct the address according to
	 * the number of parts specified.
	 */
	nparts = pp - parts + 1;	/* force to an int for switch() */
	switch (nparts) {

	case 1:				/* a -- 32 bits */
		break;

	case 2:				/* a.b -- 8.24 bits */
		if (val > 0xffffff)
			return 0;
		val |= parts[0] << 24;
		break;

	case 3:				/* a.b.c -- 8.8.16 bits */
		if (val > 0xffff)
			return 0;
		val |= (parts[0] << 24) | (parts[1] << 16);
		break;

	case 4:				/* a.b.c.d -- 8.8.8.8 bits */
		if (val > 0xff)
			return 0;
		val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
		break;
	}
	addr->s_addr = htonl(val);
	return 1;
}

#undef inet_aton
#define inet_aton my_inet_aton

#endif /* ! HAS_INET_ATON */

329 330 331 332 333
/* These are not gni() constants; they're extensions for the perl API */
/* The definitions in Socket.pm and Socket.xs must match */
#define NIx_NOHOST   (1 << 0)
#define NIx_NOSERV   (1 << 1)

334 335 336 337 338
/* On Windows, ole2.h defines a macro called "interface". We don't need that,
 * and it will complicate the variables in pack_ip_mreq() etc. (RT87389)
 */
#undef interface

339 340

static int
341
not_here(const char *s)
342 343 344 345 346
{
    croak("Socket::%s not implemented on this architecture", s);
    return -1;
}

347 348 349 350 351 352 353 354 355 356 357 358 359
#define PERL_IN_ADDR_S_ADDR_SIZE 4

/*
* Bad assumptions possible here.
*
* Bad Assumption 1: struct in_addr has no other fields
* than the s_addr (which is the field we care about
* in here, really). However, we can be fed either 4-byte
* addresses (from pack("N", ...), or va.b.c.d, or ...),
* or full struct in_addrs (from e.g. pack_sockaddr_in()),
* which may or may not be 4 bytes in size.
*
* Bad Assumption 2: the s_addr field is a simple type
360
* (such as an int, u_int32_t).	It can be a bit field,
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
* in which case using & (address-of) on it or taking sizeof()
* wouldn't go over too well.  (Those are not attempted
* now but in case someone thinks to change the below code
* to use addr.s_addr instead of addr, you have been warned.)
*
* Bad Assumption 3: the s_addr is the first field in
* an in_addr, or that its bytes are the first bytes in
* an in_addr.
*
* These bad assumptions are wrong in UNICOS which has
* struct in_addr { struct { u_long  st_addr:32; } s_da };
* #define s_addr s_da.st_addr
* and u_long is 64 bits.
*
* --jhi */

#include "const-c.inc"
378

379 380 381 382
#ifdef HAS_GETADDRINFO
static SV *err_to_SV(pTHX_ int err)
{
	SV *ret = sv_newmortal();
383
	(void) SvUPGRADE(ret, SVt_PVNV);
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414

	if(err) {
		const char *error = gai_strerror(err);
		sv_setpv(ret, error);
	}
	else {
		sv_setpv(ret, "");
	}

	SvIV_set(ret, err); SvIOK_on(ret);

	return ret;
}

static void xs_getaddrinfo(pTHX_ CV *cv)
{
	dXSARGS;

	SV   *host;
	SV   *service;
	SV   *hints;

	char *hostname = NULL;
	char *servicename = NULL;
	STRLEN len;
	struct addrinfo hints_s;
	struct addrinfo *res;
	struct addrinfo *res_iter;
	int err;
	int n_res;

415
	PERL_UNUSED_ARG(cv);
416
	if(items > 3)
417
		croak("Usage: Socket::getaddrinfo(host, service, hints)");
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449

	SP -= items;

	if(items < 1)
		host = &PL_sv_undef;
	else
		host = ST(0);

	if(items < 2)
		service = &PL_sv_undef;
	else
		service = ST(1);

	if(items < 3)
		hints = NULL;
	else
		hints = ST(2);

	SvGETMAGIC(host);
	if(SvOK(host)) {
		hostname = SvPV_nomg(host, len);
		if (!len)
			hostname = NULL;
	}

	SvGETMAGIC(service);
	if(SvOK(service)) {
		servicename = SvPV_nomg(service, len);
		if (!len)
			servicename = NULL;
	}

450
	Zero(&hints_s, sizeof(hints_s), char);
451 452 453 454 455 456 457 458 459 460 461
	hints_s.ai_family = PF_UNSPEC;

	if(hints && SvOK(hints)) {
		HV *hintshash;
		SV **valp;

		if(!SvROK(hints) || SvTYPE(SvRV(hints)) != SVt_PVHV)
			croak("hints is not a HASH reference");

		hintshash = (HV*)SvRV(hints);

462
		if((valp = hv_fetch(hintshash, "flags", 5, 0)) != NULL && SvOK(*valp))
463
			hints_s.ai_flags = SvIV(*valp);
464
		if((valp = hv_fetch(hintshash, "family", 6, 0)) != NULL && SvOK(*valp))
465
			hints_s.ai_family = SvIV(*valp);
466
		if((valp = hv_fetch(hintshash, "socktype", 8, 0)) != NULL && SvOK(*valp))
467
			hints_s.ai_socktype = SvIV(*valp);
468
		if((valp = hv_fetch(hintshash, "protocol", 8, 0)) != NULL && SvOK(*valp))
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
			hints_s.ai_protocol = SvIV(*valp);
	}

	err = getaddrinfo(hostname, servicename, &hints_s, &res);

	XPUSHs(err_to_SV(aTHX_ err));

	if(err)
		XSRETURN(1);

	n_res = 0;
	for(res_iter = res; res_iter; res_iter = res_iter->ai_next) {
		HV *res_hv = newHV();

		(void)hv_stores(res_hv, "family",   newSViv(res_iter->ai_family));
		(void)hv_stores(res_hv, "socktype", newSViv(res_iter->ai_socktype));
		(void)hv_stores(res_hv, "protocol", newSViv(res_iter->ai_protocol));

		(void)hv_stores(res_hv, "addr",     newSVpvn((char*)res_iter->ai_addr, res_iter->ai_addrlen));

		if(res_iter->ai_canonname)
			(void)hv_stores(res_hv, "canonname", newSVpv(res_iter->ai_canonname, 0));
		else
			(void)hv_stores(res_hv, "canonname", newSV(0));

		XPUSHs(sv_2mortal(newRV_noinc((SV*)res_hv)));
		n_res++;
	}

	freeaddrinfo(res);

	XSRETURN(1 + n_res);
}
#endif

#ifdef HAS_GETNAMEINFO
static void xs_getnameinfo(pTHX_ CV *cv)
{
	dXSARGS;

	SV  *addr;
	int  flags;
511
	int  xflags;
512 513 514 515 516 517 518

	char host[1024];
	char serv[256];
	char *sa; /* we'll cast to struct sockaddr * when necessary */
	STRLEN addr_len;
	int err;

519 520 521 522 523
	int want_host, want_serv;

	PERL_UNUSED_ARG(cv);
	if(items < 1 || items > 3)
		croak("Usage: Socket::getnameinfo(addr, flags=0, xflags=0)");
524 525 526 527 528 529 530 531 532 533

	SP -= items;

	addr = ST(0);

	if(items < 2)
		flags = 0;
	else
		flags = SvIV(ST(1));

534 535 536 537 538 539 540 541
	if(items < 3)
		xflags = 0;
	else
		xflags = SvIV(ST(2));

	want_host = !(xflags & NIx_NOHOST);
	want_serv = !(xflags & NIx_NOSERV);

542 543 544 545 546 547 548 549 550 551 552 553 554 555
	if(!SvPOK(addr))
		croak("addr is not a string");

	addr_len = SvCUR(addr);

	/* We need to ensure the sockaddr is aligned, because a random SvPV might
	 * not be due to SvOOK */
	Newx(sa, addr_len, char);
	Copy(SvPV_nolen(addr), sa, addr_len, char);
#ifdef HAS_SOCKADDR_SA_LEN
	((struct sockaddr *)sa)->sa_len = addr_len;
#endif

	err = getnameinfo((struct sockaddr *)sa, addr_len,
556 557
			want_host ? host : NULL, want_host ? sizeof(host) : 0,
			want_serv ? serv : NULL, want_serv ? sizeof(serv) : 0,
558 559 560 561 562 563 564 565 566
			flags);

	Safefree(sa);

	XPUSHs(err_to_SV(aTHX_ err));

	if(err)
		XSRETURN(1);

567 568
	XPUSHs(want_host ? sv_2mortal(newSVpv(host, 0)) : &PL_sv_undef);
	XPUSHs(want_serv ? sv_2mortal(newSVpv(serv, 0)) : &PL_sv_undef);
569 570 571 572 573

	XSRETURN(3);
}
#endif

574 575
MODULE = Socket		PACKAGE = Socket

576
INCLUDE: const-xs.inc
577

578 579
BOOT:
#ifdef HAS_GETADDRINFO
580
	newXS("Socket::getaddrinfo", xs_getaddrinfo, __FILE__);
581 582
#endif
#ifdef HAS_GETNAMEINFO
583
	newXS("Socket::getnameinfo", xs_getnameinfo, __FILE__);
584 585
#endif

586 587 588 589 590 591 592 593
void
inet_aton(host)
	char *	host
	CODE:
	{
	struct in_addr ip_address;
	struct hostent * phe;

594
	if ((*host != '\0') && inet_aton(host, &ip_address)) {
595
		ST(0) = sv_2mortal(newSVpvn((char *)&ip_address, sizeof(ip_address)));
596 597 598 599 600
		XSRETURN(1);
	}

	phe = gethostbyname(host);
	if (phe && phe->h_addrtype == AF_INET && phe->h_length == 4) {
601
		ST(0) = sv_2mortal(newSVpvn((char *)phe->h_addr, phe->h_length));
602
		XSRETURN(1);
603 604
	}

605
	XSRETURN_UNDEF;
606 607 608 609 610 611 612 613 614
	}

void
inet_ntoa(ip_address_sv)
	SV *	ip_address_sv
	CODE:
	{
	STRLEN addrlen;
	struct in_addr addr;
615 616
	char * ip_address;
	if (DO_UTF8(ip_address_sv) && !sv_utf8_downgrade(ip_address_sv, 1))
617
		croak("Wide character in %s", "Socket::inet_ntoa");
618 619
	ip_address = SvPVbyte(ip_address_sv, addrlen);
	if (addrlen == sizeof(addr) || addrlen == 4)
620
		addr.s_addr =
621 622 623 624 625
		    (ip_address[0] & 0xFF) << 24 |
		    (ip_address[1] & 0xFF) << 16 |
		    (ip_address[2] & 0xFF) <<  8 |
		    (ip_address[3] & 0xFF);
	else
626 627
		croak("Bad arg length for %s, length is %"UVuf", should be %"UVuf,
		      "Socket::inet_ntoa", (UV)addrlen, (UV)sizeof(addr));
628 629 630 631
	/* We could use inet_ntoa() but that is broken
	 * in HP-UX + GCC + 64bitint (returns "0.0.0.0"),
	 * so let's use this sprintf() workaround everywhere.
	 * This is also more threadsafe than using inet_ntoa(). */
632 633 634 635 636
	ST(0) = sv_2mortal(Perl_newSVpvf(aTHX_ "%d.%d.%d.%d", /* IPv6? */
					 ((addr.s_addr >> 24) & 0xFF),
					 ((addr.s_addr >> 16) & 0xFF),
					 ((addr.s_addr >>  8) & 0xFF),
					 ( addr.s_addr        & 0xFF)));
637 638
	}

639 640 641 642 643 644 645
void
sockaddr_family(sockaddr)
	SV *	sockaddr
	PREINIT:
	STRLEN sockaddr_len;
	char *sockaddr_pv = SvPVbyte(sockaddr, sockaddr_len);
	CODE:
646 647 648 649
	if (sockaddr_len < offsetof(struct sockaddr, sa_data))
		croak("Bad arg length for %s, length is %"UVuf", should be at least %"UVuf,
		      "Socket::sockaddr_family", (UV)sockaddr_len,
		      (UV)offsetof(struct sockaddr, sa_data));
650
	ST(0) = sv_2mortal(newSViv(((struct sockaddr*)sockaddr_pv)->sa_family));
651 652 653

void
pack_sockaddr_un(pathname)
654
	SV *	pathname
655 656 657 658 659
	CODE:
	{
#ifdef I_SYS_UN
	struct sockaddr_un sun_ad; /* fear using sun */
	STRLEN len;
660
	char * pathname_pv;
661
	int addr_len;
662

663
	Zero(&sun_ad, sizeof(sun_ad), char);
664
	sun_ad.sun_family = AF_UNIX;
665
	pathname_pv = SvPV(pathname,len);
666 667 668 669
	if (len > sizeof(sun_ad.sun_path))
	    len = sizeof(sun_ad.sun_path);
#  ifdef OS2	/* Name should start with \socket\ and contain backslashes! */
	{
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
		int off;
		char *s, *e;

		if (pathname_pv[0] != '/' && pathname_pv[0] != '\\')
			croak("Relative UNIX domain socket name '%s' unsupported",
			      pathname_pv);
		else if (len < 8
			 || pathname_pv[7] != '/' && pathname_pv[7] != '\\'
			 || !strnicmp(pathname_pv + 1, "socket", 6))
			off = 7;
		else
			off = 0;	/* Preserve names starting with \socket\ */
		Copy("\\socket", sun_ad.sun_path, off, char);
		Copy(pathname_pv, sun_ad.sun_path + off, len, char);

		s = sun_ad.sun_path + off - 1;
		e = s + len + 1;
		while (++s < e)
			if (*s = '/')
				*s = '\\';
690
	}
691
#  else	/* !( defined OS2 ) */
692
	Copy(pathname_pv, sun_ad.sun_path, len, char);
693
#  endif
694
	if (0) not_here("dummy");
695 696 697 698 699 700 701 702
	if (len > 1 && sun_ad.sun_path[0] == '\0') {
		/* Linux-style abstract-namespace socket.
		 * The name is not a file name, but an array of arbitrary
		 * character, starting with \0 and possibly including \0s,
		 * therefore the length of the structure must denote the
		 * end of that character array */
		addr_len = (char *)&(sun_ad.sun_path) - (char *)&sun_ad + len;
	} else {
703
		addr_len = sizeof(sun_ad);
704
	}
705 706 707
#  ifdef HAS_SOCKADDR_SA_LEN
	sun_ad.sun_len = addr_len;
#  endif
708
	ST(0) = sv_2mortal(newSVpvn((char *)&sun_ad, addr_len));
709
#else
710
	ST(0) = (SV*)not_here("pack_sockaddr_un");
711 712 713 714 715 716 717 718 719 720 721 722
#endif
	
	}

void
unpack_sockaddr_un(sun_sv)
	SV *	sun_sv
	CODE:
	{
#ifdef I_SYS_UN
	struct sockaddr_un addr;
	STRLEN sockaddrlen;
723
	char * sun_ad = SvPVbyte(sun_sv,sockaddrlen);
724
	int addr_len;
725 726
#   if defined(__linux__) || defined(HAS_SOCKADDR_SA_LEN)
	/* On Linux or *BSD sockaddrlen on sockets returned by accept, recvfrom,
727
	   getpeername and getsockname is not equal to sizeof(addr). */
728 729
	if (sockaddrlen < sizeof(addr)) {
	  Copy(sun_ad, &addr, sockaddrlen, char);
730
	  Zero(((char*)&addr) + sockaddrlen, sizeof(addr) - sockaddrlen, char);
731 732
	} else {
	  Copy(sun_ad, &addr, sizeof(addr), char);
733
	}
734 735 736 737 738 739
#     ifdef HAS_SOCKADDR_SA_LEN
	/* In this case, sun_len must be checked */
	if (sockaddrlen != addr.sun_len)
		croak("Invalid arg sun_len field for %s, length is %"UVuf", but sun_len is %"UVuf,
		      "Socket::unpack_sockaddr_un", (UV)sockaddrlen, (UV)addr.sun_len);
#     endif
740 741 742 743 744
#   else
	if (sockaddrlen != sizeof(addr))
		croak("Bad arg length for %s, length is %"UVuf", should be %"UVuf,
		      "Socket::unpack_sockaddr_un", (UV)sockaddrlen, (UV)sizeof(addr));
	Copy(sun_ad, &addr, sizeof(addr), char);
745 746
#   endif

747 748 749
	if (addr.sun_family != AF_UNIX)
		croak("Bad address family for %s, got %d, should be %d",
		      "Socket::unpack_sockaddr_un", addr.sun_family, AF_UNIX);
750
#   ifdef __linux__
751 752 753 754
	if (addr.sun_path[0] == '\0') {
		/* Linux-style abstract socket address begins with a nul
		 * and can contain nuls. */
		addr_len = (char *)&addr - (char *)&(addr.sun_path) + sockaddrlen;
755 756 757 758 759 760 761 762 763 764 765
	} else
#   endif
	{
#   if defined(HAS_SOCKADDR_SA_LEN)
		/* On *BSD sun_path not always ends with a '\0' */
		int maxlen = addr.sun_len - 2; /* should use offsetof(struct sockaddr_un, sun_path) instead of 2 */
		if (maxlen > (int)sizeof(addr.sun_path))
		  maxlen = (int)sizeof(addr.sun_path);
#   else
		const int maxlen = (int)sizeof(addr.sun_path);
#   endif
766
		for (addr_len = 0; addr.sun_path[addr_len]
767
		     && addr_len < maxlen; addr_len++);
768 769
	}

770
	ST(0) = sv_2mortal(newSVpvn(addr.sun_path, addr_len));
771
#else
772
	ST(0) = (SV*)not_here("unpack_sockaddr_un");
773 774 775 776
#endif
	}

void
777
pack_sockaddr_in(port, ip_address_sv)
778
	unsigned short	port
779
	SV *	ip_address_sv
780 781 782
	CODE:
	{
	struct sockaddr_in sin;
783 784 785 786
	struct in_addr addr;
	STRLEN addrlen;
	char * ip_address;
	if (DO_UTF8(ip_address_sv) && !sv_utf8_downgrade(ip_address_sv, 1))
787
		croak("Wide character in %s", "Socket::pack_sockaddr_in");
788 789
	ip_address = SvPVbyte(ip_address_sv, addrlen);
	if (addrlen == sizeof(addr) || addrlen == 4)
790
		addr.s_addr =
791 792 793 794 795
		    (ip_address[0] & 0xFF) << 24 |
		    (ip_address[1] & 0xFF) << 16 |
		    (ip_address[2] & 0xFF) <<  8 |
		    (ip_address[3] & 0xFF);
	else
796
		croak("Bad arg length for %s, length is %"UVuf", should be %"UVuf,
797
		      "Socket::pack_sockaddr_in",
798 799
		      (UV)addrlen, (UV)sizeof(addr));
	Zero(&sin, sizeof(sin), char);
800 801
	sin.sin_family = AF_INET;
	sin.sin_port = htons(port);
802
	sin.sin_addr.s_addr = htonl(addr.s_addr);
803
#  ifdef HAS_SOCKADDR_SA_LEN
804
	sin.sin_len = sizeof(sin);
805
#  endif
806
	ST(0) = sv_2mortal(newSVpvn((char *)&sin, sizeof(sin)));
807 808 809 810 811 812 813 814 815
	}

void
unpack_sockaddr_in(sin_sv)
	SV *	sin_sv
	PPCODE:
	{
	STRLEN sockaddrlen;
	struct sockaddr_in addr;
816
	SV *ip_address_sv;
817
	char *	sin = SvPVbyte(sin_sv,sockaddrlen);
818
	if (sockaddrlen != sizeof(addr)) {
819 820
	    croak("Bad arg length for %s, length is %"UVuf", should be %"UVuf,
		  "Socket::unpack_sockaddr_in", sockaddrlen, sizeof(addr));
821
	}
822 823
	Copy(sin, &addr, sizeof(addr), char);
	if (addr.sin_family != AF_INET) {
824
	    croak("Bad address family for %s, got %d, should be %d",
825
		  "Socket::unpack_sockaddr_in", addr.sin_family, AF_INET);
826
	}
827
	ip_address_sv = newSVpvn((char *)&addr.sin_addr, sizeof(addr.sin_addr));
828

829 830 831 832 833 834 835 836
	if(GIMME_V == G_ARRAY) {
	    EXTEND(SP, 2);
	    mPUSHi(ntohs(addr.sin_port));
	    mPUSHs(ip_address_sv);
	}
	else {
	    mPUSHs(ip_address_sv);
	}
837
	}
838

839 840 841 842 843 844 845 846
void
pack_sockaddr_in6(port, sin6_addr, scope_id=0, flowinfo=0)
	unsigned short	port
	SV *	sin6_addr
	unsigned long	scope_id
	unsigned long	flowinfo
	CODE:
	{
847
#ifdef HAS_SOCKADDR_IN6
848 849 850 851
	struct sockaddr_in6 sin6;
	char * addrbytes;
	STRLEN addrlen;
	if (DO_UTF8(sin6_addr) && !sv_utf8_downgrade(sin6_addr, 1))
852
		croak("Wide character in %s", "Socket::pack_sockaddr_in6");
853
	addrbytes = SvPVbyte(sin6_addr, addrlen);
854 855 856
	if (addrlen != sizeof(sin6.sin6_addr))
		croak("Bad arg length %s, length is %"UVuf", should be %"UVuf,
		      "Socket::pack_sockaddr_in6", (UV)addrlen, (UV)sizeof(sin6.sin6_addr));
857 858 859 860 861 862 863 864
	Zero(&sin6, sizeof(sin6), char);
	sin6.sin6_family = AF_INET6;
	sin6.sin6_port = htons(port);
	sin6.sin6_flowinfo = htonl(flowinfo);
	Copy(addrbytes, &sin6.sin6_addr, sizeof(sin6.sin6_addr), char);
#  ifdef HAS_SIN6_SCOPE_ID
	sin6.sin6_scope_id = scope_id;
#  else
865
	if (scope_id != 0)
866
	    warn("%s cannot represent non-zero scope_id %d",
867
		 "Socket::pack_sockaddr_in6", scope_id);
868 869 870 871
#  endif
#  ifdef HAS_SOCKADDR_SA_LEN
	sin6.sin6_len = sizeof(sin6);
#  endif
872
	ST(0) = sv_2mortal(newSVpvn((char *)&sin6, sizeof(sin6)));
873 874 875 876 877 878 879 880 881 882
#else
	ST(0) = (SV*)not_here("pack_sockaddr_in6");
#endif
	}

void
unpack_sockaddr_in6(sin6_sv)
	SV *	sin6_sv
	PPCODE:
	{
883
#ifdef HAS_SOCKADDR_IN6
884 885 886
	STRLEN addrlen;
	struct sockaddr_in6 sin6;
	char * addrbytes = SvPVbyte(sin6_sv, addrlen);
887
	SV *ip_address_sv;
888
	if (addrlen != sizeof(sin6))
889 890
		croak("Bad arg length for %s, length is %"UVuf", should be %"UVuf,
		      "Socket::unpack_sockaddr_in6", (UV)addrlen, (UV)sizeof(sin6));
891
	Copy(addrbytes, &sin6, sizeof(sin6), char);
892 893 894
	if (sin6.sin6_family != AF_INET6)
		croak("Bad address family for %s, got %d, should be %d",
		      "Socket::unpack_sockaddr_in6", sin6.sin6_family, AF_INET6);
895 896 897 898 899 900
	ip_address_sv = newSVpvn((char *)&sin6.sin6_addr, sizeof(sin6.sin6_addr));

	if(GIMME_V == G_ARRAY) {
	    EXTEND(SP, 4);
	    mPUSHi(ntohs(sin6.sin6_port));
	    mPUSHs(ip_address_sv);
901
#  ifdef HAS_SIN6_SCOPE_ID
902
	    mPUSHi(sin6.sin6_scope_id);
903
#  else
904
	    mPUSHi(0);
905
#  endif
906 907 908 909 910
	    mPUSHi(ntohl(sin6.sin6_flowinfo));
	}
	else {
	    mPUSHs(ip_address_sv);
	}
911 912 913 914 915
#else
	ST(0) = (SV*)not_here("pack_sockaddr_in6");
#endif
	}

916 917
void
inet_ntop(af, ip_address_sv)
918 919 920
	int	af
	SV *	ip_address_sv
	CODE:
921
#ifdef HAS_INETNTOP
922
	STRLEN addrlen;
923
#ifdef AF_INET6
924 925
	struct in6_addr addr;
	char str[INET6_ADDRSTRLEN];
926 927 928 929
#else
	struct in_addr addr;
	char str[INET_ADDRSTRLEN];
#endif
930 931 932 933 934 935
	char *ip_address;

	if (DO_UTF8(ip_address_sv) && !sv_utf8_downgrade(ip_address_sv, 1))
		croak("Wide character in %s", "Socket::inet_ntop");

	ip_address = SvPV(ip_address_sv, addrlen);
936

937 938 939 940 941 942
	switch(af) {
	  case AF_INET:
	    if(addrlen != 4)
		croak("Bad address length for Socket::inet_ntop on AF_INET;"
		      " got %"UVuf", should be 4", (UV)addrlen);
	    break;
943
#ifdef AF_INET6
944 945 946 947 948
	  case AF_INET6:
	    if(addrlen != 16)
		croak("Bad address length for Socket::inet_ntop on AF_INET6;"
		      " got %"UVuf", should be 16", (UV)addrlen);
	    break;
949
#endif
950
	  default:
951
		croak("Bad address family for %s, got %d, should be"
952
#ifdef AF_INET6
953
		      " either AF_INET or AF_INET6",
954
#else
955
		      " AF_INET",
956
#endif
957 958
		      "Socket::inet_ntop", af);
	}
959

960 961 962 963 964 965 966
	if(addrlen < sizeof(addr)) {
	    Copy(ip_address, &addr, addrlen, char);
	    Zero(((char*)&addr) + addrlen, sizeof(addr) - addrlen, char);
	}
	else {
	    Copy(ip_address, &addr, sizeof addr, char);
	}
967
	inet_ntop(af, &addr, str, sizeof str);
968

969
	ST(0) = sv_2mortal(newSVpvn(str, strlen(str)));
970
#else
971
	ST(0) = (SV*)not_here("inet_ntop");
972 973 974 975
#endif

void
inet_pton(af, host)
976 977 978
	int	      af
	const char *  host
	CODE:
979
#ifdef HAS_INETPTON
980 981
	int ok;
	int addrlen = 0;
982 983 984 985 986 987
#ifdef AF_INET6
	struct in6_addr ip_address;
#else
	struct in_addr ip_address;
#endif

988 989 990 991
	switch(af) {
	  case AF_INET:
	    addrlen = 4;
	    break;
992
#ifdef AF_INET6
993 994 995
	  case AF_INET6:
	    addrlen = 16;
	    break;
996
#endif
997
	  default:
998 999
		croak("Bad address family for %s, got %d, should be"
#ifdef AF_INET6
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
		      " either AF_INET or AF_INET6",
#else
		      " AF_INET",
#endif
		      "Socket::inet_pton", af);
	}
	ok = (*host != '\0') && inet_pton(af, host, &ip_address);

	ST(0) = sv_newmortal();
	if (ok) {
		sv_setpvn( ST(0), (char *)&ip_address, addrlen);
	}
#else
	ST(0) = (SV*)not_here("inet_pton");
#endif

void
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
pack_ip_mreq(multiaddr, interface=&PL_sv_undef)
	SV *	multiaddr
	SV *	interface
	CODE:
	{
#ifdef HAS_IP_MREQ
	struct ip_mreq mreq;
	char * multiaddrbytes;
	char * interfacebytes;
	STRLEN len;
	if (DO_UTF8(multiaddr) && !sv_utf8_downgrade(multiaddr, 1))
		croak("Wide character in %s", "Socket::pack_ip_mreq");
	multiaddrbytes = SvPVbyte(multiaddr, len);
	if (len != sizeof(mreq.imr_multiaddr))
		croak("Bad arg length %s, length is %"UVuf", should be %"UVuf,
		      "Socket::pack_ip_mreq", (UV)len, (UV)sizeof(mreq.imr_multiaddr));
	Zero(&mreq, sizeof(mreq), char);
	Copy(multiaddrbytes, &mreq.imr_multiaddr, sizeof(mreq.imr_multiaddr), char);
	if(SvOK(interface)) {
		if (DO_UTF8(interface) && !sv_utf8_downgrade(interface, 1))
			croak("Wide character in %s", "Socket::pack_ip_mreq");
		interfacebytes = SvPVbyte(interface, len);
		if (len != sizeof(mreq.imr_interface))
			croak("Bad arg length %s, length is %"UVuf", should be %"UVuf,
			      "Socket::pack_ip_mreq", (UV)len, (UV)sizeof(mreq.imr_interface));
		Copy(interfacebytes, &mreq.imr_interface, sizeof(mreq.imr_interface), char);
	}
	else
		mreq.imr_interface.s_addr = INADDR_ANY;
	ST(0) = sv_2mortal(newSVpvn((char *)&mreq, sizeof(mreq)));
#else
	not_here("pack_ip_mreq");
#endif
	}

void
unpack_ip_mreq(mreq_sv)
	SV * mreq_sv
	PPCODE:
	{
#ifdef HAS_IP_MREQ
	struct ip_mreq mreq;
	STRLEN mreqlen;
	char * mreqbytes = SvPVbyte(mreq_sv, mreqlen);
	if (mreqlen != sizeof(mreq))
		croak("Bad arg length for %s, length is %"UVuf", should be %"UVuf,
		      "Socket::unpack_ip_mreq", (UV)mreqlen, (UV)sizeof(mreq));
	Copy(mreqbytes, &mreq, sizeof(mreq), char);
	EXTEND(SP, 2);
	mPUSHp((char *)&mreq.imr_multiaddr, sizeof(mreq.imr_multiaddr));
	mPUSHp((char *)&mreq.imr_interface, sizeof(mreq.imr_interface));
#else
	not_here("unpack_ip_mreq");
#endif
	}

void
pack_ip_mreq_source(multiaddr, source, interface=&PL_sv_undef)
	SV *	multiaddr
	SV *	source
	SV *	interface
	CODE:
	{
#if defined(HAS_IP_MREQ_SOURCE) && defined (IP_ADD_SOURCE_MEMBERSHIP)
	struct ip_mreq_source mreq;
	char * multiaddrbytes;
	char * sourcebytes;
	char * interfacebytes;
	STRLEN len;
	if (DO_UTF8(multiaddr) && !sv_utf8_downgrade(multiaddr, 1))
		croak("Wide character in %s", "Socket::pack_ip_mreq_source");
	multiaddrbytes = SvPVbyte(multiaddr, len);
	if (len != sizeof(mreq.imr_multiaddr))
		croak("Bad arg length %s, length is %"UVuf", should be %"UVuf,
		      "Socket::pack_ip_mreq", (UV)len, (UV)sizeof(mreq.imr_multiaddr));
	if (DO_UTF8(source) && !sv_utf8_downgrade(source, 1))
		croak("Wide character in %s", "Socket::pack_ip_mreq_source");
	if (len != sizeof(mreq.imr_sourceaddr))
		croak("Bad arg length %s, length is %"UVuf", should be %"UVuf,
		      "Socket::pack_ip_mreq", (UV)len, (UV)sizeof(mreq.imr_sourceaddr));
	sourcebytes = SvPVbyte(source, len);
	Zero(&mreq, sizeof(mreq), char);
	Copy(multiaddrbytes, &mreq.imr_multiaddr, sizeof(mreq.imr_multiaddr), char);
	Copy(sourcebytes, &mreq.imr_sourceaddr, sizeof(mreq.imr_sourceaddr), char);
	if(SvOK(interface)) {
		if (DO_UTF8(interface) && !sv_utf8_downgrade(interface, 1))
			croak("Wide character in %s", "Socket::pack_ip_mreq");
		interfacebytes = SvPVbyte(interface, len);
		if (len != sizeof(mreq.imr_interface))
			croak("Bad arg length %s, length is %"UVuf", should be %"UVuf,
			      "Socket::pack_ip_mreq", (UV)len, (UV)sizeof(mreq.imr_interface));
		Copy(interfacebytes, &mreq.imr_interface, sizeof(mreq.imr_interface), char);
	}
	else
		mreq.imr_interface.s_addr = INADDR_ANY;
	ST(0) = sv_2mortal(newSVpvn((char *)&mreq, sizeof(mreq)));
#else
	not_here("pack_ip_mreq_source");
#endif
	}

void
unpack_ip_mreq_source(mreq_sv)
	SV * mreq_sv
	PPCODE:
	{
#if defined(HAS_IP_MREQ_SOURCE) && defined (IP_ADD_SOURCE_MEMBERSHIP)
	struct ip_mreq_source mreq;
	STRLEN mreqlen;
	char * mreqbytes = SvPVbyte(mreq_sv, mreqlen);
	if (mreqlen != sizeof(mreq))
		croak("Bad arg length for %s, length is %"UVuf", should be %"UVuf,
		      "Socket::unpack_ip_mreq_source", (UV)mreqlen, (UV)sizeof(mreq));
	Copy(mreqbytes, &mreq, sizeof(mreq), char);
	EXTEND(SP, 3);
	mPUSHp((char *)&mreq.imr_multiaddr, sizeof(mreq.imr_multiaddr));
	mPUSHp((char *)&mreq.imr_sourceaddr, sizeof(mreq.imr_sourceaddr));
	mPUSHp((char *)&mreq.imr_interface, sizeof(mreq.imr_interface));
#else
	not_here("unpack_ip_mreq_source");
#endif
	}

void
1141
pack_ipv6_mreq(multiaddr, ifindex)
1142
	SV *	multiaddr
1143
	unsigned int	ifindex
1144 1145 1146 1147
	CODE:
	{
#ifdef HAS_IPV6_MREQ
	struct ipv6_mreq mreq;
1148 1149 1150
	char * multiaddrbytes;
	STRLEN len;
	if (DO_UTF8(multiaddr) && !sv_utf8_downgrade(multiaddr, 1))
1151
		croak("Wide character in %s", "Socket::pack_ipv6_mreq");
1152 1153
	multiaddrbytes = SvPVbyte(multiaddr, len);
	if (len != sizeof(mreq.ipv6mr_multiaddr))
1154
		croak("Bad arg length %s, length is %"UVuf", should be %"UVuf,
1155
		      "Socket::pack_ipv6_mreq", (UV)len, (UV)sizeof(mreq.ipv6mr_multiaddr));
1156
	Zero(&mreq, sizeof(mreq), char);
1157
	Copy(multiaddrbytes, &mreq.ipv6mr_multiaddr, sizeof(mreq.ipv6mr_multiaddr), char);
1158
	mreq.ipv6mr_interface = ifindex;
1159
	ST(0) = sv_2mortal(newSVpvn((char *)&mreq, sizeof(mreq)));
1160
#else
1161
	not_here("pack_ipv6_mreq");
1162
#endif
1163
	}
1164

1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
void
unpack_ipv6_mreq(mreq_sv)
	SV * mreq_sv
	PPCODE:
	{
#ifdef HAS_IPV6_MREQ
	struct ipv6_mreq mreq;
	STRLEN mreqlen;
	char * mreqbytes = SvPVbyte(mreq_sv, mreqlen);
	if (mreqlen != sizeof(mreq))
		croak("Bad arg length for %s, length is %"UVuf", should be %"UVuf,
		      "Socket::unpack_ipv6_mreq", (UV)mreqlen, (UV)sizeof(mreq));
	Copy(mreqbytes, &mreq, sizeof(mreq), char);
	EXTEND(SP, 2);
	mPUSHp((char *)&mreq.ipv6mr_multiaddr, sizeof(mreq.ipv6mr_multiaddr));
	mPUSHi(mreq.ipv6mr_interface);
1181
#else
1182
	not_here("unpack_ipv6_mreq");
1183
#endif
1184
	}