/***********************************************************
	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.
******************************************************************/
/*
 * Copyright (c) 1983,1988 Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms are permitted
 * provided that this notice is preserved and that due credit is given
 * to the University of California at Berkeley. The name of the University
 * may not be used to endorse or promote products derived from this
 * software without specific prior written permission. This software
 * is provided ``as is'' without express or implied warranty.
 */

#include <stdio.h>
#include <strings.h>
#include <ctype.h>

#include <sys/param.h>
#include <sys/socket.h>

#include <netinet/in.h>

#include <netdb.h>
#include "asn1.h"
#include "snmp.h"
#include "snmp_impl.h"
#include "snmp_api.h"
#include "snmp_client.h"
#include "mib.h"

extern	char *routename(), *plural();
extern	char *malloc();
int nflag;


struct acc_entry {
    oid	    instance[8];
    struct in_addr  source, destination;
    int	    set_source, set_destination;
    int	    packets;
    int	    set_packets;
    int	    bytes;
    int	    set_bytes;
};


int     snmp_dump_packet = 0;

#define ACCSRC		1
#define ACCDEST		2
#define ACCPKTS		3
#define ACCBYTS		4
#define ACCCKPT		9
static oid oid_acctable[] = {1, 3, 6, 1, 4, 1, 9, 2, 4, 7};
static oid oid_accsrc[] =   {1, 3, 6, 1, 4, 1, 9, 2, 4, 7, 1, 1};
static oid oid_accdest[] =  {1, 3, 6, 1, 4, 1, 9, 2, 4, 7, 1, 2};
static oid oid_accpkts[] =  {1, 3, 6, 1, 4, 1, 9, 2, 4, 7, 1, 3};
static oid oid_accbyts[] =  {1, 3, 6, 1, 4, 1, 9, 2, 4, 7, 1, 4};

#define TABLE_INDEX        ((sizeof(oid_acctable)/sizeof(oid)) - 1)

/*
 * Print IP accounting tables.
 */
main(argc, argv)
	int argc;
	char *argv[];
{
	struct snmp_session session, *ss;
	struct acc_entry acc, *ap = &acc;
	struct snmp_pdu *request, *response;
	struct variable_list *vp;
	char name[16], *flags, *gateway = NULL, *community = NULL;
	oid *instance, type;
	int toloopback, status, arg, count, heading_done = 0;
	char ch;

	init_mib(); 

	/* gwacc -c -n -d <gw> <community>

	-c	show checkpoint accounting table
	-n	don't convert IP addresses to names
	-d	dump SNMP packets */

	nflag = 0;
	for (arg = 1; arg < argc; arg++){
		if (argv[arg][0] == '-'){

			switch(argv[arg][1]){
			case 'c':
				oid_acctable[TABLE_INDEX] = ACCCKPT;
				oid_accsrc[TABLE_INDEX] = ACCCKPT;
				oid_accdest[TABLE_INDEX] = ACCCKPT;
				oid_accpkts[TABLE_INDEX] = ACCCKPT;
				oid_accbyts[TABLE_INDEX] = ACCCKPT;
				break;
			case 'd':
				snmp_dump_packet++;
				break;
			case 'n':
				nflag++;
				break;
			default:
				printf("invalid option: -%c\n", argv[arg][1]);
				break;
			}
		continue;
        	}

		if (gateway == NULL){
			gateway = argv[arg];
        	} else if (community == NULL){
           		 community = argv[arg]; 
       		} else {
	  		 printf("usage: gwacc [-c|-n|-d] <gw> <community>\n");
			exit(1);
       		}
	}
	
	if (!gateway){
		printf("usage: gwacc [-c|-n|-d] <gw> <community>\n");
		exit(1);
	}

	if (!community) community = "public";

	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;
	snmp_synch_setup(&session);
	ss = snmp_open(&session);
	if (ss == NULL){
		printf("Couldn't open snmp\n");
		exit(-1);
	}

	request = snmp_pdu_create(GETNEXT_REQ_MSG);

	snmp_add_null_var(request, oid_accsrc, sizeof(oid_accsrc)/sizeof(oid));
	snmp_add_null_var(request, oid_accdest, sizeof(oid_accdest)/sizeof(oid));
	snmp_add_null_var(request, oid_accpkts, sizeof(oid_accpkts)/sizeof(oid));
	snmp_add_null_var(request, oid_accbyts, sizeof(oid_accbyts)/sizeof(oid));

	while(request){
	    status = snmp_synch_response(ss, request, &response);
	    if (status != STAT_SUCCESS || response->errstat != SNMP_ERR_NOERROR){
		if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOSUCHNAME) {
			printf("This name does not exist: ");
			for (count=1, vp = response->variables;
			vp && count != response->errindex; vp= vp->next_variable, count++);
				if (vp) print_objid(vp->name, vp->name_length);
			printf("\n");
                }

		fprintf(stderr, "SNMP request failed\n");
		break;
	    }
	    instance = NULL;
	    request = NULL;
	    ap->set_destination = 0;
	    ap->set_source = 0;
	    ap->set_packets = 0;
	    ap->set_bytes = 0;
	    for(vp = response->variables; vp; vp = vp->next_variable){

		if (vp->name_length != 20 ||
		    bcmp((char *)vp->name, (char *)oid_acctable, sizeof(oid_acctable))){
		    continue;	/* if it isn't in this subtree, just continue */
		}

		if (instance != NULL){
		    oid *ip, *op;
		    int count;

		    ip = instance;
		    op = vp->name + 12;
		    for(count = 0; count < 8; count++){
			if (*ip++ != *op++)
			    break;
		    }
		    if (count < 8)
			continue;	/* not the right instance, ignore */
		} else {
		    instance = vp->name + 12;
		}
		/*
		 * At this point, this variable is known to be in the routing table
		 * subtree, and is of the right instance for this transaction.
		 */

		if (request == NULL)
		    request = snmp_pdu_create(GETNEXT_REQ_MSG);
		snmp_add_null_var(request, vp->name, vp->name_length);

		type = vp->name[11];
		switch ((char)type){
		    case ACCDEST:
			bcopy((char *)vp->val.string, (char *)&ap->destination, sizeof(u_long));
			ap->set_destination = 1;
			break;
		    case ACCSRC:
			bcopy((char *)vp->val.string, (char *)&ap->source, sizeof(u_long));
			ap->set_source = 1;
			break;
		    case ACCPKTS:
			ap->packets = *vp->val.integer;
			ap->set_packets = 1;
			break;
		    case ACCBYTS:
			ap->bytes = *vp->val.integer;
			ap->set_bytes = 1;
			break;
		}
	    }

	    if (!(ap->set_destination && ap->set_source
		&& ap->set_packets && ap->set_bytes)){
			if (request) {
		    		snmp_free_pdu(request);
				request = 0;
				continue;
			} else {
				printf("No accounting table or table empty\n");
				break;
			}
		    /* request = 0;
		    continue; */
	    }
	
	    if (!(heading_done)) { 
		printf("%-25.25s %-30.30s  %6s %6s\n",
			"Source", "Destination",
			"Packets", "Bytes");
		heading_done = 1;
	    }

	    printf("%-25.25s ", routename(ap->source));
	    printf("%-30.30s  ", routename(ap->destination));
	    printf("%6d ", ap->packets);
            printf(" %6d\n", ap->bytes);

	}
}

char *routename(in)
	struct in_addr in;
{
	register char *cp;
	static char line[MAXHOSTNAMELEN + 1];
	struct hostent *hp;
	static char domain[MAXHOSTNAMELEN + 1];
	static int first = 1;
	char *index();

	if (first) {
		first = 0;
		if (gethostname(domain, MAXHOSTNAMELEN) == 0 &&
		    (cp = index(domain, '.')))
			(void) strcpy(domain, cp + 1);
		else
			domain[0] = 0;
	}
	cp = 0;
	if (!nflag) {
		hp = gethostbyaddr((char *)&in, sizeof (struct in_addr),
			AF_INET);
		if (hp) {
			if ((cp = index(hp->h_name, '.')) &&
			    !strcmp(cp + 1, domain))
				*cp = 0;
			cp = hp->h_name;
		}
	}
	if (cp)
		strncpy(line, cp, sizeof(line) - 1);
	else {
#define C(x)	((x) & 0xff)
		in.s_addr = ntohl(in.s_addr);
		sprintf(line, "%u.%u.%u.%u", C(in.s_addr >> 24),
			C(in.s_addr >> 16), C(in.s_addr >> 8), C(in.s_addr));
	}
	return (line);
}
