/*
 * This file provides functions needed from the NET-SNMP package
 * which are otherwise requiring full NET-SNMP libraries to
 * be added to products which need SNMP.
 * $Id: net-snmp.c 8676 2008-01-17 23:11:17Z ispringer $
 */
/* Includes */
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>

/* NET-SNMP includes */
#include <ucd-snmp-config.h>
#include <asn1.h>
#include <snmp_api.h>

/*
 * This function is taken from net-snmp/snmplib/snmp_api.c
 *
 * lexicographical compare two object identifiers.
 * Returns -1 if name1 < name2,
 *          0 if name1 = name2,
 *          1 if name1 > name2
 *
 * Caution: this method is called often by
 *          command responder applications (ie, agent).
 */
int
snmp_oid_compare(const oid *in_name1, size_t len1,
                 const oid *in_name2, size_t len2)
{
    register int len, res;
    register const oid * name1 = in_name1;
    register const oid * name2 = in_name2;

    /* len = minimum of len1 and len2 */
    if (len1 < len2)
        len = len1;
    else
        len = len2;
    /* find first non-matching OID */
    while(len-- > 0){
        res = *(name1++) - *(name2++);
        if (res < 0)
            return -1;
        if (res > 0)
            return 1;
    }
    /* both OIDs equal up to length of shorter OID */
    if (len1 < len2)
        return -1;
    if (len2 < len1)
        return 1;
    return 0;
}

/*
 * This function is copied from net-snmp/snmplib/snmp_client.c
 *
 * Add some value to SNMP variable.
 * If the value is large, additional memory is allocated.
 * Returns 0 if successful.
 */
int
snmp_set_var_value(struct variable_list *newvar,
                    u_char *val_str, size_t val_len)
{
    if (newvar->val.string && newvar->val.string != newvar->buf) {
        free(newvar->val.string);
    }
    newvar->val.string = 0; newvar->val_len = 0;
    /* need a pointer and a length to copy a string value. */
    if (val_str && val_len) {
        if (val_len <= sizeof(newvar->buf)) {
            newvar->val.string = newvar->buf;
        } else {
            newvar->val.string = (u_char *)malloc(val_len);
            if (!newvar->val.string) return 1;
        }
        memmove(newvar->val.string, val_str, val_len);
        newvar->val_len = val_len;
    }
    return 0;
}

/*
 * This function is copied from net-snmp/snmplib/snmp_client.c
 *
 * Add object identifier name to SNMP variable.
 * If the name is large, additional memory is allocated.
 * Returns 0 if successful.
 */
int
snmp_set_var_objid (struct variable_list *vp, const oid *objid, size_t name_length)
{
    size_t len = sizeof(oid) * name_length;
    
    /* use built-in storage for smaller values */
    if (len <= sizeof(vp->name_loc)) {
        vp->name = vp->name_loc;
    } else {
        vp->name = (oid *)malloc(len);
        if (!vp->name) return 1;
    }
    memmove(vp->name, objid, len);
    vp->name_length = name_length;
    return 0;
}

