/*---------------------------------------------------------------------------*
  C MODULE  cf_ip4_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_ip4_proto_p.h"

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

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

static int cf_ip4_proto_sockaddr_compare(value v1, value v2)
{
    CAMLparam2(v1, v2);
    const struct sockaddr_in* sinAddr1Ptr;
    const struct sockaddr_in* sinAddr2Ptr;
    const u_int8_t* addr1Ptr;
    const u_int8_t* addr2Ptr;
    int i, result;
    
    sinAddr1Ptr = &Cf_socket_sockaddrx_val(in, v1)->sx_sockaddr_in;
    sinAddr2Ptr = &Cf_socket_sockaddrx_val(in, v2)->sx_sockaddr_in;
    
    addr1Ptr = (u_int8_t*)(sinAddr1Ptr->sin_addr.s_addr) + 3;
    addr2Ptr = (u_int8_t*)(sinAddr2Ptr->sin_addr.s_addr) + 3;
    
    for (i = 4; i >= 0; --i, --addr1Ptr, --addr2Ptr) {
        result = *addr1Ptr - *addr2Ptr;
        if (result) goto done;
    }
    
    addr1Ptr = (u_int8_t*) &(sinAddr1Ptr->sin_port) + 1;
    addr2Ptr = (u_int8_t*) &(sinAddr2Ptr->sin_port) + 1;
    
    for (i = 2; i >= 0; --i, --addr1Ptr, --addr2Ptr) {
        result = *addr1Ptr - *addr2Ptr;
        if (result) goto done;
    }
    
  done:
    CAMLreturn(result);
}

static long cf_ip4_proto_sockaddr_hash(value sxVal)
{
    CAMLparam1(sxVal);
    const struct sockaddr_in* sinPtr;
    long result;
    
    sinPtr = &Cf_socket_sockaddrx_val(in, sxVal)->sx_sockaddr_in;
    result = (long) ntohl(sinPtr->sin_addr.s_addr);
    result ^= ntohs(sinPtr->sin_port);
    
    CAMLreturn(result);
}

static void cf_ip4_proto_sockaddr_serialize
   (value sxVal, unsigned long* size32Ptr, unsigned long* size64Ptr)
{
    CAMLparam1(sxVal);
    const struct sockaddr_in* sinPtr;
    
    sinPtr = &Cf_socket_sockaddrx_val(in, sxVal)->sx_sockaddr_in;
    serialize_int_4(ntohl(sinPtr->sin_addr.s_addr));
    serialize_int_2(ntohs(sinPtr->sin_port));
    
    *size32Ptr = sizeof *sinPtr;
    *size64Ptr = sizeof *sinPtr;
    
    CAMLreturn0;
}

static unsigned long cf_ip4_proto_sockaddr_deserialize(void* bufferPtr)
{
    struct sockaddr_in* sinPtr;
    
    sinPtr = (struct sockaddr_in*) bufferPtr;
    sinPtr->sin_family = AF_INET;
    sinPtr->sin_addr.s_addr = deserialize_uint_4();
    sinPtr->sin_addr.s_addr = htonl(sinPtr->sin_addr.s_addr);
    sinPtr->sin_port = deserialize_uint_2();
    sinPtr->sin_port = htons(sinPtr->sin_port);
    
    return sizeof *sinPtr;
}

static struct custom_operations cf_ip4_proto_sockaddr_op = {
    "org.conjury.ocnae.cf.sockaddr_in",
    custom_finalize_default,
    cf_ip4_proto_sockaddr_compare,
    cf_ip4_proto_sockaddr_hash,
    cf_ip4_proto_sockaddr_serialize,
    cf_ip4_proto_sockaddr_deserialize
};

value cf_ip4_proto_sockaddr_cons(const struct sockaddr* saPtr, size_t saLen)
{
    value sxVal;
    Cf_socket_sockaddrx_in_t* sxPtr;
    const size_t sxLen =
        offsetof(Cf_socket_sockaddrx_in_t, sx_sockaddr_in) +
        sizeof(struct sockaddr_in);
            
    sxVal = alloc_custom(&cf_ip4_proto_sockaddr_op, sxLen, 0, 1);
    sxPtr = Cf_socket_sockaddrx_val(in, sxVal);
    if (sxPtr) {
        sxPtr->sx_socklen = saLen;
        memcpy(&sxPtr->sx_sockaddr_in, saPtr, saLen);
    }
    
    return sxVal;
}

static value cf_ip4_proto_domain_val = Val_unit;

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

/*---
    external to_sockaddr:
        Cf_ip4_addr.opaque Cf_ip4_addr.t * int ->
        [`AF_INET] Cf_socket.sockaddr_t = "cf_ip4_proto_to_sockaddr"
  ---*/
CAMLprim value cf_ip4_proto_to_sockaddr(value addrVal)
{
    CAMLparam1(addrVal);
    CAMLlocal1(resultVal);
    
    struct sockaddr_in sin;
    int port;
    
    port = Int_val(Field(addrVal, 1));
    if (port < 0 || port > 65535)
        INVALID_ARGUMENT("to_sockaddr: invalid port number");
    
    memset(&sin, 0, sizeof sin);
    sin.sin_family = AF_INET;
    sin.sin_port = htons(port);
    sin.sin_addr = *Cf_ip4_addr_val(Field(addrVal, 0));
    
    resultVal =
        cf_ip4_proto_sockaddr_cons((struct sockaddr*) &sin, sizeof sin);
    CAMLreturn(resultVal);
}

/*---
    external of_sockaddr:
        [`AF_INET] Cf_socket.sockaddr_t ->
        Cf_ip4_addr.opaque Cf_ip4_addr.t * int = "cf_ip4_proto_of_sockaddr"
  ---*/
CAMLprim value cf_ip4_proto_of_sockaddr(value sxVal)
{
    CAMLparam1(sxVal);
    CAMLlocal2(addrVal, resultVal);
    
    const Cf_socket_sockaddrx_in_t* sxPtr;
    const struct sockaddr_in* sinPtr;
    
    sxPtr = Cf_socket_sockaddrx_val(in, sxVal);
    sinPtr = &sxPtr->sx_sockaddr_in;
    addrVal = cf_ip4_addr_alloc(&sinPtr->sin_addr);
    
    resultVal = alloc_small(2, 0);
    Field(resultVal, 0) = addrVal;
    Field(resultVal, 1) = Val_int(ntohs(sinPtr->sin_port));

    CAMLreturn(resultVal);
}

/*---
    external siocgifaddr:
        ([ `AF_INET ], 'st) Cf_socket.t -> string ->
        [> Cf_ip4_addr.unicast ] Cf_ip4_addr.t = "cf_ip4_proto_siocgifaddr"
  ---*/
CAMLprim value cf_ip4_proto_siocgifaddr(value sockVal, value nameVal)
{
    CAMLparam2(sockVal, nameVal);
    CAMLlocal1(resultVal);
    const char* namePtr;
    const Cf_socket_t* sockPtr;
    char buffer[IF_NAMESIZE + sizeof(struct sockaddr_storage)];
    struct ifreq* ifrPtr;
    const struct sockaddr_in* sinPtr;
    int v;
    
    namePtr = String_val(nameVal);
    if (string_length(nameVal) > IF_NAMESIZE || strlen(namePtr) >= IF_NAMESIZE)
        invalid_argument("ioctl[SIOCGIFADDR]: name too long.");
    
    memset(buffer, 0, sizeof buffer);
    ifrPtr = (struct ifreq*) buffer;
    strcpy(ifrPtr->ifr_name, String_val(nameVal));
    sockPtr = Cf_socket_val(sockVal);

    v = ioctl(sockPtr->s_fd, SIOCGIFADDR, buffer);
    if (v == -1) unix_error(errno, "ioctl[SIOCGIFADDR]", Nothing);

    sinPtr = (const struct sockaddr_in*) &ifrPtr->ifr_addr;
    resultVal = cf_ip4_addr_alloc(&sinPtr->sin_addr);
    CAMLreturn(resultVal);
}

value cf_ip4_proto_getsockopt_uchar
   (const Cf_socket_option_context_t* contextPtr)
{
    u_char optval;
    socklen_t optlen;
    
    memset(&optval, 0, sizeof optval);
    optlen = sizeof optval;
    cf_socket_getsockopt_guard(contextPtr, &optval, &optlen);
        
    return Val_int(optval);
}

void cf_ip4_proto_setsockopt_uchar
   (const Cf_socket_option_context_t* contextPtr, value x)
{
    u_char optval;
    int n;
    
    n = Int_val(x);
    if (n < 0 || n > 0xFF)
        invalid_argument("Cf_ip4_proto.setsockopt[uchar]: range error.");
    
    optval = n;
    cf_socket_setsockopt_guard(contextPtr, &optval, sizeof optval);
}

value cf_ip4_proto_getsockopt_addr
   (const Cf_socket_option_context_t* contextPtr)
{
    struct in_addr optval;
    socklen_t optlen;
    
    memset(&optval, 0, sizeof optval);
    optlen = sizeof optval;
    cf_socket_getsockopt_guard(contextPtr, &optval, &optlen);
        
    return cf_ip4_addr_alloc(&optval);
}

void cf_ip4_proto_setsockopt_addr
   (const Cf_socket_option_context_t* contextPtr, value x)
{
    struct in_addr optval;
    
    optval = *Cf_ip4_addr_val(x);
    cf_socket_setsockopt_guard(contextPtr, &optval, sizeof optval);
}

value cf_ip4_proto_getsockopt_mreq
   (const Cf_socket_option_context_t* contextPtr)
{
    CAMLparam0();
    CAMLlocal3(multiaddrVal, interfaceVal, resultVal);
    struct ip_mreq optval;
    socklen_t optlen;
    
    memset(&optval, 0, sizeof optval);
    optlen = sizeof optval;
    cf_socket_getsockopt_guard(contextPtr, &optval, &optlen);

    multiaddrVal = cf_ip4_addr_alloc(&optval.imr_multiaddr);
    interfaceVal = cf_ip4_addr_alloc(&optval.imr_interface);

    resultVal = alloc_small(2, 0);
    Field(resultVal, 0) = multiaddrVal;
    Field(resultVal, 0) = interfaceVal;

    CAMLreturn(resultVal);
}

void cf_ip4_proto_setsockopt_mreq
   (const Cf_socket_option_context_t* contextPtr, value x)
{
    struct ip_mreq optval;
    
    optval.imr_multiaddr = *Cf_ip4_addr_val(Field(x, 0));
    optval.imr_interface = *Cf_ip4_addr_val(Field(x, 1));
    cf_socket_setsockopt_guard(contextPtr, &optval, sizeof optval);
}

/*---
    type sockopt_index_t =
        IP_TTL | IP_ADD_MEMBERSHIP | IP_DROP_MEMBERSHIP | IP_MULTICAST_IF |
        IP_MULTICAST_TTL | IP_MULTICAST_LOOP
  ---*/
static Cf_socket_sockopt_lift_t cf_ip4_proto_sockopt_lift_array[] = {
    { /* IP_TTL */
        Val_unit,
        {
            IPPROTO_IP, IP_TTL,
            cf_socket_getsockopt_int, cf_socket_setsockopt_int
        }
    },

    { /* IP_ADD_MEMBERSHIP */
        Val_unit,
        {
            IPPROTO_IP, IP_ADD_MEMBERSHIP,
            cf_ip4_proto_getsockopt_mreq, cf_ip4_proto_setsockopt_mreq
        }
    },

    { /* IP_DROP_MEMBERSHIP */
        Val_unit,
        {
            IPPROTO_IP, IP_DROP_MEMBERSHIP,
            cf_ip4_proto_getsockopt_mreq, cf_ip4_proto_setsockopt_mreq
        }
    },

    { /* IP_MULTICAST_IF */
        Val_unit,
        {
            IPPROTO_IP, IP_MULTICAST_IF,
            cf_ip4_proto_getsockopt_addr, cf_ip4_proto_setsockopt_addr
        }
    },

    { /* IP_MULTICAST_TTL */
        Val_unit,
        {
            IPPROTO_IP, IP_MULTICAST_TTL,
            cf_ip4_proto_getsockopt_uchar, cf_ip4_proto_setsockopt_uchar
        }
    },

    { /* IP_MULTICAST_LOOP */
        Val_unit,
        {
            IPPROTO_IP, IP_MULTICAST_LOOP,
            cf_ip4_proto_getsockopt_uchar, cf_ip4_proto_setsockopt_uchar
        }
    },
};

#define CF_IP4_PROTO_SOCKOPT_LIFT_ARRAY_SIZE \
    (sizeof cf_ip4_proto_sockopt_lift_array / \
        sizeof cf_ip4_proto_sockopt_lift_array[0])

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

/*---
  Initialization primitive
  ---*/
CAMLprim value cf_ip4_proto_init(value unit)
{
    int i;

    static Cf_socket_domain_t domain = {
        PF_INET, AF_INET, cf_ip4_proto_sockaddr_cons,
        sizeof(struct sockaddr_in)
    };

    register_custom_operations(&cf_ip4_proto_sockaddr_op);
    
    register_global_root(&cf_ip4_proto_domain_val);
    cf_ip4_proto_domain_val = cf_socket_domain_alloc(&domain);

    for (i = 0; i < CF_IP4_PROTO_SOCKOPT_LIFT_ARRAY_SIZE; ++i) {        
        Cf_socket_sockopt_lift_t* liftPtr;
        
        liftPtr = &cf_ip4_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_ip4_proto_p.c ] ---*/
