/*
 * White Rabbit Switch Management
 * Copyright (C) 2010, CERN.
 *
 * Version:     wrsw_snmpd v1.0
 *
 * Authors:     Juan Luis Manas (juan.manas@integrasys.es)
 *
 * Description: Handles requests for ieee8021QVlanStaticTable table.
 *              Provides support for inserting/deleting static VLAN
 *              entries into the VLAN table
 *              Note: this file originally auto-generated by mib2c using
 *              : mib2c.raw-table.conf 17436 2009-03-31 15:12:19Z dts12 $
 *
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version
 * 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
#include <net-snmp/agent/net-snmp-agent-includes.h>

#include "ieee8021QBridgeVlanStaticTable.h"
#include "rtu_fd_proxy.h"
#include "utils.h"

#define MIBMOD "8021Q"
#define VNAME_LENGTH 32

/* column number definitions for table ieee8021QBridgeVlanStaticTable */
#define COLUMN_IEEE8021QBRIDGEVLANSTATICCOMPONENTID	        1
#define COLUMN_IEEE8021QBRIDGEVLANSTATICVLANINDEX           2
#define COLUMN_IEEE8021QBRIDGEVLANSTATICNAME                3
#define COLUMN_IEEE8021QBRIDGEVLANSTATICEGRESSPORTS         4
#define COLUMN_IEEE8021QBRIDGEVLANFORBIDDENEGRESSPORTS      5
#define COLUMN_IEEE8021QBRIDGEVLANSTATICUNTAGGEDPORTS       6
#define COLUMN_IEEE8021QBRIDGEVLANSTATICROWSTATUS           7


// Row entry
struct mib_static_vlan_table_entry {
    // indexes
    u_long   cid;
    uint16_t vid;

    // Columns
    char vname[VNAME_LENGTH];
    char egress_ports[NUM_PORTS];
    char forbidden_ports[NUM_PORTS];
    char untagged_ports[NUM_PORTS];
    int  row_status;

    netsnmp_request_info *req;                      // associated SNMP request
    struct mib_static_vlan_table_entry *next;
};

/**
 * Stores information related to SET actions that must be handled atomically
 */
static struct mib_static_vlan_table_entry *cache = NULL;

/**
 * Create a new row in the cache table
 */
static struct mib_static_vlan_table_entry *cache_create(u_long cid, u_long vid)
{
    struct mib_static_vlan_table_entry *ent;

    ent = SNMP_MALLOC_TYPEDEF(struct mib_static_vlan_table_entry);
    if (!ent)
        return NULL;

    ent->cid        = cid;
    ent->vid        = vid;
    ent->row_status = RS_NOTINSERVICE;

    memset(ent->vname, 0, VNAME_LENGTH);
    memset(ent->egress_ports, 0, NUM_PORTS);
    memset(ent->forbidden_ports, 0, NUM_PORTS);
    memset(ent->untagged_ports, 0, NUM_PORTS);

    // insert entry in table
    ent->next = cache;
    cache     = ent;
    return ent;
}

/**
 * Determine the appropriate row for an exact request
 */
static struct mib_static_vlan_table_entry *cache_get(int vid)
{
    struct mib_static_vlan_table_entry *ptr;

    for (ptr = cache; ptr; ptr = ptr->next)
        if (ptr->vid == vid)
            return ptr;
    return NULL;
}

/**
 * Remove all entries from cache.
 */
static void cache_clean()
{
    struct mib_static_vlan_table_entry *ptr;

    while(cache) {
        ptr = cache;
        cache = cache->next;
        SNMP_FREE(ptr);
    }
}

/**
 * Get indexes for an entry.
 * @param tinfo table information that contains the indexes (in raw format)
 * @param ent (OUT) used to return the retrieved indexes
 */
static int get_indexes(netsnmp_variable_list               *vb,
                        netsnmp_handler_registration        *reginfo,
                        netsnmp_table_request_info          *tinfo,
                        struct mib_static_vlan_table_entry  *ent)
{
    int oid_len, rootoid_len;
    netsnmp_variable_list *idx;

    // Get indexes from request - in case OID contains them!.
    // Otherwise use default values for first row
    oid_len     = vb->name_length;
    rootoid_len = reginfo->rootoid_len;

    if (oid_len > rootoid_len) {
        if (!tinfo || !tinfo->indexes)
            return SNMP_ERR_GENERR;
        idx = tinfo->indexes;
        ent->cid = *idx->val.integer;
    } else {
        ent->cid = 0;
    }

    if (oid_len > rootoid_len + 1) {
        idx = idx->next_variable;
        ent->vid = *idx->val.integer;
    } else {
        ent->vid = 0;
    }
    return SNMP_ERR_NOERROR;
}

/**
 * @param ent should contain appropriate entry indexes
 */
static int get_column(netsnmp_variable_list                 *vb,
                      int                                   colnum,
                      struct mib_static_vlan_table_entry    *ent)
{
    switch (colnum) {
    case COLUMN_IEEE8021QBRIDGEVLANSTATICNAME:
        snmp_set_var_typed_value(vb, ASN_OCTET_STR, ent->vname, VNAME_LENGTH);
        break;
    case COLUMN_IEEE8021QBRIDGEVLANSTATICEGRESSPORTS:
        snmp_set_var_typed_value(vb, ASN_OCTET_STR, ent->egress_ports,
            NUM_PORTS);
        break;
    case COLUMN_IEEE8021QBRIDGEVLANFORBIDDENEGRESSPORTS:
        snmp_set_var_typed_value(vb, ASN_OCTET_STR, ent->forbidden_ports,
            NUM_PORTS);
        break;
    case COLUMN_IEEE8021QBRIDGEVLANSTATICUNTAGGEDPORTS:
        snmp_set_var_typed_value(vb, ASN_OCTET_STR, ent->untagged_ports,
            NUM_PORTS);
        break;
    default:
        return SNMP_NOSUCHOBJECT;
    }
    return SNMP_ERR_NOERROR;
}

static int get(netsnmp_request_info *req, netsnmp_handler_registration *reginfo)
{
    int err;
    uint32_t ep;    // egress ports
    uint32_t fp;    // forbidden ports
    uint32_t up;    // untagged ports
    struct mib_static_vlan_table_entry ent;
    netsnmp_table_request_info *tinfo = netsnmp_extract_table_info(req);

    // Read indexes from request and insert them into ent
    err = get_indexes(req->requestvb, reginfo, tinfo, &ent);
    if (err)
        return err;

    DEBUGMSGTL((MIBMOD, "get cid=%lu vid=%d column=%d\n",
        ent.cid, ent.vid, tinfo->colnum));
    // Check index range
    if ((ent.cid != DEFAULT_COMPONENT_ID) ||
        (ent.vid >= NUM_VLANS))
        return SNMP_NOSUCHINSTANCE;
    // Read entry from FDB
    errno = 0;
    err = rtu_fdb_proxy_read_static_vlan_entry(ent.vid, &ep, &fp, &up);
    if (errno)
        goto minipc_err;
    if (err)
        goto not_found;

    to_octetstr(ep, ent.egress_ports);
    to_octetstr(fp, ent.forbidden_ports);
    to_octetstr(up, ent.untagged_ports);

    return get_column(req->requestvb, tinfo->colnum, &ent);

not_found:
    DEBUGMSGTL((MIBMOD, "vlan vid=%d not found in static fdb\n", ent.vid));
    return SNMP_NOSUCHINSTANCE;

minipc_err:
    snmp_log(LOG_ERR, "%s(%s): mini-ipc error [%s]\n", __FILE__, __LINE__,
        strerror(errno));
    return SNMP_ERR_GENERR;
}

static int get_next(netsnmp_request_info         *req,
                    netsnmp_handler_registration *reginfo)
{
    int err;
    uint32_t ep;    // egress ports
    uint32_t fp;    // forbidden ports
    uint32_t up;    // untagged ports
    netsnmp_variable_list *idx;
    struct mib_static_vlan_table_entry ent;
    netsnmp_table_request_info *tinfo = netsnmp_extract_table_info(req);

    // Read indexes from request and insert them into ent
    err = get_indexes(req->requestvb, reginfo, tinfo, &ent);
    if (err)
        return err;

    DEBUGMSGTL((MIBMOD, "cid=%d vid=%d column=%d\n",
        ent.cid, ent.vid, tinfo->colnum));
    // Get indexes for next entry
    // SNMP_ENDOFMIBVIEW informs the handler to proceed with next column.
    if (ent.cid > DEFAULT_COMPONENT_ID)
        return SNMP_ENDOFMIBVIEW;
    if (ent.cid == 0) {
        ent.cid = DEFAULT_COMPONENT_ID;
        ent.vid = 0;
#ifdef V2
        // Although use of VID=0 is reserved, it is actually used by HW V2,
        // so we need to check it also.
        errno = 0;
        err = rtu_fdb_proxy_read_static_vlan_entry(ent.vid, &ep, &fp, &up);
        if (errno)
            goto minipc_err;
        if (!err)
            goto update_idx;
#endif // V2
    }
    if (ent.vid >= NUM_VLANS)
        return SNMP_ENDOFMIBVIEW;
    // Read next vlan entry from FDB
    errno = 0;
    err = rtu_fdb_proxy_read_next_static_vlan_entry(&ent.vid, &ep, &fp, &up);
    if (errno)
        goto minipc_err;
    if (err)
        return SNMP_ENDOFMIBVIEW;   // No other entry found

update_idx:
    to_octetstr(ep, ent.egress_ports);
    to_octetstr(fp, ent.forbidden_ports);
    to_octetstr(up, ent.untagged_ports);

    // Update indexes and OID returned in SNMP response
    idx = tinfo->indexes;
    *idx->val.integer = ent.cid;

    idx = idx->next_variable;
    *idx->val.integer = ent.vid;

    update_oid(req, reginfo, tinfo->colnum, tinfo->indexes);
    // Get next entry column value
    return get_column(req->requestvb, tinfo->colnum, &ent);

minipc_err:
    snmp_log(LOG_ERR, "%s(%s): mini-ipc error [%s]\n", __FILE__, __func__,
        strerror(errno));
    return SNMP_ERR_GENERR;
}


/**
 * Checks that the type and size of the value matches the corresponding
 * column type and size.
 */
static int set_reserve1(netsnmp_request_info            *req,
                        netsnmp_handler_registration    *reginfo)
{
    uint32_t ep, fp, up; // aux fields just to read entry from fdb
    struct mib_static_vlan_table_entry ent;

    int err = SNMP_ERR_NOERROR;
    netsnmp_variable_list *vb = req->requestvb;
    netsnmp_table_request_info *tinfo = netsnmp_extract_table_info(req);

    // Check indexes
    err = get_indexes(vb, reginfo, tinfo, &ent);
    if (err)
        return err;

    DEBUGMSGTL((MIBMOD, "cid=%d vid=%d column=%d\n",
        ent.cid, ent.vid, tinfo->colnum));

    if ((ent.cid != DEFAULT_COMPONENT_ID) ||
        (ent.vid >= NUM_VLANS))
        return SNMP_NOSUCHINSTANCE;

    // Check column values
    switch (tinfo->colnum) {
    case COLUMN_IEEE8021QBRIDGEVLANSTATICNAME:
        err = netsnmp_check_vb_type_and_size(vb, ASN_OCTET_STR, VNAME_LENGTH);
        break;
    case COLUMN_IEEE8021QBRIDGEVLANSTATICEGRESSPORTS:
        err = netsnmp_check_vb_type_and_size(vb, ASN_OCTET_STR, NUM_PORTS);
        break;
    case COLUMN_IEEE8021QBRIDGEVLANFORBIDDENEGRESSPORTS:
        err = netsnmp_check_vb_type_and_size(vb, ASN_OCTET_STR, NUM_PORTS);
        break;
    case COLUMN_IEEE8021QBRIDGEVLANSTATICUNTAGGEDPORTS:
        err = netsnmp_check_vb_type_and_size(vb, ASN_OCTET_STR, NUM_PORTS);
        break;
    case COLUMN_IEEE8021QBRIDGEVLANSTATICROWSTATUS:
        // Get current row status and check transition from current to requested
        errno = 0;
        err = rtu_fdb_proxy_read_static_vlan_entry(ent.vid, &ep, &fp, &up);
        if (errno)
            goto minipc_err;
        err = netsnmp_check_vb_rowstatus(vb, err ? RS_NONEXISTENT:RS_ACTIVE);
        break;
    default:
        return SNMP_ERR_NOTWRITABLE;
    }
    return err;

minipc_err:
    snmp_log(LOG_ERR, "%s(%s): mini-ipc error [%s]\n", __FILE__, __func__,
        strerror(errno));
    return SNMP_ERR_GENERR;
}

/**
 * Reserve space in agent memory to hold values until commited
 */
static int set_reserve2(netsnmp_request_info *req)
{
    netsnmp_table_request_info *tinfo = netsnmp_extract_table_info(req);

    switch (tinfo->colnum) {
    case COLUMN_IEEE8021QBRIDGEVLANSTATICROWSTATUS:
        switch (*req->requestvb->val.integer) { //status
        case RS_CREATEANDGO:
        case RS_CREATEANDWAIT:
            if (!cache_create(*tinfo->indexes->val.integer,
                              *tinfo->indexes->next_variable->val.integer))
                return SNMP_ERR_RESOURCEUNAVAILABLE;
        }
    }
    return SNMP_ERR_NOERROR;
}

/**
 * Cache active/notInService FDB entries.
 */
static int set_reserve3(netsnmp_request_info *req)
{
    int i, cid, vid, err;
    uint32_t ep;    // egress ports
    uint32_t fp;    // forbidden ports
    uint32_t up;    // untagged ports
    struct mib_static_vlan_table_entry *ent;

    netsnmp_table_request_info *tinfo = netsnmp_extract_table_info(req);

    // Get indexes for entry
    cid = *tinfo->indexes->val.integer;
    vid = *tinfo->indexes->next_variable->val.integer;

    // If no entry in cache for this vid, it means we are setting fields for
    // ACTIVE or NOTINSERVICE rows, since set_reserve2 creates rows for
    // CREATE_AND_GO and CREATE_AND_WAIT
    ent = cache_get(vid);
    if (!ent) {
        ent = cache_create(cid, vid);
        if (!ent)
            return SNMP_ERR_RESOURCEUNAVAILABLE;

        // Read data from FDB and save it into entry
        errno = 0;
        err = rtu_fdb_proxy_read_static_vlan_entry(vid, &ep, &fp, &up);
        if (errno)
            goto minipc_err;
        if (err)
            goto not_found;

        to_octetstr(ep, ent->egress_ports);
        to_octetstr(fp, ent->forbidden_ports);
        to_octetstr(up, ent->untagged_ports);

        ent->row_status = RS_ACTIVE; // std row status
    }
    return SNMP_ERR_NOERROR;

not_found:
    DEBUGMSGTL((MIBMOD, "vlan vid=%d not found in static fdb\n", ent->vid));
    return SNMP_NOSUCHINSTANCE;

minipc_err:
    snmp_log(LOG_ERR, "%s(%d): mini-ipc error [%s]\n", __FILE__, __LINE__,
        strerror(errno));
    return SNMP_ERR_GENERR;
}

/**
 * Sets value using cached entries in the agent memory.
 */
static int set_action(netsnmp_request_info *req)
{
    int vid;
    struct mib_static_vlan_table_entry *ent;
    netsnmp_variable_list *vb = req->requestvb;
    netsnmp_table_request_info *tinfo = netsnmp_extract_table_info(req);

    // Get indexes
    vid = *tinfo->indexes->next_variable->val.integer;
    // Get entry from cache
    ent = cache_get(vid);
    // Set column value
    switch (tinfo->colnum) {
    case COLUMN_IEEE8021QBRIDGEVLANSTATICNAME:
        memcpy(ent->vname, vb->val.string, vb->val_len);
        break;
    case COLUMN_IEEE8021QBRIDGEVLANSTATICEGRESSPORTS:
        memcpy(ent->egress_ports, vb->val.string, vb->val_len);
        break;
    case COLUMN_IEEE8021QBRIDGEVLANFORBIDDENEGRESSPORTS:
        memcpy(ent->forbidden_ports, vb->val.string, vb->val_len);
        break;
    case COLUMN_IEEE8021QBRIDGEVLANSTATICUNTAGGEDPORTS:
        memcpy(ent->untagged_ports, vb->val.string, vb->val_len);
        break;
    case COLUMN_IEEE8021QBRIDGEVLANSTATICROWSTATUS:
        ent->row_status = *vb->val.integer;
        break;
    }
    // Keep reference to last request for this entry (to return err later on)
    ent->req = req;
    return SNMP_ERR_NOERROR;
}

/**
 * Check consistency of active rows.
 */
static int check_consistency(struct mib_static_vlan_table_entry *ent)
{
    int i;

    switch(ent->row_status) {
    case RS_ACTIVE:
    case RS_CREATEANDGO:
        // Ports can not be egress and forbidden egress at the same time.
        for (i = 0; i < NUM_PORTS; i++) {
            if((ent->egress_ports[i] == 1) && (ent->forbidden_ports[i] == 1)) {
                snmp_log(LOG_ERR,
                    "%s: inconsistent egress port definition - port %d\n",
                    __FILE__, i);
               return SNMP_ERR_INCONSISTENTVALUE;
            }
        }
    }
    return SNMP_ERR_NOERROR;
}

static int set_commit(struct mib_static_vlan_table_entry *ent)
{
    int err;
    uint32_t ep;
    uint32_t fp;
    uint32_t up;

    switch (ent->row_status) {
    case RS_DESTROY:
        DEBUGMSGTL((MIBMOD, "delete vlan vid=%d\n", ent->vid));
        // Remove entry from VLAN table
        errno = 0;
        err = rtu_fdb_proxy_delete_static_vlan_entry(ent->vid);
        if (errno)
            goto minipc_err;
        if (err)
            goto not_deleted;
        break;
    case RS_CREATEANDWAIT:
    case RS_NOTINSERVICE:
        // TODO (requires RTU row status support)
        break;
    case RS_CREATEANDGO:
    case RS_ACTIVE:
        from_octetstr(&ep, ent->egress_ports);
        from_octetstr(&fp, ent->forbidden_ports);
        from_octetstr(&up, ent->untagged_ports);
        // TODO handle the VLAN name
        DEBUGMSGTL((MIBMOD, "create/update vlan vid=%d\n", ent->vid));
        // Create/update entry in VLAN table
        errno = 0;
        err = rtu_fdb_proxy_create_static_vlan_entry(ent->vid, ep, fp, up);
        if (errno)
            goto minipc_err;
        if (err)
            goto not_created;
        break;
    }
    return SNMP_ERR_NOERROR;

not_created:
    snmp_log(LOG_ERR, "%s(%s): create static vlan entry error [%d]\n",
        __FILE__, __func__, err);
    return SNMP_ERR_GENERR;

not_deleted:
    snmp_log(LOG_ERR, "%s(%s): delete vlan vid=%d error [%s]\n",
        __FILE__, __func__, ent->vid, strerror(err));
    return SNMP_ERR_GENERR;

minipc_err:
    snmp_log(LOG_ERR, "%s(%s): mini-ipc error [%s]\n", __FILE__, __func__,
        strerror(errno));
    return SNMP_ERR_GENERR;
}

/**
 * Handles requests for the ieee8021QBridgeVlanStaticTable table
 */
static int _handler(netsnmp_mib_handler          *handler,
                    netsnmp_handler_registration *reginfo,
                    netsnmp_agent_request_info   *reqinfo,
                    netsnmp_request_info         *requests)
{

    int err;
    netsnmp_request_info *req;
    struct mib_static_vlan_table_entry *ent;

    switch (reqinfo->mode) {
    case MODE_GET:
        for (req = requests; req; req = req->next) {
            err = get(req, reginfo);
            if (err)
                netsnmp_set_request_error(reqinfo, req, err);
        }
        break;
    case MODE_GETNEXT:
        for (req = requests; req; req = req->next) {
            err = get_next(req, reginfo);
            if (err)
                netsnmp_set_request_error(reqinfo, req, err);
        }
        break;
    case MODE_SET_RESERVE1:
        for (req =requests; req; req =req->next) {
            err = set_reserve1(req, reginfo);
            if (err)
                netsnmp_set_request_error(reqinfo, req, err);
        }
        break;
    case MODE_SET_RESERVE2:
        for (req = requests; req; req = req->next) {
            err = set_reserve2(req);
            if (err)
                netsnmp_set_request_error(reqinfo, req, err);
        }
        for (req = requests; req; req = req->next) {
            err = set_reserve3(req);
            if (err)
                netsnmp_set_request_error(reqinfo, req, err);
        }
        break;
    case MODE_SET_FREE:
        cache_clean();
        break;
    case MODE_SET_ACTION:
        for (req = requests; req; req = req->next) {
            err = set_action(req);
            if (err)
                netsnmp_set_request_error(reqinfo, req, err);
        }
        for (ent = cache; ent; ent = ent->next) {
            err = check_consistency(ent);
            if (err)
                netsnmp_set_request_error(reqinfo, ent->req, err);
        }
        break;
    case MODE_SET_UNDO:
        cache_clean();
        break;
    case MODE_SET_COMMIT:
        for (ent = cache; ent; ent = ent->next) {
            err = set_commit(ent);
            if (err)
                netsnmp_set_request_error(reqinfo, ent->req, err);
        }
        cache_clean(); // prepare for next atomic set operation
        break;
    }
    return SNMP_ERR_NOERROR;
}

/**
 * Initialize the ieee8021QBridgeVlanStaticTable table by defining its
 * contents and how it's structured
 */
static void initialize_table(void)
{
    const oid _oid[] = {1,3,111,2,802,1,1,4,1,4,3};
    netsnmp_handler_registration    *reg;
    netsnmp_table_registration_info *tinfo;

    reg = netsnmp_create_handler_registration(
            "ieee8021QBridgeVlanStaticTable",
            _handler,
            (oid *)_oid,
            OID_LENGTH(_oid),
            HANDLER_CAN_RWRITE);

    tinfo = SNMP_MALLOC_TYPEDEF( netsnmp_table_registration_info );
    netsnmp_table_helper_add_indexes(
            tinfo,
            ASN_UNSIGNED,  /* index: ComponentId */
            ASN_UNSIGNED,  /* index: VlanIndex */
            0);

    tinfo->min_column = COLUMN_IEEE8021QBRIDGEVLANSTATICNAME;
    tinfo->max_column = COLUMN_IEEE8021QBRIDGEVLANSTATICROWSTATUS;

    netsnmp_register_table(reg, tinfo);
}

/**
 * Initializes the ieee8021QBridgeVlanStaticTable module
 */
void init_ieee8021QBridgeVlanStaticTable(void)
{
    struct minipc_ch *client;

    client = rtu_fdb_proxy_create("rtu_fdb");
    if(client) {
        initialize_table();
        snmp_log(LOG_INFO, "%s: initialised\n", __FILE__);
    } else {
        snmp_log(LOG_ERR, "%s: error creating mini-ipc proxy - %s\n", __FILE__,
            strerror(errno));
    }
}
