/*
 * This file was generated automatically by ExtUtils::ParseXS version 3.45 from the
 * contents of Lookup.xs. Do not edit this file, edit Lookup.xs instead.
 *
 *    ANY CHANGES MADE HERE WILL BE LOST!
 *
 */

#line 1 "Lookup.xs"
#define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

#include "ppport.h"

#include "const-c.inc"


#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <net/if.h>
#include <ifaddrs.h>
#include <sys/un.h>
#endif

#define AV_FLAGS      0
#define AV_FAMILY     1
#define AV_TYPE       2
#define AV_PROTOCOL   3
#define AV_ADDR       4
#define AV_CANONNAME  5

#line 39 "Lookup.c"
#ifndef PERL_UNUSED_VAR
#  define PERL_UNUSED_VAR(var) if (0) var = var
#endif

#ifndef dVAR
#  define dVAR		dNOOP
#endif


/* This stuff is not part of the API! You have been warned. */
#ifndef PERL_VERSION_DECIMAL
#  define PERL_VERSION_DECIMAL(r,v,s) (r*1000000 + v*1000 + s)
#endif
#ifndef PERL_DECIMAL_VERSION
#  define PERL_DECIMAL_VERSION \
	  PERL_VERSION_DECIMAL(PERL_REVISION,PERL_VERSION,PERL_SUBVERSION)
#endif
#ifndef PERL_VERSION_GE
#  define PERL_VERSION_GE(r,v,s) \
	  (PERL_DECIMAL_VERSION >= PERL_VERSION_DECIMAL(r,v,s))
#endif
#ifndef PERL_VERSION_LE
#  define PERL_VERSION_LE(r,v,s) \
	  (PERL_DECIMAL_VERSION <= PERL_VERSION_DECIMAL(r,v,s))
#endif

/* XS_INTERNAL is the explicit static-linkage variant of the default
 * XS macro.
 *
 * XS_EXTERNAL is the same as XS_INTERNAL except it does not include
 * "STATIC", ie. it exports XSUB symbols. You probably don't want that
 * for anything but the BOOT XSUB.
 *
 * See XSUB.h in core!
 */


/* TODO: This might be compatible further back than 5.10.0. */
#if PERL_VERSION_GE(5, 10, 0) && PERL_VERSION_LE(5, 15, 1)
#  undef XS_EXTERNAL
#  undef XS_INTERNAL
#  if defined(__CYGWIN__) && defined(USE_DYNAMIC_LOADING)
#    define XS_EXTERNAL(name) __declspec(dllexport) XSPROTO(name)
#    define XS_INTERNAL(name) STATIC XSPROTO(name)
#  endif
#  if defined(__SYMBIAN32__)
#    define XS_EXTERNAL(name) EXPORT_C XSPROTO(name)
#    define XS_INTERNAL(name) EXPORT_C STATIC XSPROTO(name)
#  endif
#  ifndef XS_EXTERNAL
#    if defined(HASATTRIBUTE_UNUSED) && !defined(__cplusplus)
#      define XS_EXTERNAL(name) void name(pTHX_ CV* cv __attribute__unused__)
#      define XS_INTERNAL(name) STATIC void name(pTHX_ CV* cv __attribute__unused__)
#    else
#      ifdef __cplusplus
#        define XS_EXTERNAL(name) extern "C" XSPROTO(name)
#        define XS_INTERNAL(name) static XSPROTO(name)
#      else
#        define XS_EXTERNAL(name) XSPROTO(name)
#        define XS_INTERNAL(name) STATIC XSPROTO(name)
#      endif
#    endif
#  endif
#endif

/* perl >= 5.10.0 && perl <= 5.15.1 */


/* The XS_EXTERNAL macro is used for functions that must not be static
 * like the boot XSUB of a module. If perl didn't have an XS_EXTERNAL
 * macro defined, the best we can do is assume XS is the same.
 * Dito for XS_INTERNAL.
 */
#ifndef XS_EXTERNAL
#  define XS_EXTERNAL(name) XS(name)
#endif
#ifndef XS_INTERNAL
#  define XS_INTERNAL(name) XS(name)
#endif

/* Now, finally, after all this mess, we want an ExtUtils::ParseXS
 * internal macro that we're free to redefine for varying linkage due
 * to the EXPORT_XSUB_SYMBOLS XS keyword. This is internal, use
 * XS_EXTERNAL(name) or XS_INTERNAL(name) in your code if you need to!
 */

#undef XS_EUPXS
#if defined(PERL_EUPXS_ALWAYS_EXPORT)
#  define XS_EUPXS(name) XS_EXTERNAL(name)
#else
   /* default to internal */
#  define XS_EUPXS(name) XS_INTERNAL(name)
#endif

#ifndef PERL_ARGS_ASSERT_CROAK_XS_USAGE
#define PERL_ARGS_ASSERT_CROAK_XS_USAGE assert(cv); assert(params)

/* prototype to pass -Wmissing-prototypes */
STATIC void
S_croak_xs_usage(const CV *const cv, const char *const params);

STATIC void
S_croak_xs_usage(const CV *const cv, const char *const params)
{
    const GV *const gv = CvGV(cv);

    PERL_ARGS_ASSERT_CROAK_XS_USAGE;

    if (gv) {
        const char *const gvname = GvNAME(gv);
        const HV *const stash = GvSTASH(gv);
        const char *const hvname = stash ? HvNAME(stash) : NULL;

        if (hvname)
	    Perl_croak_nocontext("Usage: %s::%s(%s)", hvname, gvname, params);
        else
	    Perl_croak_nocontext("Usage: %s(%s)", gvname, params);
    } else {
        /* Pants. I don't think that it should be possible to get here. */
	Perl_croak_nocontext("Usage: CODE(0x%" UVxf ")(%s)", PTR2UV(cv), params);
    }
}
#undef  PERL_ARGS_ASSERT_CROAK_XS_USAGE

#define croak_xs_usage        S_croak_xs_usage

#endif

/* NOTE: the prototype of newXSproto() is different in versions of perls,
 * so we define a portable version of newXSproto()
 */
#ifdef newXS_flags
#define newXSproto_portable(name, c_impl, file, proto) newXS_flags(name, c_impl, file, proto, 0)
#else
#define newXSproto_portable(name, c_impl, file, proto) (PL_Sv=(SV*)newXS(name, c_impl, file), sv_setpv(PL_Sv, proto), (CV*)PL_Sv)
#endif /* !defined(newXS_flags) */

#if PERL_VERSION_LE(5, 21, 5)
#  define newXS_deffile(a,b) Perl_newXS(aTHX_ a,b,file)
#else
#  define newXS_deffile(a,b) Perl_newXS_deffile(aTHX_ a,b)
#endif

#line 183 "Lookup.c"

/* INCLUDE:  Including 'const-xs.inc' from 'Lookup.xs' */


XS_EUPXS(XS_Socket__More__Lookup_constant); /* prototype to pass -Wmissing-prototypes */
XS_EUPXS(XS_Socket__More__Lookup_constant)
{
    dVAR; dXSARGS;
    if (items != 1)
       croak_xs_usage(cv,  "sv");
    PERL_UNUSED_VAR(ax); /* -Wall */
    SP -= items;
    {
#line 4 "./const-xs.inc"
#ifdef dXSTARG
	dXSTARG; /* Faster if we have it.  */
#else
	dTARGET;
#endif
	STRLEN		len;
        int		type;
	/* IV		iv;	Uncomment this if you need to return IVs */
	/* NV		nv;	Uncomment this if you need to return NVs */
	/* const char	*pv;	Uncomment this if you need to return PVs */
#line 208 "Lookup.c"
	SV *	sv = ST(0)
;
	const char *	s = SvPV(sv, len);
#line 18 "./const-xs.inc"
	type = constant(aTHX_ s, len);
      /* Return 1 or 2 items. First is error message, or undef if no error.
           Second, if present, is found value */
        switch (type) {
        case PERL_constant_NOTFOUND:
          sv =
	    sv_2mortal(newSVpvf("%s is not a valid Socket::More::Lookup macro", s));
          PUSHs(sv);
          break;
        case PERL_constant_NOTDEF:
          sv = sv_2mortal(newSVpvf(
	    "Your vendor has not defined Socket::More::Lookup macro %s, used",
				   s));
          PUSHs(sv);
          break;
	/* Uncomment this if you need to return IVs
        case PERL_constant_ISIV:
          EXTEND(SP, 2);
          PUSHs(&PL_sv_undef);
          PUSHi(iv);
          break; */
	/* Uncomment this if you need to return NOs
        case PERL_constant_ISNO:
          EXTEND(SP, 2);
          PUSHs(&PL_sv_undef);
          PUSHs(&PL_sv_no);
          break; */
	/* Uncomment this if you need to return NVs
        case PERL_constant_ISNV:
          EXTEND(SP, 2);
          PUSHs(&PL_sv_undef);
          PUSHn(nv);
          break; */
	/* Uncomment this if you need to return PVs
        case PERL_constant_ISPV:
          EXTEND(SP, 2);
          PUSHs(&PL_sv_undef);
          PUSHp(pv, strlen(pv));
          break; */
	/* Uncomment this if you need to return PVNs
        case PERL_constant_ISPVN:
          EXTEND(SP, 2);
          PUSHs(&PL_sv_undef);
          PUSHp(pv, iv);
          break; */
	/* Uncomment this if you need to return SVs
        case PERL_constant_ISSV:
          EXTEND(SP, 2);
          PUSHs(&PL_sv_undef);
          PUSHs(sv);
          break; */
	/* Uncomment this if you need to return UNDEFs
        case PERL_constant_ISUNDEF:
          break; */
	/* Uncomment this if you need to return UVs
        case PERL_constant_ISUV:
          EXTEND(SP, 2);
          PUSHs(&PL_sv_undef);
          PUSHu((UV)iv);
          break; */
	/* Uncomment this if you need to return YESs
        case PERL_constant_ISYES:
          EXTEND(SP, 2);
          PUSHs(&PL_sv_undef);
          PUSHs(&PL_sv_yes);
          break; */
        default:
          sv = sv_2mortal(newSVpvf(
	    "Unexpected return type %d while processing Socket::More::Lookup macro %s, used",
               type, s));
          PUSHs(sv);
        }
#line 285 "Lookup.c"
	PUTBACK;
	return;
    }
}


/* INCLUDE: Returning to 'Lookup.xs' from 'const-xs.inc' */


XS_EUPXS(XS_Socket__More__Lookup_getaddrinfo); /* prototype to pass -Wmissing-prototypes */
XS_EUPXS(XS_Socket__More__Lookup_getaddrinfo)
{
    dVAR; dXSARGS;
    if (items != 4)
       croak_xs_usage(cv,  "hostname, servicename, hints, results");
    PERL_UNUSED_VAR(ax); /* -Wall */
    SP -= items;
    {
	SV *	hostname = ST(0)
;
	SV *	servicename = ST(1)
;
	SV *	hints = ST(2)
;
	AV *	results;
	SV *	RETVAL;

	STMT_START {
		SV* const xsub_tmp_sv = ST(3);
		SvGETMAGIC(xsub_tmp_sv);
		if (SvROK(xsub_tmp_sv) && SvTYPE(SvRV(xsub_tmp_sv)) == SVt_PVAV){
		    results = (AV*)SvRV(xsub_tmp_sv);
		}
		else{
		    Perl_croak_nocontext("%s: %s is not an ARRAY reference",
				"Socket::More::Lookup::getaddrinfo",
				"results");
		}
	} STMT_END
;
#line 55 "Lookup.xs"
    int ret;
    char *hname=NULL;
    char *sname=NULL;
    struct addrinfo *res;
    struct addrinfo h;
    struct addrinfo  *hh=NULL;
    struct addrinfo *next;
    int len;
    SV *temp;
    bool return_av;


#line 339 "Lookup.c"
#line 68 "Lookup.xs"
    h.ai_flags=0;
    h.ai_family=0;
    h.ai_socktype=0;
    h.ai_protocol=0;
    h.ai_addrlen=0;
    h.ai_addr=NULL;
    h.ai_canonname=NULL;
    h.ai_next=NULL;

    // First check that output array is doable

    //expectiong a hostname 

    return_av=false; //Default to a hash return

    if(SvOK(hostname) && SvPOK(hostname)){
      len=SvCUR(hostname);
      hname=SvPVX(hostname);//SvGROW(hostname,1);
      hname[len]='\0';
      //Perl_croak(aTHX_ "This croaked because: %" SVf "\n", SVfARG(hostname));
    }
    else{
    }
    if(SvOK(servicename)){
      if(SvPOK(servicename)){
        len=SvCUR(servicename);
        sname=SvPVX(servicename);//SvGROW(servicename,1);
        sname[len]='\0';
      }
      else if (SvIOK(servicename)){
        temp=newSVpvf("%" SVf , SVfARG(servicename));
        len=SvCUR(temp);
        sname=SvPVX(temp);
        sname[len]='\0';
      }


    }

    if(SvOK(hints) && SvROK(hints)){
      SV** temp;
      SV** key;
      SV** val;
      AV* av; 
      HV* hv;
      int len;
      int i=0;

      switch(SvTYPE(SvRV(hints))){
        case SVt_PVAV:
          // Treat as 'array struct'

          return_av=true;
          av=(AV *)SvRV(hints);

          len=av_top_index(av)+1;
          if(len){


            val=av_fetch(av,i++,0);
            if((val != NULL) && SvOK(*val)){
              //fprintf(stderr, "FLAGS: %ld\n",SvIV(*val));
              h.ai_flags = SvIV(*val);
            }

            val=av_fetch(av,i++,0);
            if((val != NULL) && SvOK(*val)){
              //fprintf(stderr, "family: %ld\n",SvIV(*val));
              h.ai_family = SvIV(*val);
            }

            val=av_fetch(av,i++,0);
            if((val != NULL) && SvOK(*val)){
              //fprintf(stderr, "sock type: %ld\n",SvIV(*val));
              h.ai_socktype = SvIV(*val);
            }

            val=av_fetch(av,i++,0);
            if((val != NULL) && SvOK(*val)){
              //fprintf(stderr, "protocol: %ld\n",SvIV(*val));
              h.ai_protocol = SvIV(*val);
            }
            hh=&h;
          }
          else {
            //Empty array, treat as default, but still want array
            hh=NULL;
          }

          break;

        case SVt_PVHV:
          return_av=false;
          hv=(HV *)SvRV(hints);
          temp=hv_fetch(hv,"flags",5,1);
          if((temp != NULL ) && SvIOK(*temp)){
            h.ai_flags = SvIV(*temp);
          }
          temp=hv_fetch(hv,"family",6,1);
          if((temp != NULL ) && SvIOK(*temp)){
            h.ai_family = SvIV(*temp);
          }
          temp=hv_fetch(hv,"socktype",8,1);
          if((temp != NULL ) && SvIOK(*temp)){
            h.ai_socktype = SvIV(*temp);
          }
          temp=hv_fetch(hv,"protocol",8,1);
          if((temp != NULL ) && SvIOK(*temp)){
            h.ai_protocol = SvIV(*temp);
          }
          hh=&h;

          break;

        default:
          //Perl_croak(aTHX_ "%s", "Hints must be an array or hash ref");
          // Assume no hints. Let getaddrinfo work with the default hints by setting to NULL 
          hh=NULL;
          break;
      }
    }


    ret=getaddrinfo(hname, sname, hh, &res);


    if(ret!=0){
      // The return array to error?
      errno=ret;
      XSRETURN_UNDEF;
    }
    else{
      // Copy results into output array
      HV *h;
      AV *a;
      int count=0;
      next=res;
      while(next){
        count++;
        next=next->ai_next;
      }
      av_extend(results,count);
      //Resize output array to  fit count 
      int i=0;
      next=res;
      if(return_av){
        while(next){
          a=newAV();
          av_store(a, AV_FLAGS, newSViv(0));
          av_store(a, AV_FAMILY, newSViv(next->ai_family));
          av_store(a, AV_TYPE, newSViv(next->ai_socktype));
          av_store(a, AV_PROTOCOL, newSViv(next->ai_protocol));
          av_store(a, AV_ADDR, newSVpv((char *) next->ai_addr, next->ai_addrlen));
          if(next->ai_canonname == NULL){
            av_store(a, AV_CANONNAME, newSVpv("",0));
          }
          else {
            av_store(a, AV_CANONNAME, newSVpv((char *)next->ai_canonname,0));
          }
          //Push results to return stack
          next=next->ai_next;
          av_store(results, i, newRV_noinc((SV *)a));
          i++;
        }
      }
      else {
        while(next){
          h=newHV();
          hv_store(h, "family", 6, newSViv(next->ai_family), 0);
          hv_store(h, "socktype", 8, newSViv(next->ai_socktype), 0);
          hv_store(h, "protocol", 8, newSViv(next->ai_protocol), 0);
          hv_store(h, "addr", 4, newSVpv((char *)(next->ai_addr), next->ai_addrlen), 0);
          if(next->ai_canonname == NULL){
            hv_store(h, "canonname", 9, newSVpv("",0), 0);
          }
          else {
            hv_store(h, "canonname", 9, newSVpv(next->ai_canonname,0), 0);
          }


          //Push results to return stack
          next=next->ai_next;
          av_store(results,i,newRV_noinc((SV *)h));
          i++;

        }
      }
      freeaddrinfo(res);
      XSRETURN_IV(1);
    }
#line 531 "Lookup.c"
	PUTBACK;
	return;
    }
}


XS_EUPXS(XS_Socket__More__Lookup_gai_strerror); /* prototype to pass -Wmissing-prototypes */
XS_EUPXS(XS_Socket__More__Lookup_gai_strerror)
{
    dVAR; dXSARGS;
    if (items != 1)
       croak_xs_usage(cv,  "code");
    {
	int	code = (int)SvIV(ST(0))
;
	const char *	RETVAL;
	dXSTARG;

	RETVAL = gai_strerror(code);
	sv_setpv(TARG, RETVAL);
	XSprePUSH;
	PUSHTARG;
    }
    XSRETURN(1);
}


XS_EUPXS(XS_Socket__More__Lookup_getnameinfo); /* prototype to pass -Wmissing-prototypes */
XS_EUPXS(XS_Socket__More__Lookup_getnameinfo)
{
    dVAR; dXSARGS;
    if (items != 4)
       croak_xs_usage(cv,  "address, hostname, servicename, flags");
    PERL_UNUSED_VAR(ax); /* -Wall */
    SP -= items;
    {
	SV *	address = ST(0)
;
	SV *	hostname = ST(1)
;
	SV *	servicename = ST(2)
;
	SV *	flags = ST(3)
;
	SV *	RETVAL;
#line 274 "Lookup.xs"
    int ret;
    char *host;
    char *service;
    int fl;
    int addrlen;
    struct sockaddr *addr;

#line 585 "Lookup.c"
#line 283 "Lookup.xs"
    //Ensure outputs are not readonly

    if(SvREADONLY(hostname) || SvREADONLY(servicename)){
            Perl_croak(aTHX_ "%s", PL_no_modify);
    }

    if(SvOK(address) && SvPOK(address)){
      addrlen=SvCUR(address);
      addr=(struct sockaddr *)SvPVX(address);//SvGROW(address,0);
    }

    if(!SvOK(hostname)){
      hostname=sv_2mortal(newSV(NI_MAXHOST+1));

    }

    SvPOK_on(hostname);
    host=SvGROW(hostname, NI_MAXHOST+1);

    if(!SvOK(servicename)){
      servicename=sv_2mortal(newSV(NI_MAXSERV+1));
    }

    SvPOK_on(servicename);
    service=SvGROW(servicename, NI_MAXSERV+1);


    if(SvOK(flags)  && SvIOK(flags)){
      fl=SvIV(flags); 
    }
    else {
      fl=0;
    }

    ret=getnameinfo(addr, addrlen, host, NI_MAXHOST, service, NI_MAXSERV, fl);

    if(ret==0){
      //Update the actual length used
      SvCUR_set(hostname, strlen(host));
      SvCUR_set(servicename, strlen(service));

      //Return as no error (true)
      XSRETURN_IV(1);

    }
    else {
      //return as error, and set errno
      errno=ret;
      //SV * e=get_sv("!",GV_ADD);
      //sv_setiv(e, ret);
      //sv_setpv(e, gai_strerror(ret));
      XSRETURN_UNDEF; 
    }
#line 640 "Lookup.c"
	PUTBACK;
	return;
	sv_setsv_mg(ST(1), hostname);
	SvSETMAGIC(ST(1));
	sv_setsv_mg(ST(2), servicename);
	SvSETMAGIC(ST(2));
    }
}

#ifdef __cplusplus
extern "C"
#endif
XS_EXTERNAL(boot_Socket__More__Lookup); /* prototype to pass -Wmissing-prototypes */
XS_EXTERNAL(boot_Socket__More__Lookup)
{
#if PERL_VERSION_LE(5, 21, 5)
    dVAR; dXSARGS;
#else
    dVAR; dXSBOOTARGSXSAPIVERCHK;
#endif
#if PERL_VERSION_LE(5, 8, 999) /* PERL_VERSION_LT is 5.33+ */
    char* file = __FILE__;
#else
    const char* file = __FILE__;
#endif

    PERL_UNUSED_VAR(file);

    PERL_UNUSED_VAR(cv); /* -W */
    PERL_UNUSED_VAR(items); /* -W */
#if PERL_VERSION_LE(5, 21, 5)
    XS_VERSION_BOOTCHECK;
#  ifdef XS_APIVERSION_BOOTCHECK
    XS_APIVERSION_BOOTCHECK;
#  endif
#endif

        newXS_deffile("Socket::More::Lookup::constant", XS_Socket__More__Lookup_constant);
        (void)newXSproto_portable("Socket::More::Lookup::getaddrinfo", XS_Socket__More__Lookup_getaddrinfo, file, "$$$\\@");
        newXS_deffile("Socket::More::Lookup::gai_strerror", XS_Socket__More__Lookup_gai_strerror);
        (void)newXSproto_portable("Socket::More::Lookup::getnameinfo", XS_Socket__More__Lookup_getnameinfo, file, "$$$$");

    /* Initialisation Section */

#line 35 "Lookup.xs"
#ifdef WIN32
     // Initialize Winsock or nothing works
     WSADATA wsaData;
     int iResult;
      iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
      if (iResult != 0) {
          Perl_croak(aTHX_ "WSAStartup failed: %d\n", iResult);
      }
#endif

#line 696 "Lookup.c"

    /* End of Initialisation Section */

#if PERL_VERSION_LE(5, 21, 5)
#  if PERL_VERSION_GE(5, 9, 0)
    if (PL_unitcheckav)
        call_list(PL_scopestack_ix, PL_unitcheckav);
#  endif
    XSRETURN_YES;
#else
    Perl_xs_boot_epilog(aTHX_ ax);
#endif
}

