/* 1255, Wed 11 Sep 96

   SNMPTEST.C:  GET/SET MIB variables on an SNMP agent.
            NeTraMet version, based on CMU SNMPv2 (see below).

   Copyright (C) 1992-2002 by Nevil Brownlee,
   CAIDA | University of Auckland */

/*
 * $Log: snmptest.c,v $
 * Revision 1.1.1.2.2.9  2002/02/23 01:57:13  nevil
 * Moving srl examples to examples/ directory.  Modified examples/Makefile.in
 *
 * Revision 1.1.1.2.2.5  2000/08/08 19:44:40  nevil
 * 44b8 release
 *
 * Revision 1.1.1.2.2.3  2000/06/06 03:38:05  nevil
 * Combine NEW_ATR with TCP_ATR, various bug fixes
 *
 * Revision 1.1.1.2  1999/10/03 21:06:04  nevil
 * *** empty log message ***
 *
 * Revision 1.1.1.1.2.3  1999/09/22 05:38:31  nevil
 * Improve code to work properly on 64-bit machines
 * - Add OS=ALPHA handling to configure.in
 * - Clean up the Alpha compiler warnings
 * - Change all the snmp-related code to use Bit32 instead of unsigned long
 *
 * Revision 1.1.1.1.2.2  1999/01/27 04:26:10  nevil
 * Minor corrections to fix compiler warnings
 *
 * Revision 1.1.1.1.2.1  1999/01/08 01:38:15  nevil
 * Distribution file for 4.3b
 *
 * Revision 1.1.1.1  1998/11/16 03:57:26  nevil
 * Import of NeTraMet 4.3b3
 *
 * Revision 1.1.1.1  1998/11/16 03:22:00  nevil
 * Import of release 4.3b3
 *
 * Revision 1.1.1.1.2.1  1998/11/11 23:14:33  nevil
 * Only include malloc.h if we HAVE_MALLOC_H
 *
 * Revision 1.1.1.1  1998/10/28 20:31:22  nevil
 * Import of NeTraMet 4.3b1
 *
 * Revision 1.1.3.2.2.3  1998/10/27 04:39:11  nevil
 * 4.3b1 release
 *
 * Revision 1.1.3.2.2.2  1998/10/22 23:03:21  nevil
 * Provide log_msg() for snmp library, check length of input strings
 */

/***********************************************************************
	Copyright 1988, 1989, 1991, 1992 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.
******************************************************************/

#if HAVE_CONFIG_H
#include <ntm_conf.h>
#endif

#include <sys/types.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include <netdb.h>
#include <errno.h>
#if HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif

#define EXTSNMP
#define INPUTLEN 128

#include "ausnmp.h"

#include "asn1.h"
#include "snmp.h"
#include "snmpimpl.h"
#include "snmpapi.h"
#include "snmpclnt.h"

extern int  errno;
int command = GET_REQ_MSG;
int	snmp_dump_packet = 0;


void usage(void ) {
   fprintf(stderr, "Usage: snmptest -v 1 hostname community\n");
   fprintf(stderr, "or:    snmptest -v 2 hostname community\n\n");
   fprintf(stderr, "$ vbls:  Get, Next, Set, Bulk, Inform, Trap\n");
   fprintf(stderr, "         Q to quit, D to toggle packet dump\n");
   }

void log_msg(int priority, int die, char *fmt, ...)
{
   char msg[100];
   va_list ap;

   va_start(ap, fmt);
   vsprintf(msg, fmt, ap);
   va_end(ap);
   printf("%s\n",msg);

   if (die) exit(die);
   }

void get_string(char *buf, int sz, char *msg)
{
   char *bp;
   printf(msg);  fflush(stdout);
   fgets(buf, sz, stdin);
   /* fgets leaves the trailing \n (gets doesn't) */
   if ((bp = strchr(buf,'\n')) != NULL) *bp = '\0';
   }

int main(int argc, char *argv[])
{
   struct snmp_session session, *ss;
   struct snmp_pdu *pdu, *response, *copy = NULL;
   struct variable_list *vars, *vp;
   int arg, ret, version = 2;
   char *hostname = NULL;
   char *community = NULL;
   int port_flag = 0;
   int dest_port = 0;
   int status, count;
   char input[INPUTLEN];
   int varcount, nonRepeaters = -1, maxRepetitions;
   int timeout_flag = 0, timeout, retransmission_flag = 0, retransmission;
   
   init_mib();

   for (arg = 1; arg < argc; arg++) {
      if (argv[arg][0] == '-') {
	 switch(argv[arg][1]) {
	 case 'd':
	    snmp_dump_packet++;
	    break;
	 case 'm':
	    au_snmp_port = atoi(argv[++arg]);
	    break;
	 case 'p':
	    port_flag++;
	    dest_port = atoi(argv[++arg]);
	    break;
	 case 't':
	    timeout_flag++;
	    timeout = atoi(argv[++arg]) * 1000000L;
	    break;
	 case 'r':
	    retransmission_flag++;
	    retransmission = atoi(argv[++arg]);
	    break;
	 case 'v':
	    version = atoi(argv[++arg]);
	    if (version < 1 || version > 2) {
	       fprintf(stderr, "Invalid version\n");
	       usage();
	       exit(1);
	       }
	    break;
	 default:
	    fprintf(stderr, "invalid option: -%c\n", argv[arg][1]);
	    break;
	    }
	 continue;
	 }
      if (hostname == NULL) {
	 hostname = argv[arg];
	 } 
      else if ((version == 2 || version == 1) && community == NULL) {
	 community = argv[arg]; 
	 }
      else {
	 usage();
	 exit(1);
	 }
      }
   
   if (!hostname || version < 1 || version > 2) {
      usage();
      exit(1);
      }
   
   if (community == NULL)
      community = "public";  /* Default to public */

   memset((char *)&session, 0, sizeof(struct snmp_session));
   session.peername = hostname;
   if (port_flag)
      session.remote_port = dest_port;

   if (version == 1) session.version = SNMP_VERSION_1;
   else session.version = SNMP_VERSION_2C;
   session.community = (u_char *)community;
   session.community_len = strlen((char *)community);

   if (retransmission_flag)
      session.retries = retransmission;
   else
      session.retries = SNMP_DEFAULT_RETRIES;
   if (timeout_flag)
      session.timeout = timeout;
   else
      session.timeout = SNMP_DEFAULT_TIMEOUT;
   session.authenticator = NULL;
   snmp_synch_setup(&session);
   ss = snmp_open(&session);
   if (ss == NULL) {
      fprintf(stderr, "Couldn't open snmp\n");
      exit(-1);
      }
   
   varcount = 0;
   while (1) {
      vars = NULL;
      for (ret = 1; ret != 0;) {
	 vp = (struct variable_list *)malloc(sizeof(struct variable_list));
	 vp->next_variable = NULL;
	 vp->name = NULL;
	 vp->val.string = NULL;

	 while ((ret = input_variable(vp)) == -1)
	    ;
	 if (ret == 1) {
	    varcount++;
	    /* add it to the list */
	    if (vars == NULL) {
	       /* if first variable */
	       pdu = snmp_pdu_create(command);
	       pdu->variables = vp;
	       }
	    else {
	       vars->next_variable = vp;
	       }
	    vars = vp;
	    }
	 else {
	    /* free the last (unused) variable */
	    if (vp->name)
	       free((char *)vp->name);
	    if (vp->val.string)
	       free((char *)vp->val.string);
	    free((char *)vp);

	    if (command == BULK_REQ_MSG) {
	       if (nonRepeaters == -1) {
		  nonRepeaters = varcount;
		  ret = -1;	/* So we collect more variables */
		  printf("Now input the repeating variables\n");
		  }
	       else {
		  get_string(input, sizeof(input),
                     "What repeat count? ");
		  maxRepetitions = atoi(input);
		  pdu->non_repeaters = nonRepeaters;
		  pdu->max_repetitions = maxRepetitions;
		  }
	       }
	    }
	 if (varcount == 0 && ret == 0) {
	    if (!copy) {
	       printf("No PDU to send.\n");
	       ret = -1;
	       }
	    else {
	       pdu = snmp_clone_pdu(copy);
	       printf("Resending last PDU.\n");
	       }
	    }
	 }
      copy = snmp_clone_pdu(pdu);
      if (command == TRP2_REQ_MSG) {
	 /* No response needed */
	 if (!snmp_send(ss, pdu)) {
	    printf("Couldn't send SNMPv2 trap.\n");
	    }
	 }
      else {
	 status = snmp_synch_response(ss, pdu, &response);
	 if (status == STAT_SUCCESS) {
	    if (command == INFORM_REQ_MSG &&
		  response->errstat == SNMP_ERR_NOERROR) {
	       printf("Inform Acknowledged\n");
	       }
	    else {
	       switch(response->command) {
	       case GET_REQ_MSG:
		  printf("Received Get Request ");
		  break;
	       case GETNEXT_REQ_MSG:
		  printf("Received Getnext Request ");
		  break;
	       case GET_RSP_MSG:
		  printf("Received Get Response ");
		  break;
	       case SET_REQ_MSG:
		  printf("Received Set Request ");
		  break;
	       case TRP_REQ_MSG:
		  printf("Received Trap Request ");
		  break;
	       case BULK_REQ_MSG:
		  printf("Received Bulk Request ");
		  break;
	       case INFORM_REQ_MSG:
		  printf("Received Inform Request ");
		  break;
	       case TRP2_REQ_MSG:
		  printf("Received SNMPv2 Trap Request ");
		  break;
		  }
	       printf("from %s\n", inet_ntoa(response->address.sin_addr));
	       printf("requestid 0x%X errstat 0x%X errindex 0x%X\n",
		  response->reqid, response->errstat, response->errindex);
	       if (response->errstat == SNMP_ERR_NOERROR) {
		  for (vars = response->variables; vars;
		        vars = vars->next_variable)
		     print_variable(vars->name, vars->name_length, vars);
		  }
	       else {
		  fprintf(stderr, "Error in packet.\nReason: %s\n",
		     snmp_errstring(response->errstat));
		  if (response->errstat == SNMP_ERR_NOSUCHNAME) {
		     for (count = 1, vars = response->variables;
			   vars && count != response->errindex;
			   vars = vars->next_variable, count++)
			;
		     if (vars) {
			printf("This name doesn't exist: ");
			print_objid(vars->name, vars->name_length);
			}
		     printf("\n");
		     }
		  }
	       }
	    }
	 else if (status == STAT_TIMEOUT) {
	    fprintf(stderr, "No Response from %s\n", hostname);
	    }
	 else {	/* status == STAT_ERROR */
	    fprintf(stderr, "An error occurred, Quitting\n");
	    }
	    
	 if (response)
	    snmp_free_pdu(response);
	 }
      varcount = 0;
      nonRepeaters = -1;
      }
   }

int ascii_to_binary(u_char *cp, u_char *bufp)
{
   int	subidentifier;
   u_char *bp = bufp;

   for (; *cp != '\0'; cp++) {
      if (isspace(*cp))
	 continue;
      if (!isdigit(*cp)) {
	 fprintf(stderr, "Input error\n");
	 return -1;
	 }
      subidentifier = atoi(cp);
      if (subidentifier > 255) {
	 fprintf(stderr, "subidentifier %d is too large ( > 255)\n",
		 subidentifier);
	 return -1;
	 }
      *bp++ = (u_char)subidentifier;
      while (isdigit(*cp))
	 cp++;
      cp--;
      }
   return bp - bufp;
   }


int hex_to_binary(u_char *cp, u_char *bufp)
{
   int	subidentifier;
   u_char *bp = bufp;

   for (; *cp != '\0'; cp++) {
      if (isspace(*cp))
	 continue;
      if (!isxdigit(*cp)) {
	 fprintf(stderr, "Input error\n");
	 return -1;
	 }
      sscanf(cp, "%x", &subidentifier);
      if (subidentifier > 255) {
	 fprintf(stderr, "subidentifier %d is too large ( > 255)\n",
		 subidentifier);
	 return -1;
	 }
      *bp++ = (u_char)subidentifier;
      while (isxdigit(*cp))
	 cp++;
      cp--;
      }
   return bp - bufp;
   }


input_variable(struct variable_list *vp)
{
   char buf[256];
   u_char value[256], ch;
   oid name[MAX_NAME_LEN];

   get_string(buf, sizeof(buf), "Variable: ");
   if (*buf == 0) {
      vp->name_length = 0;
      return 0;
      }
   if (*buf == '$') {
      switch(buf[1]) {
      case 'G':
	 command = GET_REQ_MSG;
	 printf("Request type is Get Request\n");
	 break;
      case 'N':
	 command = GETNEXT_REQ_MSG;
	 printf("Request type is Getnext Request\n");
	 break;
      case 'S':
	 command = SET_REQ_MSG;
	 printf("Request type is Set Request\n");
	 break;
      case 'B':
	 command = BULK_REQ_MSG;
	 printf("Request type is Bulk Request\n");
	 printf("Enter a blank line to terminate the list of non-repeaters\n");
	 printf("and to begin the repeating variables\n");
	 break;
      case 'I':
	 command = INFORM_REQ_MSG;
	 printf("Request type is Inform Request\n");
	 printf("(Are you sending to the right port?)\n");
	 break;
      case 'T':
	 command = TRP2_REQ_MSG;
	 printf("Request type is SNMPv2 Trap Request\n");
	 printf("(Are you sending to the right port?)\n");
	 break;
      case 'D':
	 if (snmp_dump_packet) {
	    snmp_dump_packet = 0;
	    printf("Turned packet dump off\n");
	    }
	 else {
	    snmp_dump_packet = 1;
	    printf("Turned packet dump on\n");
	    }
	 break;
      case 'Q':
	 printf("Quitting,  Goodbye\n");
	 exit(0);
	 break;
      default:
	 fprintf(stderr, "Bad command\n");
	 }
      return -1;
      }
   vp->name_length = MAX_NAME_LEN;
   if (!read_objid(buf, name, &vp->name_length))
      return -1;
   vp->name = (oid *)malloc(vp->name_length * sizeof(oid));
   bcopy((char *)name, (char *)vp->name, vp->name_length * sizeof(oid));

   if (command == SET_REQ_MSG || command == INFORM_REQ_MSG
       || command == TRP2_REQ_MSG) {
      get_string(buf, sizeof(buf), "Type [i|s|x|d|n|o|t|a]: ");
      ch = *buf;
      switch(ch) {
      case 'i':
	 vp->type = INTEGER;
	 break;
      case 's':
	 vp->type = STRING;
	 break;
      case 'x':
	 vp->type = STRING;
	 break;
      case 'd':
	 vp->type = STRING;
	 break;
      case 'n':
	 vp->type = NULLOBJ;
	 break;
      case 'o':
	 vp->type = OBJID;
	 break;
      case 't':
	 vp->type = TIMETICKS;
	 break;
      case 'a':
	 vp->type = IPADDRESS;
	 break;
      default:
	 fprintf(stderr, "bad type \"%c\", use \"i\", \"s\", \"x\", \"d\", \"n\", \"o\", \"t\", or \"a\".\n", *buf);
	 return -1;
	 }
      get_string(buf, sizeof(buf), "Value: "); 
      switch(vp->type) {
      case INTEGER:
	 vp->val.integer = (Int32 *)malloc(sizeof(Int32));
	 *(vp->val.integer) = atoi(buf);
	 vp->val_len = sizeof(Int32);
	 break;
      case STRING:
	 if (ch == 'd') {
	    vp->val_len = ascii_to_binary((u_char *)buf, value);
	    }
	 else if (ch == 's') {
	    strcpy(value, buf);
	    vp->val_len = strlen(buf);
	    }
	 else if (ch == 'x') {
	    vp->val_len = hex_to_binary((u_char *)buf, value);
	    }
	 vp->val.string = (u_char *)malloc(vp->val_len);
	 bcopy((char *)value, (char *)vp->val.string, vp->val_len);
	 break;
      case NULLOBJ:
	 vp->val_len = 0;
	 vp->val.string = NULL;
	 break;
      case OBJID:
	 vp->val_len = MAX_NAME_LEN;;
	 read_objid(buf, (oid *)value, &vp->val_len);
	 vp->val_len *= sizeof(oid);
	 vp->val.objid = (oid *)malloc(vp->val_len);
	 bcopy((char *)value, (char *)vp->val.objid, vp->val_len);
	 break;
      case TIMETICKS:
	 vp->val.u_int = (Bit32 *)malloc(sizeof(Bit32));
	 *(vp->val.u_int) = atoi(buf);
	 vp->val_len = sizeof(Bit32);
	 break;
      case IPADDRESS:
	 vp->val.u_int = (Bit32 *)malloc(sizeof(Bit32));
	 *(vp->val.u_int) = inet_addr(buf);
	 vp->val_len = sizeof(Bit32);
	 break;
      default:
	 fprintf(stderr, "Internal error\n");
	 break;
	 }
      }
   else {			/* some form of get message */
      vp->type = NULLOBJ;
      vp->val_len = 0;
      }
   return 1;
   }

