/*---------------------------------------------------------------------------*
  C MODULE  cf_ip6_proto_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_ip6_proto_p.h"

#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>

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

static int cf_ip6_proto_sockaddr_compare(value v1, value v2)
{
    CAMLparam2(v1, v2);
    const struct sockaddr_in6* sinAddr1Ptr;
    const struct sockaddr_in6* sinAddr2Ptr;
    const u_int8_t* addr1Ptr;
    const u_int8_t* addr2Ptr;
    int i, result;
    
    sinAddr1Ptr = &Cf_socket_sockaddrx_val(in6, v1)->sx_sockaddr_in6;
    sinAddr2Ptr = &Cf_socket_sockaddrx_val(in6, v2)->sx_sockaddr_in6;
    
    result = sinAddr1Ptr->sin6_scope_id - sinAddr2Ptr->sin6_scope_id;
    if (result) goto done;
    
    addr1Ptr = (u_int8_t*)(sinAddr1Ptr->sin6_addr.s6_addr);
    addr2Ptr = (u_int8_t*)(sinAddr2Ptr->sin6_addr.s6_addr);
    
    for (i = 0; i < 16; ++i, ++addr1Ptr, ++addr2Ptr) {
        result = *addr1Ptr - *addr2Ptr;
        if (result) goto done;
    }
        
    addr1Ptr = (u_int8_t*) &(sinAddr1Ptr->sin6_port);
    addr2Ptr = (u_int8_t*) &(sinAddr2Ptr->sin6_port);
    
    for (i = 0; i < 2; ++i, ++addr1Ptr, ++addr2Ptr) {
        result = *addr1Ptr - *addr2Ptr;
        if (result) goto done;
    }
    
  done:
    CAMLreturn(result);
}

static long cf_ip6_proto_sockaddr_hash(value sxVal)
{
    CAMLparam1(sxVal);
    const struct sockaddr_in6* sin6Ptr;
    long result;
    int i;
    unsigned long* p;

    sin6Ptr = &Cf_socket_sockaddrx_val(in6, sxVal)->sx_sockaddr_in6;
    result = ntohs(sin6Ptr->sin6_port);
    p = (unsigned long*) &sin6Ptr->sin6_addr;
    for (i = 0; i < 4; ++i) result ^= ntohl(p[i]);
    result ^= sin6Ptr->sin6_scope_id;
    
    CAMLreturn(result);
}

static void cf_ip6_proto_sockaddr_serialize
   (value sxVal, unsigned long* size32Ptr, unsigned long* size64Ptr)
{
    CAMLparam1(sxVal);
    /* const */ struct sockaddr_in6* sin6Ptr;
    
    sin6Ptr = &Cf_socket_sockaddrx_val(in6, sxVal)->sx_sockaddr_in6;
    serialize_block_1(sin6Ptr->sin6_addr.s6_addr, 16);
    serialize_int_2(ntohs(sin6Ptr->sin6_port));
    serialize_int_4(ntohl(sin6Ptr->sin6_scope_id));
    
    *size32Ptr = sizeof *sin6Ptr;
    *size64Ptr = sizeof *sin6Ptr;
    
    CAMLreturn0;
}

static unsigned long cf_ip6_proto_sockaddr_deserialize(void* bufferPtr)
{
    struct sockaddr_in6* sin6Ptr;
    
    sin6Ptr = (struct sockaddr_in6*) bufferPtr;
    sin6Ptr->sin6_family = AF_INET6;
    deserialize_block_1(sin6Ptr->sin6_addr.s6_addr, 16);
    sin6Ptr->sin6_port = deserialize_uint_2();
    sin6Ptr->sin6_port = htons(sin6Ptr->sin6_port);
    sin6Ptr->sin6_scope_id = deserialize_uint_4();
    sin6Ptr->sin6_scope_id = htonl(sin6Ptr->sin6_scope_id);
    
    return sizeof *sin6Ptr;
}

static struct custom_operations cf_ip6_proto_sockaddr_op = {
    "org.conjury.ocnae.cf.sockaddr_in6",
    custom_finalize_default,
    cf_ip6_proto_sockaddr_compare,
    cf_ip6_proto_sockaddr_hash,
    cf_ip6_proto_sockaddr_serialize,
    cf_ip6_proto_sockaddr_deserialize
};

value cf_ip6_proto_sockaddr_cons(const struct sockaddr* saPtr, size_t saLen)
{
    value sxVal;
    Cf_socket_sockaddrx_in6_t* sxPtr;
    const size_t sxLen =
        offsetof(Cf_socket_sockaddrx_in6_t, sx_sockaddr_in6) +
        sizeof(struct sockaddr_in6);
    
    sxVal = alloc_custom(&cf_ip6_proto_sockaddr_op, sxLen, 0, 1);
    sxPtr = Cf_socket_sockaddrx_val(in6, sxVal);
    if (sxPtr) {
        sxPtr->sx_socklen = saLen;
        memcpy(&sxPtr->sx_sockaddr_in6, saPtr, saLen);
    }
    
    return sxVal;
}

static value cf_ip6_proto_domain_val = Val_unit;

/*---
    external domain_: unit -> 'a Cf_socket.domain_t = "cf_ip6_proto_domain"
  ---*/
CAMLprim value cf_ip6_proto_domain(value unit)
{
    CAMLparam0();
    CAMLreturn(cf_ip6_proto_domain_val);
}

/*---
    external to_sockaddr:
        Cf_ip6_addr.opaque Cf_ip6_addr.t * int * int32 ->
        [`AF_INET6] Cf_socket.sockaddr_t = "cf_ip6_proto_to_sockaddr"
  ---*/
CAMLprim value cf_ip6_proto_to_sockaddr(value addrVal)
{
    CAMLparam1(addrVal);
    CAMLlocal1(resultVal);
    
    struct sockaddr_in6 sin6;
    int port;
    
    port = Int_val(Field(addrVal, 1));
    if (port < 0 || port > 65535)
        INVALID_ARGUMENT("to_sockaddr: invalid port number");
    
    memset(&sin6, 0, sizeof sin6);
    sin6.sin6_family = AF_INET6;
    sin6.sin6_port = htons(port);
    sin6.sin6_addr = *Cf_ip6_addr_val(Field(addrVal, 0));
    sin6.sin6_scope_id = Int32_val(Field(addrVal, 2));
    
    resultVal =
        cf_ip6_proto_sockaddr_cons((struct sockaddr*) &sin6, sizeof sin6);
    CAMLreturn(resultVal);
}

/*---
    external of_sockaddr:
        [`AF_INET6] Cf_socket.sockaddr_t ->
        Cf_ip6_addr.opaque Cf_ip6_addr.t * int * int32
          = "cf_ip6_proto_of_sockaddr"
  ---*/
CAMLprim value cf_ip6_proto_of_sockaddr(value sxVal)
{
    CAMLparam1(sxVal);
    CAMLlocal2(addrVal, resultVal);
    
    const Cf_socket_sockaddrx_in6_t* sxPtr;
    const struct sockaddr_in6* sin6Ptr;
    
    sxPtr = Cf_socket_sockaddrx_val(in6, sxVal);
    sin6Ptr = &sxPtr->sx_sockaddr_in6;
    addrVal = cf_ip6_addr_alloc(&sin6Ptr->sin6_addr);
    
    resultVal = alloc_small(3, 0);
    Store_field(resultVal, 0, addrVal);
    Store_field(resultVal, 1, Val_int(ntohs(sin6Ptr->sin6_port)));
    Store_field(resultVal, 2, copy_int32(sin6Ptr->sin6_scope_id));
    
    CAMLreturn(resultVal);
}

value cf_ip6_proto_getsockopt_mreq
   (const Cf_socket_option_context_t* contextPtr)
{
    CAMLparam0();
    CAMLlocal2(multiaddrVal, resultVal);
    struct ipv6_mreq optval;
    socklen_t optlen;
    
    memset(&optval, 0, sizeof optval);
    optlen = sizeof optval;
    cf_socket_getsockopt_guard(contextPtr, &optval, &optlen);

    multiaddrVal = cf_ip6_addr_alloc(&optval.ipv6mr_multiaddr);

    resultVal = alloc_small(2, 0);
    Store_field(resultVal, 0, multiaddrVal);
    Store_field(resultVal, 1, Val_int(optval.ipv6mr_interface));

    CAMLreturn(resultVal);
}

void cf_ip6_proto_setsockopt_mreq
   (const Cf_socket_option_context_t* contextPtr, value x)
{
    struct ipv6_mreq optval;
    
    optval.ipv6mr_multiaddr = *Cf_ip6_addr_val(Field(x, 0));
    optval.ipv6mr_interface = Int_val(Field(x, 1));
    cf_socket_setsockopt_guard(contextPtr, &optval, sizeof optval);
}

/*---
    type sockopt_index_t =
        IPV6_UNICAST_HOPS | IPV6_V6ONLY | IPV6_JOIN_GROUP | IPV6_LEAVE_GROUP |
        IPV6_MULTICAST_IF | IPV6_MULTICAST_HOPS | IPV6_MULTICAST_LOOP
  ---*/
static Cf_socket_sockopt_lift_t cf_ip6_proto_sockopt_lift_array[] = {
    { /* IPV6_UNICAST_HOPS */
        Val_unit,
        {
            IPPROTO_IPV6, IPV6_UNICAST_HOPS,
            cf_socket_getsockopt_int, cf_socket_setsockopt_int
        }
    },

    { /* IPV6_V6ONLY */
        Val_unit,
        {
            IPPROTO_IPV6, IPV6_V6ONLY,
            cf_socket_getsockopt_bool, cf_socket_setsockopt_bool
        }
    },

    { /* IPV6_JOIN_GROUP */
        Val_unit,
        {
            IPPROTO_IPV6, IPV6_JOIN_GROUP,
            cf_ip6_proto_getsockopt_mreq, cf_ip6_proto_setsockopt_mreq
        }
    },

    { /* IPV6_LEAVE_GROUP */
        Val_unit,
        {
            IPPROTO_IPV6, IPV6_LEAVE_GROUP,
            cf_ip6_proto_getsockopt_mreq, cf_ip6_proto_setsockopt_mreq
        }
    },

    { /* IPV6_MULTICAST_IF */
        Val_unit,
        {
            IPPROTO_IPV6, IPV6_MULTICAST_IF,
            cf_socket_getsockopt_int, cf_socket_setsockopt_int
        }
    },

    { /* IPV6_MULTICAST_HOPS */
        Val_unit,
        {
            IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
            cf_socket_getsockopt_int, cf_socket_setsockopt_int
        }
    },

    { /* IPV6_MULTICAST_LOOP */
        Val_unit,
        {
            IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
            cf_socket_getsockopt_bool, cf_socket_setsockopt_bool
        }
    },
};

#define CF_IP6_PROTO_SOCKOPT_LIFT_ARRAY_SIZE \
    (sizeof cf_ip6_proto_sockopt_lift_array / \
        sizeof cf_ip6_proto_sockopt_lift_array[0])

/*---
    external sockopt_lift:
        sockopt_index_t -> ('a, 'b, 'c) Cf_socket.sockopt_t =
        "cf_ip6_proto_sockopt_lift"
  ---*/
CAMLprim value cf_ip6_proto_sockopt_lift(value indexVal)
{
    CAMLparam1(indexVal);
    CAMLreturn(cf_ip6_proto_sockopt_lift_array[Int_val(indexVal)].ol_val);
}

/*---
  Initialization primitive
  ---*/
CAMLprim value cf_ip6_proto_init(value unit)
{
    int i;
    
    static Cf_socket_domain_t domain = {
        PF_INET6, AF_INET6, cf_ip6_proto_sockaddr_cons,
        sizeof(struct sockaddr_in6)
    };

    register_custom_operations(&cf_ip6_proto_sockaddr_op);
    
    register_global_root(&cf_ip6_proto_domain_val);
    cf_ip6_proto_domain_val = cf_socket_domain_alloc(&domain);

    for (i = 0; i < CF_IP6_PROTO_SOCKOPT_LIFT_ARRAY_SIZE; ++i) {        
        Cf_socket_sockopt_lift_t* liftPtr;
        
        liftPtr = &cf_ip6_proto_sockopt_lift_array[i];
        register_global_root(&liftPtr->ol_val);
        liftPtr->ol_val = cf_socket_option_alloc(&liftPtr->ol_option);
    }

    return Val_unit;
}

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