/*
 * ktrap.c - send n sequences of snmp traps to a network entity.
 * Allows to choose the interface from which to send the trap.
 *
 * Based on CMU snmp implementation.
 *
 * Type:
 *      ktrap -h
 * to get help about its usage.
 *
 * Last modified:
 * E. Pasqualucci, 24 Jan. 1997
 *
 */
/******************************************************************
	Copyright 1989 by Carnegie Mellon University

                      All Rights Reserved

Permission to use, copy, modify, and distribute this software and its 
documentation for any purpose and without fee is hereby granted, 
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in 
supporting documentation, and that the name of CMU not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.  

CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
******************************************************************/

/*#define debug*/

/* standard include files */

#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/file.h>

/* snmp include files */

#include "compat.h"
#include "asn1.h"
#include "snmp.h"
#include "snmp_impl.h"
#include "snmp_api.h"
#include "snmp_client.h"

/* specific include file */

#include "utilib_protos.h"
#include "ksnmp.h"
#include "ktrap.h"

/* global variables  */

int snmp_dump_packet = 0;

int nloop = 1;
int ksnmp_trap_port = KSNMP_KLOE_TRAP_PORT;

char default_community_string[] = KSNMP_KLOE_TRAP_COMMUNITY;
char default_subnet_mask[] = KSNMP_KLOE_TRAP_IF;

char *gateway = NULL;
char *community = default_community_string;
char *specific = NULL;
char *description = NULL;
char *agent = NULL;
char *interface = default_subnet_mask;

oid objid_enterprise[] = {1, 3, 6, 1, 4, 1, 3, 1, 1};
oid objid_sysdescr[] = {1, 3, 6, 1, 2, 1, 1, 1, 0};

struct traps *trap_list = (struct traps *) NULL;
struct snmp_session session, *ss;

int ktrap_snmp_input (void)
{
    return;
}

unsigned int ktrap_get_myaddr (void)
{
    int sd;
    struct ifconf ifc;
    struct ifreq conf[NUM_NETWORKS], *ifrp, ifreq;
    struct sockaddr_in *in_addr;
    int count;
    int interfaces;		/* number of interfaces returned by ioctl */
    unsigned int subnet_mask;
    char mask[32];

    strcpy (mask, interface);
    strcat (mask, ".0");

#ifdef debug
    printf ("subnet mask %s\n", mask);
#endif

    subnet_mask = uti_translate_ip_address (mask);

    if ((sd = socket (AF_INET, SOCK_DGRAM, 0)) < 0)
	return 0;

    ifc.ifc_len = sizeof (conf);
    ifc.ifc_buf = (caddr_t) conf;

    if (ioctl(sd, SIOCGIFCONF, (char *) &ifc) < 0)
    {
	close(sd);
	return 0;
    }

    ifrp = ifc.ifc_req;

    interfaces = ifc.ifc_len / sizeof (struct ifreq);

    for (count = 0; count < interfaces; count++, ifrp++)
    {
	ifreq = *ifrp;

	if (ioctl(sd, SIOCGIFFLAGS, (char *)&ifreq) < 0)
	    continue;

	in_addr = (struct sockaddr_in *)&ifrp->ifr_addr;

	if ((ifreq.ifr_flags & IFF_UP)
	    && (ifreq.ifr_flags & IFF_RUNNING)
	    && !(ifreq.ifr_flags & IFF_LOOPBACK)
	    && in_addr->sin_addr.s_addr != LOOPBACK
            && in_addr->sin_family == AF_INET)
                if ((subnet_mask & in_addr->sin_addr.s_addr) ==
                    subnet_mask)
		{
                    close(sd);
#ifdef debug
                    printf (" subnet mask %s\n my address %s\n",
                            uti_translate_ip_address_reverse (&subnet_mask),
                            uti_translate_ip_address_reverse (
                            (unsigned int *) &in_addr->sin_addr.s_addr));
#endif
                    return in_addr->sin_addr.s_addr;
                }
    }

    close(sd);
    return 0;
}

void ktrap_help (void)
{
    printf ("\n Usage :\tktrap -g gateway -t trap_or_traplist [opt]\n");
    printf ("\n Options :\n");
    printf ("\t\t-a agent\n");
    printf ("\t\t-i interface mask (default = %s)\n",
            KSNMP_KLOE_TRAP_IF);
    printf ("\t\t-c community (default = public)\n");
    printf ("\t\t-s specific (default = 0)\n");
    printf ("\t\t-d description\n");
    printf ("\t\t-p port (default = %d)\n", KSNMP_KLOE_TRAP_PORT);
    printf ("\t\t-n nloop (default = 1)\n");
    printf ("\t\t-D (dump packets)\n");
    printf ("\t\t-h (print help)\n");
}

struct traps *ktrap_parse_trap (char *list)
{
    int len;
    int last = 0;
    char *tmp;
    char *pointer;
    char *trap_pointer;
    struct traps *retval = NULL;
    struct traps *tlist = NULL;

    tlist = retval =
            (struct traps *) calloc ((size_t) 1, sizeof (struct traps));

    if ((pointer = strchr (list, ',')) == NULL)
    {
        tlist->trap_type = atoi (list);
        tlist->next_trap = (struct traps *) NULL;
    }
    else
    {
        pointer = list - 1;

        while (!last)
        {
            trap_pointer = ++pointer;

            if ((pointer = strchr (trap_pointer, ',')) == NULL)
	    {
                ++last;
                pointer = strchr (list, '\0');
            }

            len = (int) (pointer - trap_pointer);
            tmp = (char *) calloc ((size_t) len, sizeof (char));
            strncpy (tmp, trap_pointer, len);
            tlist->trap_type = atoi (tmp);
            free (tmp);

            if (last)
                tlist->next_trap = (struct traps *) NULL;
            else
	    {
                tlist->next_trap = (struct traps *) calloc ((size_t) 1,
                                                    sizeof (struct traps));
                tlist = tlist->next_trap;
	    }
        }
    }

    return retval;
}

void ktrap_opt (int n_opt, char **opt)
{
    int i;

    for (i = 1; i < n_opt; i++)
        if (opt[i][0] == '-')
            switch (opt[i][1])
            {
                case 'a':
                    agent = opt[++i];
                    break;
                case 'g':
                    gateway = opt[++i];
                    break;
                case 'i':
                    interface = opt[++i];
                    break;
                case 'c':
                    community = opt[++i];
                    break;
                case 't':
                    trap_list = ktrap_parse_trap (opt[++i]);
                    break;
                case 's':
                    specific = opt[++i];
                    break;
                case 'd':
                    description = opt[++i];
                    break;
                case 'D':
                    ++snmp_dump_packet;
                    break;
                case 'p':
                    ksnmp_trap_port = atoi(opt[++i]);
                    break;
                case 'n':
                    nloop = atoi(opt[++i]);
                    break;
                case 'h':
                    ktrap_help ();
                    exit (0);
                default:
                    printf("invalid option: -%c\n", opt[i][1]);
                    break;
            }

    if (!(gateway && trap_list))
        ktrap_help ();
}

struct snmp_session *ktrap_init_session (void)
{
    struct snmp_session session, *session_pointer;

    bzero((char *)&session, sizeof(struct snmp_session));

    session.peername = gateway;
    session.community = (u_char *)community;
    session.community_len = strlen((char *)community);
    session.retries = SNMP_DEFAULT_RETRIES;
    session.timeout = SNMP_DEFAULT_TIMEOUT;
    session.authenticator = NULL;
    session.callback = ktrap_snmp_input;
    session.callback_magic = NULL;
    session.remote_port = ksnmp_trap_port;

    session_pointer = snmp_open(&session);

    if (session_pointer == NULL)
    {
	printf("Couldn't open snmp\n");
	exit(-1);
    }

    return session_pointer;
}

struct snmp_pdu *ktrap_create_pdu (int trap)
{
    struct snmp_pdu *pdu;
    struct variable_list *vars;

    pdu = snmp_pdu_create(TRP_REQ_MSG);

    pdu->enterprise = (oid *) malloc (sizeof (objid_enterprise));

    bcopy ((char *) objid_enterprise,
           (char *) pdu->enterprise, sizeof (objid_enterprise));

    pdu->enterprise_length = sizeof (objid_enterprise) / sizeof (oid);

    if (agent != NULL)
	pdu->agent_addr.sin_addr.s_addr = uti_address (agent);
    else
	pdu->agent_addr.sin_addr.s_addr = ktrap_get_myaddr ();

    pdu->trap_type = trap;
    pdu->specific_type = specific ? atoi (specific) : 0;
    pdu->time = 0;
    pdu->variables = vars = 
                     (struct variable_list *) malloc (
                                              sizeof (struct variable_list));

    vars->next_variable = NULL;

    vars->name = (oid *) malloc (sizeof (objid_sysdescr));

    bcopy ((char *) objid_sysdescr, (char *) vars->name,
           sizeof (objid_sysdescr));

    vars->name_length = sizeof (objid_sysdescr) / sizeof (oid);
    vars->type = ASN_OCTET_STR;
    vars->val.string = (u_char *) malloc (description ?
                                          strlen (description) + 1 :
                                          strlen ("0"));
    strcpy ((char *) vars->val.string, description ? description : "0");

    vars->val_len = description ? strlen (description) : strlen ("0");

    return pdu;
}

void ktrap_init (void)
{
    struct traps *tlist = trap_list;

    ss = ktrap_init_session ();

    while (tlist)
    {
        tlist->pdu = ktrap_create_pdu (tlist->trap_type);
        tlist = tlist->next_trap;
    }
}

void ktrap_main_loop (void)
{
    register int i;

    for (i=0 ; i < nloop ; ++i)
    {
        struct traps *tlist = trap_list;

        while (tlist)
        {
            if (snmp_send (ss, tlist->pdu) == 0)
                printf("error\n");

            tlist = tlist->next_trap;
        }
    }
}

void ktrap_end (void)
{
    snmp_close (ss);
}

main (int argc, char **argv)
{
    ktrap_opt (argc, argv);
    ktrap_init ();
    ktrap_main_loop ();
    ktrap_end ();
}