/*---------------------------------------------------------------------------*
  C MODULE  cf_nameinfo_p.c

  Copyright (c) 2003-2006, James H. Woodyatt
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:

    Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

    Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  OF THE POSSIBILITY OF SUCH DAMAGE. 
 *---------------------------------------------------------------------------*/

#include "cf_nameinfo_p.h"

#include <string.h>
#include <netdb.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>

#include <netinet/in.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>


#define INVALID_ARGUMENT(S)     (invalid_argument("Cf_nameinfo." S))
#define FAILWITH(S)             (failwith("Cf_nameinfo." S))

static int cf_nameinfo_sockaddr_compare(value v1, value v2)
{
    CAMLparam2(v1, v2);
    const Cf_socket_sockaddrx_unit_t* sxPtr[2];
    const struct sockaddr* saPtr[2];
    int result;
    
    sxPtr[0] = Cf_socket_sockaddrx_unit_val(v1);
    saPtr[0] = &sxPtr[0]->sx_sockaddr;
    sxPtr[1] = Cf_socket_sockaddrx_unit_val(v2);    
    saPtr[1] = &sxPtr[1]->sx_sockaddr;

    result = saPtr[0]->sa_family - saPtr[1]->sa_family;
    if (!result) {
        result = sxPtr[0]->sx_socklen - sxPtr[1]->sx_socklen;
        if (!result) {
            size_t ssLen = sxPtr[0]->sx_socklen;
            result = memcmp(saPtr[0]->sa_data, saPtr[1]->sa_data, ssLen);
        }
    }
    
    CAMLreturn(result);
}

static long cf_nameinfo_sockaddr_hash(value sxVal)
{
    CAMLparam1(sxVal);
    const Cf_socket_sockaddrx_unit_t* sxPtr;
    const struct sockaddr* saPtr;
    unsigned long result;
    unsigned int i;
    
    sxPtr = Cf_socket_sockaddrx_unit_val(sxVal);
    saPtr = (const struct sockaddr*) &sxPtr->sx_sockaddr;
    for (result = 0, i = 0; i < sxPtr->sx_socklen; ++i) {
        unsigned long x = result >> 24;
        result <<= 8;
        result |= saPtr->sa_data[i] ^ x;
    }
    
    CAMLreturn((long) result);
}

static void cf_nameinfo_sockaddr_serialize
   (value sxVal, unsigned long* size32Ptr, unsigned long* size64Ptr)
{
    CAMLparam1(sxVal);
    Cf_socket_sockaddrx_unit_t* sxPtr;
    size_t saLen, sxLen;
        
    sxPtr = Cf_socket_sockaddrx_unit_val(sxVal); 
    sxLen =
        offsetof(Cf_socket_sockaddrx_unit_t, sx_sockaddr) +
        sxPtr->sx_socklen;
    
    serialize_int_1(sxPtr->sx_socklen);
    serialize_block_1((void*) &sxPtr->sx_sockaddr, sxPtr->sx_socklen);
    
    *size32Ptr = sxLen;
    *size64Ptr = sxLen;
    
    CAMLreturn0;
}

static unsigned long cf_nameinfo_sockaddr_deserialize(void* bufferPtr)
{
    Cf_socket_sockaddrx_unit_t* sxPtr;
    size_t sxLen;
    
    sxPtr = (Cf_socket_sockaddrx_unit_t*) bufferPtr;
    sxPtr->sx_socklen = deserialize_uint_1();
    deserialize_block_1((void*) &sxPtr->sx_sockaddr, sxPtr->sx_socklen);

    return
        offsetof(Cf_socket_sockaddrx_unit_t, sx_sockaddr) +
        sxPtr->sx_socklen;
}

static struct custom_operations cf_nameinfo_sockaddr_op = {
    "org.conjury.pagoda.cf.sockaddr_nameinfo",
    custom_finalize_default,
    cf_nameinfo_sockaddr_compare,
    cf_nameinfo_sockaddr_hash,
    cf_nameinfo_sockaddr_serialize,
    cf_nameinfo_sockaddr_deserialize
};

value cf_nameinfo_sockaddr_cons(const struct sockaddr* saPtr, size_t saLen)
{
    value sxVal;
    Cf_socket_sockaddrx_unit_t* sxPtr;
    const size_t sxLen =
        offsetof(Cf_socket_sockaddrx_unit_t, sx_sockaddr) + saLen;
        
    sxVal = alloc_custom(&cf_nameinfo_sockaddr_op, sxLen, 0, 1);
    sxPtr = Cf_socket_sockaddrx_unit_val(sxVal);
    if (sxPtr) {
        sxPtr->sx_socklen = saLen;
        memcpy(&sxPtr->sx_sockaddr, saPtr, saLen);
        
        #if defined(IN6_IS_ADDR_LINKLOCAL)
        /* a rude hack to work around common bugs on some BSD systems */
        if (sxPtr->sx_sockaddr.sa_family == AF_INET6) {
            struct sockaddr_in6* sin6Ptr =
                (struct sockaddr_in6*) &sxPtr->sx_sockaddr;
            struct in6_addr* in6Ptr = &sin6Ptr->sin6_addr;
            if (IN6_IS_ADDR_LINKLOCAL(in6Ptr)) {
                uint16_t* u16Ptr = (uint16_t*) in6Ptr->s6_addr;
                if (sin6Ptr->sin6_scope_id == 0)
                    sin6Ptr->sin6_scope_id = ntohs(u16Ptr[1]);
                u16Ptr[1] = 0;
            }
        }
        #endif
    }
    
    return sxVal;
}

static Cf_socket_domain_t cf_nameinfo_pf_unspec = {
    PF_UNSPEC, AF_UNSPEC, cf_nameinfo_sockaddr_cons,
    sizeof(struct sockaddr_storage)
};

static value* cf_nameinfo_unresolved_exn = 0;
static value cf_nameinfo_domain_val = Val_unit;
static value cf_nameinfo_socktype_val = Val_unit;
static value cf_nameinfo_protocol_val = Val_unit;
static value cf_nameinfo_unspecified_val = Val_unit;
static value cf_nameinfo_default_ai_flags_val = Val_unit;

/*---
    external domain_: unit -> unit Cf_socket.domain_t = "cf_nameinfo_domain"
  ---*/
CAMLprim value cf_nameinfo_domain(value unit)
{
    CAMLparam0();
    CAMLreturn(cf_nameinfo_domain_val);
}

/*---
    external socktype_:
        unit -> unit Cf_socket.socktype_t = "cf_nameinfo_socktype"
  ---*/
CAMLprim value cf_nameinfo_socktype(value unit)
{
    CAMLparam0();
    CAMLreturn(cf_nameinfo_socktype_val);
}

/*---
    external protocol_: unit -> Cf_socket.protocol_t = "cf_nameinfo_protocol"
  ---*/
CAMLprim value cf_nameinfo_protocol(value unit)
{
    CAMLparam0();
    CAMLreturn(cf_nameinfo_protocol_val);
}

/*---
    external unspecified_: unit -> address_t = "cf_nameinfo_unspecified"
  ---*/
CAMLprim value cf_nameinfo_unspecified(value unit)
{
    CAMLparam0();
    CAMLreturn(cf_nameinfo_unspecified_val);
}

/*---
    external default_ai_flags_:
        unit -> to_address_default_flags = "cf_nameinfo_default_ai_flags"
  ---*/
CAMLprim value cf_nameinfo_default_ai_flags(value unit)
{
    CAMLparam0();
    CAMLreturn(cf_nameinfo_default_ai_flags_val);
}


/*---
    external is_specific_socktype:
        unit Cf_socket.socktype_t -> 'st Cf_socket.socktype_t -> bool =
        "cf_nameinfo_is_specific_socktype"
  ---*/
CAMLprim value cf_nameinfo_is_specific_socktype(value unitStVal, value xStVal)
{
    CAMLparam2(unitStVal, xStVal);
    CAMLreturn(Val_bool(Nativeint_val(unitStVal) == Nativeint_val(xStVal)));
}

/*---
    external is_specific_domain:
        unit Cf_socket.sockaddr_t -> 'af Cf_socket.domain_t -> bool =
        "cf_nameinfo_is_specific_domain"
  ---*/
CAMLprim value cf_nameinfo_is_specific_domain(value sxVal, value domainVal)
{
    CAMLparam2(sxVal, domainVal);    
    const Cf_socket_sockaddrx_unit_t* sxPtr;
    const Cf_socket_domain_t* domainPtr;
    int result;
    
    sxPtr = Cf_socket_sockaddrx_unit_val(sxVal);
    domainPtr = Cf_socket_domain_val(domainVal);
    
    result =
        !!((int) domainPtr->d_family == (int) sxPtr->sx_sockaddr.sa_family);
    
    CAMLreturn(Val_bool(result));
}

/*---
    external specialize_sockaddr:
        unit Cf_socket.sockaddr_t -> 'af Cf_socket.domain_t ->
        'af Cf_socket.sockaddr_t = "cf_nameinfo_specialize_sockaddr"
  ---*/
CAMLprim value cf_nameinfo_specialize_sockaddr(value sxVal, value domainVal)
{
    CAMLparam2(sxVal, domainVal);
    CAMLlocal2(resultVal, someVal);
    
    const Cf_socket_sockaddrx_unit_t* sxPtr;
    const Cf_socket_domain_t* domainPtr;
    
    sxPtr = Cf_socket_sockaddrx_unit_val(sxVal);
    domainPtr = Cf_socket_domain_val(domainVal);
    
    if ((int) domainPtr->d_family != (int) sxPtr->sx_sockaddr.sa_family)
        caml_raise_not_found();
        
    resultVal = domainPtr->d_consaddr((struct sockaddr*) &sxPtr->sx_sockaddr,
        domainPtr->d_socklen);
    CAMLreturn(resultVal);
}

/*---
type unresolved_t =
    EAI_ADDRFAMILY | EAI_AGAIN | EAI_BADFLAGS | EAI_FAIL | EAI_FAMILY |
    EAI_MEMORY | EAI_NODATA | EAI_NONAME | EAI_SERVICE | EAI_SOCKTYPE |
    EAI_BADHINTS | EAI_PROTOCOL | EAI_UNKNOWN of int
  ---*/
static const int cf_nameinfo_unresolved_array[] = {
  /*EAI_ADDRFAMILY,*/ EAI_AGAIN, EAI_BADFLAGS, EAI_FAIL, EAI_FAMILY,
  EAI_MEMORY, /* EAI_NODATA, */ EAI_NONAME, EAI_SERVICE, EAI_SOCKTYPE,
#ifdef EAI_BADHINTS
    EAI_BADHINTS,
#endif
#ifdef EAI_PROTOCOL
    EAI_PROTOCOL
#endif
};

#define CF_NAMEINFO_UNRESOLVED_ARRAY_SIZE \
    (sizeof cf_nameinfo_unresolved_array / \
        sizeof cf_nameinfo_unresolved_array[0])

value cf_nameinfo_unresolved_of_code(int error)
{
    value resultVal;
    int i;
    
    for (i = 0; i < CF_NAMEINFO_UNRESOLVED_ARRAY_SIZE; ++i)
        if (cf_nameinfo_unresolved_array[i] == error)
            return Val_int(i);
    
    resultVal = alloc_small(1, 0);
    Store_field(resultVal, 0, Val_int(error));
    return resultVal;
}

/*---
    external error_message:
        unresolved_t -> string = "cf_nameinfo_error_message"
  ---*/
CAMLprim value cf_nameinfo_error_message(value codeVal)
{
    CAMLparam1(codeVal);
    CAMLlocal1(resultVal);
    
    if (Is_block(codeVal)) {
        char buffer[128];
        sprintf(buffer, "unknown error (code=%d)",
            (int) Int_val(Field(codeVal, 0)));
        resultVal = copy_string(buffer);
    }
    else {
        int code;
        const char* msgPtr;
        
        code = cf_nameinfo_unresolved_array[Int_val(codeVal)];
        msgPtr = gai_strerror(code);
        resultVal = copy_string(msgPtr);
    }
    
    CAMLreturn(resultVal);
}

/*---
    type of_address_flags_t = {
        ni_nofqdn: bool;
        ni_numerichost: bool;
        ni_namereqd: bool;
        ni_numericserv: bool;
        ni_dgram: bool;
    }
  ---*/
static const int cf_nameinfo_of_address_flags_array[] = {
    NI_NOFQDN, NI_NUMERICHOST, NI_NAMEREQD, NI_NUMERICSERV, NI_DGRAM,
};

#define Cf_nameinfo_of_address_flags_array_size \
    (sizeof cf_nameinfo_of_address_flags_array \
     / sizeof cf_nameinfo_of_address_flags_array[0])

int cf_nameinfo_of_address_flags_to_int(value flagsVal)
{
    int flags = 0;
    int i;
    
    for (i = 0; i < Cf_nameinfo_of_address_flags_array_size; ++i)
        if (Field(flagsVal, i) != Val_false)
            flags |= cf_nameinfo_of_address_flags_array[i];
    
    return flags;
}

value cf_nameinfo_of_address_flags_of_int(int flags)
{
    CAMLparam0();
    CAMLlocal1(flagsVal);
    int i;
    
    flagsVal = alloc_small(Cf_nameinfo_of_address_flags_array_size, 0);
    for (i = 0; i < Cf_nameinfo_of_address_flags_array_size; ++i)
        Store_field(flagsVal, i,
            (flags & cf_nameinfo_of_address_flags_array[i])
            ? Val_true : Val_false);
    
    CAMLreturn(flagsVal);
}

static void cf_nameinfo_raise_unresolved
   (int error, int syserror, const char* fname)
{
    CAMLparam0();
    CAMLlocal2(unresolvedVal, resultVal);

    if (!cf_nameinfo_unresolved_exn)
        cf_nameinfo_unresolved_exn =
          caml_named_value("Cf_nameinfo.Unresolved");
    
    if (!cf_nameinfo_unresolved_exn) {
        char message[128];
        sprintf
           (message, "Cf_nameinfo.%s: exception unavailable in primitive",
            fname);
        invalid_argument(message);
    }
            
    if (error == EAI_SYSTEM)
        unix_error(syserror, fname, Nothing);
    
    unresolvedVal = cf_nameinfo_unresolved_of_code(error);
    
    resultVal = alloc_small(2, 0);
    Store_field(resultVal, 0, *cf_nameinfo_unresolved_exn);
    Store_field(resultVal, 1, unresolvedVal);
    caml_raise(resultVal);
    
    CAMLreturn0;
}

/*---
    external of_address:
        ?host:int -> ?serv:int -> ?flags:of_address_flags_t ->
        'a Cf_socket.sockaddr_t -> string * string = "cf_nameinfo_of_address"
  ---*/
CAMLprim value cf_nameinfo_of_address
   (value hostLenVal, value servLenVal, value flagsVal, value sxVal)
{
    CAMLparam4(hostLenVal, servLenVal, flagsVal, sxVal);
    CAMLlocal3(hostNameVal, servNameVal, resultVal);
    
    int error, syserror, flags;
    const Cf_socket_sockaddrx_unit_t* sxPtr;
    size_t ssLen, hostLen, servLen;
    char* hostName;
    char* servName;
        
    hostLen = NI_MAXHOST;
    if (Is_block(hostLenVal)) {
        int n = Int_val(Field(hostLenVal, 0));
        if (n <= 0) INVALID_ARGUMENT("of_address: hostname length");
        hostLen = (size_t) n; 
    }
    
    servLen = NI_MAXSERV;
    if (Is_block(servLenVal)) {
        int n = Int_val(Field(servLenVal, 0));
        if (n <= 0) INVALID_ARGUMENT("of_address: service name length");
        servLen = (size_t) n; 
    }
        
    hostName = malloc(hostLen);
    if (!hostName) unix_error(ENOMEM, "getnameinfo", Nothing);
    
    servName = malloc(servLen);
    if (!servName) {
        free(hostName);
        unix_error(ENOMEM, "getnameinfo", Nothing);
    }

    sxPtr = Cf_socket_sockaddrx_unit_val(sxVal);
    ssLen = sxPtr->sx_socklen;

    flags = 0;
    if (Is_block(flagsVal))
        flags = cf_nameinfo_of_address_flags_to_int(Field(flagsVal, 0));
    
    enter_blocking_section();
    error = getnameinfo((const struct sockaddr*) &sxPtr->sx_sockaddr, ssLen,
        hostName, hostLen, servName, servLen, flags);
    syserror = errno;
    leave_blocking_section();
        
    hostNameVal = copy_string(hostName);
    servNameVal = copy_string(servName);

    free(hostName);
    free(servName);
    
    if (error) cf_nameinfo_raise_unresolved(error, syserror, "getnameinfo");
    
    resultVal = alloc_small(2, 0);
    Store_field(resultVal, 0, hostNameVal);
    Store_field(resultVal, 1, servNameVal);
    
    CAMLreturn(resultVal);
}

/*---
    type to_address_arg_t =
        | A_nodename of string
        | A_servicename of string
        | A_bothnames of string * string
    
    type ('af, 'st) addrinfo = private {
        ai_flags: to_address_flags_t;
        ai_family: 'af Cf_socket.domain_t;
        ai_socktype: 'st Cf_socket.socktype_t;
        ai_protocol: Cf_socket.protocol_t;
        ai_cname: string option;
        ai_addr: 'af Cf_socket.sockaddr_t;
    }
    
    external to_address:
        ('af, 'st) addrinfo -> to_address_arg_t -> ('af, 'st) addrinfo list =
        "cf_nameinfo_to_addresses"
  ---*/
CAMLprim value cf_nameinfo_to_addresses(value hintVal, value argVal)
{
    CAMLparam2(hintVal, argVal);
    CAMLlocal3(listVal, flagsVal, prevVal);
    CAMLlocal4(nextVal, infoVal, familyVal, socktypeVal);
    CAMLlocal4(protocolVal, cnameVal, addrVal, strVal);            
    
    int error, syserror;
    const char* hostname;
    const char* servname;
    struct addrinfo hints;
    struct addrinfo* hintsPtr;
    struct addrinfo* resultPtr;
    
    listVal = Val_int(0);
    
    hostname = 0;
    servname = 0;
    hintsPtr = 0;
    resultPtr = 0;
    
    switch (Tag_val(argVal)) {
      case 0:
        hostname = String_val(Field(argVal, 0));
        break;
    
      case 1:
        servname = String_val(Field(argVal, 0));
        break;
    
      case 2:
        hostname = String_val(Field(argVal, 0));
        servname = String_val(Field(argVal, 1));
        break;
    }
    
    memset(&hints, 0, sizeof hints);
    flagsVal = Field(hintVal, 0);
    if (Bool_val(Field(flagsVal, 0))) hints.ai_flags |= AI_PASSIVE;
    if (Bool_val(Field(flagsVal, 1))) hints.ai_flags |= AI_CANONNAME;
    if (Bool_val(Field(flagsVal, 2))) hints.ai_flags |= AI_NUMERICHOST;
    
    hints.ai_family = Nativeint_val(Field(hintVal, 1));
    hints.ai_socktype = Nativeint_val(Field(hintVal, 2));
    hints.ai_protocol = Nativeint_val(Field(hintVal, 3));

    if (
        hints.ai_family != PF_UNSPEC ||
        hints.ai_socktype != 0 ||
        hints.ai_protocol != 0 ||
        hints.ai_flags
       )
        hintsPtr = &hints;
        
    enter_blocking_section();
    error = getaddrinfo(hostname, servname, hintsPtr, &resultPtr);
    syserror = errno;
    leave_blocking_section();
    
    if (error) cf_nameinfo_raise_unresolved(error, syserror, "getaddrinfo");

    if (resultPtr) {
        const struct addrinfo* p;
        
        prevVal = Val_int(0);
        
        for (p = resultPtr; !!p; p = p->ai_next) {
            Cf_socket_domain_t domain;
            
            flagsVal = cf_nameinfo_default_ai_flags_val;
            if (p->ai_flags) {
                flagsVal = alloc_small(3, 0);
                Store_field(flagsVal, 0, Bool_val(p->ai_flags & AI_PASSIVE));
                Store_field(flagsVal, 1, Bool_val(p->ai_flags & AI_CANONNAME));
                Store_field(flagsVal, 2,
                    Bool_val(p->ai_flags & AI_NUMERICHOST));
            }
            
            domain = cf_nameinfo_pf_unspec;
            domain.d_domain = p->ai_family;
            domain.d_family = p->ai_family;
            
            familyVal = cf_socket_domain_alloc(&domain);
            socktypeVal = copy_nativeint(p->ai_socktype);
            protocolVal = copy_nativeint(p->ai_protocol);
            
            if (!p->ai_canonname) {
                cnameVal = Val_int(0);
            }
            else {                
                strVal = copy_string(p->ai_canonname);
                cnameVal = alloc_small(1, 0);
                Store_field(cnameVal, 0, strVal);
            }
            
            addrVal = cf_nameinfo_sockaddr_cons(p->ai_addr, p->ai_addrlen);
            
            infoVal = alloc_small(6, 0);
            Store_field(infoVal, 0, flagsVal);
            Store_field(infoVal, 1, familyVal);
            Store_field(infoVal, 2, socktypeVal);
            Store_field(infoVal, 3, protocolVal);
            Store_field(infoVal, 4, cnameVal);
            Store_field(infoVal, 5, addrVal);
            
            nextVal = alloc_small(2, 0);
            Store_field(nextVal, 0, infoVal);
            Store_field(nextVal, 1, Val_int(0));
            
            if (!Is_block(listVal))
                listVal = nextVal;
            else
                modify(&Field(prevVal, 1), nextVal);
            
            prevVal = nextVal;
        }
        
        freeaddrinfo(resultPtr);
    }
    
    CAMLreturn(listVal);
}

/*---
  Initialization primitive
  ---*/
CAMLprim value cf_nameinfo_init(value unit)
{
    struct sockaddr_storage ss;
    struct sockaddr* saPtr;
    register_custom_operations(&cf_nameinfo_sockaddr_op);

    register_global_root(&cf_nameinfo_domain_val);
    cf_nameinfo_domain_val =
        cf_socket_domain_alloc(&cf_nameinfo_pf_unspec);

    register_global_root(&cf_nameinfo_socktype_val);
    cf_nameinfo_socktype_val = caml_copy_nativeint(0);

    register_global_root(&cf_nameinfo_protocol_val);
    cf_nameinfo_protocol_val = caml_copy_nativeint(0);
    
    register_global_root(&cf_nameinfo_unspecified_val);
    saPtr = (struct sockaddr*) &ss;
    memset(&ss, 0, sizeof ss);
    cf_nameinfo_unspecified_val =
        cf_nameinfo_pf_unspec.d_consaddr(saPtr, sizeof ss);

    register_global_root(&cf_nameinfo_default_ai_flags_val);
    cf_nameinfo_default_ai_flags_val = alloc_small(3, 0);
    Store_field(cf_nameinfo_default_ai_flags_val, 0, Val_false);
    Store_field(cf_nameinfo_default_ai_flags_val, 1, Val_false);
    Store_field(cf_nameinfo_default_ai_flags_val, 2, Val_false);

    return Val_unit;
}

/*--- End of File [ cf_nameinfo_p.c ] ---*/
