/* 1435, Wed 3 Jun 98

   SNMPCLNT.C:  SNMP utility routines for building SNMP clients
            NeTraMet version, based on CMU SNMPv2 (see below).

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

/*
 * $Log: snmpclnt.c,v $
 * Revision 1.1.1.2.2.7  2002/02/23 01:57:40  nevil
 * Moving srl examples to examples/ directory.  Modified examples/Makefile.in
 *
 * Revision 1.1.1.2.2.3  2000/06/06 03:38:31  nevil
 * Combine NEW_ATR with TCP_ATR, various bug fixes
 *
 * Revision 1.1.1.2  1999/10/03 21:06:32  nevil
 * *** empty log message ***
 *
 * Revision 1.1.1.1.2.1  1999/01/08 01:38:39  nevil
 * Distribution file for 4.3b7
 *
 * Revision 1.1.1.1  1998/11/16 03:57:32  nevil
 * Import of NeTraMet 4.3b3
 *
 * Revision 1.1.1.1  1998/11/16 03:22:02  nevil
 * Import of release 4.3b3
 *
 * Revision 1.1.1.1  1998/10/28 20:31:32  nevil
 * Import of NeTraMet 4.3b1
 *
 * Revision 1.1.3.1.2.2  1998/10/22 01:28:10  nevil
 * Community data wasn't being copied when PDUs were cloned, which gave
 * unpredictable results when the cloned pdu was freed.  Added code to
 * copy community data properly.  Also added PDU_MALLOC_CHECK define
 * to trace malloc() and Free() operations on pdus.
 *
 * Revision 1.1.3.1.2.1  1998/10/19 02:30:41  nevil
 * Use log_msg() to report errors instead of fprintf(stderr ..)
 *
 * Revision 1.1.3.1  1998/10/13 02:48:59  nevil
 * Import of Nicolai's 4.2.2
 *
 * Revision 1.1.1.1  1998/08/24 12:09:30  nguba
 * NetraMet 4.2 Original Distribution
 *
 * Revision 1.3  1998/06/03 04:42:38  rtfm
 * Add debugging for select timeouts
 */

/**********************************************************************
	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

#define TEST_TIMEOUTS  0
#define PDU_MALLOC_CHECK  0

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#ifdef DOS
#include <time.h>
#include <bios.h>
#include <mem.h>
#include "tcp.h"
#endif

#ifndef DOS
#include <sys/param.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <sys/socket.h>
#if HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#include <netdb.h>
#endif

#include "ausnmp.h"

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

#if defined(DOS) || defined(CYGWIN32)
#define	timerisset(tvp)		((tvp)->tv_sec || (tvp)->tv_usec)
#define	timercmp(tvp, uvp, cmp)	\
	((tvp)->tv_sec cmp (uvp)->tv_sec || \
	 (tvp)->tv_sec == (uvp)->tv_sec && (tvp)->tv_usec cmp (uvp)->tv_usec)
#define	timerclear(tvp)		(tvp)->tv_sec = (tvp)->tv_usec = 0
#endif

#if PDU_MALLOC_CHECK
extern char mc_buf[64];
#endif

extern int errno;
struct synch_state snmp_synch_state;

struct snmp_pdu *snmp_pdu_create(int command)
{
   struct snmp_pdu *pdu;

   pdu = (struct snmp_pdu *)malloc(sizeof(struct snmp_pdu));
   memset((char *)pdu, 0, sizeof(struct snmp_pdu));
#if PDU_MALLOC_CHECK
   printf("clnt:pdu_create(): pdu=%lu, pdu[null]\n",
      pdu);
#endif
   pdu->version = SNMP_DEFAULT_VERSION;
   pdu->community_len = 0;
   pdu->command = command;
   pdu->errstat = SNMP_DEFAULT_ERRSTAT;
   pdu->errindex = SNMP_DEFAULT_ERRINDEX;
#ifdef DOS
   pdu->address.s_ip = SNMP_DEFAULT_ADDRESS;
#else
   pdu->address.sin_addr.s_addr = SNMP_DEFAULT_ADDRESS;
#endif
   pdu->enterprise = NULL;
   pdu->enterprise_length = 0;
   pdu->variables = NULL;
   return pdu;
   }

/*
 * Add a null variable with the requested name to the end of the list
 * of variables for this pdu.
 */
void snmp_add_null_var(struct snmp_pdu *pdu,
   oid *name, int name_length)
{
   struct variable_list *vars;

   if (pdu->variables == NULL) {
      pdu->variables = vars =
         (struct variable_list *)malloc(sizeof(struct variable_list));
      }
   else {
      for (vars = pdu->variables; vars->next_variable;
            vars = vars->next_variable)
         ;  /* EXIT */
      vars->next_variable =
         (struct variable_list *)malloc(sizeof(struct variable_list));
      vars = vars->next_variable;
      }

   vars->next_variable = NULL;
   vars->name = (oid *)malloc(name_length * sizeof(oid));
   memcpy((char *)vars->name, (char *)name, name_length * sizeof(oid));
   vars->name_length = name_length;
   vars->type = ASN_NULL;
   vars->val.string = NULL;
   vars->val_len = 0;
   }

int snmp_synch_input(
   int op,
   struct snmp_session *session,
   int reqid,
   struct snmp_pdu *pdu,
   void *magic)
{
   struct variable_list *var, *newvar;
   struct synch_state *state = (struct synch_state *)magic;
   struct snmp_pdu *newpdu;

   if (reqid != state->reqid)
      return 0;
   state->waiting = 0;
   if (op == RECEIVED_MESSAGE && pdu->command == GET_RSP_MSG) {
      /* Clone the pdu */
      state->pdu = newpdu =
         (struct snmp_pdu *)malloc(sizeof(struct snmp_pdu));
      memcpy((char *)newpdu, (char *)pdu, sizeof(struct snmp_pdu));
      if (pdu->community_len != 0) {
         newpdu->community = (u_char *)malloc(pdu->community_len);
         memcpy(newpdu->community, pdu->community, pdu->community_len);
         }
#if PDU_MALLOC_CHECK
      memcpy(mc_buf, newpdu->community, newpdu->community_len);
      mc_buf[newpdu->community_len] = '\0';
      printf("clnt:synch_input(): newpdu=%lu, community=%lu, newpdu[%s]\n",
         newpdu, newpdu->community, mc_buf);
#endif
      newpdu->variables = 0;
      var = pdu->variables;
      if (var != NULL) {
	 newpdu->variables = newvar =
            (struct variable_list *)malloc(sizeof(struct variable_list));
	 memcpy((char *)newvar, (char *)var, sizeof(struct variable_list));
	 if (var->name != NULL) {
	    newvar->name = (oid *)malloc(var->name_length * sizeof(oid));
	    memcpy((char *)newvar->name, (char *)var->name,
               var->name_length * sizeof(oid));
	    }
	 if (var->val.string != NULL) {
	    newvar->val.string = (u_char *)malloc(var->val_len);
	    memcpy((char *)newvar->val.string,
               (char *)var->val.string, var->val_len);
	    }
	 newvar->next_variable = 0;
	 while (var->next_variable) {
	    newvar->next_variable =
               (struct variable_list *)malloc(sizeof(struct variable_list));
	    var = var->next_variable;
	    newvar = newvar->next_variable;
	    memcpy((char *)newvar, (char *)var,
               sizeof(struct variable_list));
	    if (var->name != NULL) {
	       newvar->name = (oid *)malloc(var->name_length * sizeof(oid));
	       memcpy((char *)newvar->name,
                  (char *)var->name, var->name_length * sizeof(oid));
	       }
	    if (var->val.string != NULL) {
	       newvar->val.string = (u_char *)malloc(var->val_len);
	       memcpy((char *)newvar->val.string,
                  (char *)var->val.string, var->val_len);
	       }
	    newvar->next_variable = 0;
	    }
         }
      state->status = STAT_SUCCESS;
      }
   else if (op == TIMED_OUT) {
      state->pdu = NULL;
      state->status = STAT_TIMEOUT;
      }
   return 1;
   }


/*
 * If there was an error in the input pdu, creates a clone of the pdu
 * that includes all the variables except the one marked by the
 * errindex.  The command is set to the input command and the reqid,
 * errstat, and errindex are set to default values.  If the error
 * status didn't indicate an error, the error index didn't indicate a
 * variable, the pdu wasn't a get response message, or there would be
 * no remaining variables, this function will return NULL.  If
 * everything was successful, a pointer to the fixed cloned pdu will
 * be returned.
 */
struct snmp_pdu *snmp_fix_pdu(
   struct snmp_pdu *pdu,
   int command)
{
   struct variable_list *var, *newvar;
   struct snmp_pdu *newpdu;
   int index, copied = 0;

   if (pdu->command != GET_RSP_MSG ||
         pdu->errstat == SNMP_ERR_NOERROR || pdu->errindex <= 0)
      return NULL;
   /* Clone the pdu */
   newpdu = (struct snmp_pdu *)malloc(sizeof(struct snmp_pdu));
   memcpy((char *)newpdu, (char *)pdu, sizeof(struct snmp_pdu));
   newpdu->variables = 0;
   newpdu->command = command;
   newpdu->reqid = SNMP_DEFAULT_REQID;
   newpdu->errstat = SNMP_DEFAULT_ERRSTAT;
   newpdu->errindex = SNMP_DEFAULT_ERRINDEX;
   if (pdu->community_len != 0) {
      newpdu->community = (u_char *)malloc(pdu->community_len);
      memcpy(newpdu->community, pdu->community, pdu->community_len);
      }
   var = pdu->variables;
   index = 1;
   if (pdu->errindex == index) {  /* Skip first variable */
      var = var->next_variable;
      index++;
      }
   if (var != NULL) {
      newpdu->variables = newvar =
         (struct variable_list *)malloc(sizeof(struct variable_list));
      memcpy((char *)newvar, (char *)var, sizeof(struct variable_list));
      if (var->name != NULL) {
         newvar->name = (oid *)malloc(var->name_length * sizeof(oid));
	 memcpy((char *)newvar->name, (char *)var->name,
            var->name_length * sizeof(oid));
	 }
      if (var->val.string != NULL) {
	 newvar->val.string = (u_char *)malloc(var->val_len);
	 memcpy((char *)newvar->val.string,
            (char *)var->val.string, var->val_len);
	 }
      newvar->next_variable = 0;
      copied++;

      while (var->next_variable) {
	 var = var->next_variable;
	 if (++index == pdu->errindex)
	    continue;
	 newvar->next_variable =
            (struct variable_list *)malloc(sizeof(struct variable_list));
	 newvar = newvar->next_variable;
	 memcpy((char *)newvar,
            (char *)var, sizeof(struct variable_list));
	 if (var->name != NULL) {
	    newvar->name = (oid *)malloc(var->name_length * sizeof(oid));
	    memcpy((char *)newvar->name,
               (char *)var->name, var->name_length * sizeof(oid));
	    }
	 if (var->val.string != NULL) {
	    newvar->val.string = (u_char *)malloc(var->val_len);
	    memcpy((char *)newvar->val.string,
               (char *)var->val.string, var->val_len);
	    }
	 newvar->next_variable = 0;
	 copied++;
	 }
      }
   if (index < pdu->errindex || copied == 0) {
      snmp_free_pdu(newpdu);
      return NULL;
      }
   return newpdu;
   }


/*
 * Creates (allocates and copies) a clone of the input PDU.
 */
struct snmp_pdu *snmp_clone_pdu(struct snmp_pdu *pdu)
{
   struct variable_list *var, *newvar;
   struct snmp_pdu *newpdu;

   /* Clone the pdu */
   newpdu = (struct snmp_pdu *)malloc(sizeof(struct snmp_pdu));
   memcpy((char *)newpdu, (char *)pdu, sizeof(struct snmp_pdu));
   if (pdu->community_len != 0) {
      newpdu->community = (u_char *)malloc(pdu->community_len);
      memcpy(newpdu->community, pdu->community, pdu->community_len);
      }
   newpdu->variables = 0;
   var = pdu->variables;
   if (var != NULL) {
      newpdu->variables = newvar =
         (struct variable_list *)malloc(sizeof(struct variable_list));
      memcpy((char *)newvar, (char *)var, sizeof(struct variable_list));
	 if (var->name != NULL) {
	    newvar->name = (oid *)malloc(var->name_length * sizeof(oid));
	    memcpy((char *)newvar->name, (char *)var->name,
	       var->name_length * sizeof(oid));
	    }
	 if (var->val.string != NULL) {
	    newvar->val.string = (u_char *)malloc(var->val_len);
	    memcpy((char *)newvar->val.string, (char *)var->val.string,
		  var->val_len);
	 }
      newvar->next_variable = 0;

      while (var->next_variable) {
	 var = var->next_variable;
	 newvar->next_variable =
	    (struct variable_list *)malloc(sizeof(struct variable_list));
	 newvar = newvar->next_variable;
	 memcpy((char *)newvar, (char *)var, sizeof(struct variable_list));
	 if (var->name != NULL) {
	    newvar->name = (oid *)malloc(var->name_length * sizeof(oid));
	    memcpy((char *)newvar->name, (char *)var->name,
	       var->name_length * sizeof(oid));
	    }
	 if (var->val.string != NULL) {
	    newvar->val.string = (u_char *)malloc(var->val_len);
	    memcpy((char *)newvar->val.string, (char *)var->val.string,
	       var->val_len);
	    }
	 newvar->next_variable = 0;
	 }
      }
   return newpdu;
   }


int snmp_synch_response(
   struct snmp_session *ss,
   struct snmp_pdu *pdu,
   struct snmp_pdu **response)
{
   struct synch_state *state = &snmp_synch_state;
   int numfds, count;
   fd_set fdset;
   struct timeval timeout, *tvp;
   int block;
#ifdef DOS
   struct timeval *now;
   int timed_out;
#endif

#if PDU_MALLOC_CHECK
   memcpy(mc_buf, ss->community, ss->community_len);
   mc_buf[ss->community_len] = '\0';
   printf("clnt:synch_response(): ss=%lu, pdu=%lu, ss[%s]\n",
      ss, pdu, mc_buf);
#endif
   if ((state->reqid = snmp_send(ss, pdu)) == 0) {
      *response = NULL;
      snmp_free_pdu(pdu);
      return STAT_ERROR;
      }
   state->waiting = 1;
#ifdef DOS
   now = (struct timeval *)malloc(sizeof(struct timeval));
#endif

   while (state->waiting) {
      numfds = 0;
      FD_ZERO(&fdset);
      block = 1;
      tvp = &timeout;
      timerclear(tvp);
      snmp_select_info(&numfds, &fdset, tvp, &block);
#if TEST_TIMEOUTS
      printf(
         " *** sync_response(1): numfds=%d, tvp=%lu, block=%d\n",
         numfds,tvp,block);
#endif
      if (block == 1)
	 tvp = NULL;	/* block without timeout */
#ifdef DOS
      gettimeofday(now,(struct timezone *)0);
      tvp->tv_sec += now->tv_sec;
      timed_out = 0;
      do {
	 tcp_tick(NULL);
	 snmp_read(&fdset);
	 if (!state->waiting) break;
	 gettimeofday(now,(struct timezone *)0);
	 timed_out = timercmp(now,tvp,>);
         } while (!timed_out);
      if (timed_out) snmp_timeout();
#else
      count = select(numfds, &fdset, 0, 0, tvp);
#if TEST_TIMEOUTS
      printf(
         " *** sync_response(2): count=%d, numfds=%d, tvp=%lu, *tvp=(%lu,%lu)\n", 
         count,numfds,tvp, tvp->tv_sec,tvp->tv_usec);
#endif
      if (count > 0) {
	 snmp_read(&fdset);
	 }
      else switch(count) {
      case 0:
	 snmp_timeout();
	 break;
      case -1:
	 if (errno == EINTR) {
	    continue;
	    }
	 else {
	    perror("select");
	    }
	    /* FALLTHRU */
         default:
	   *response = NULL;
	   return STAT_ERROR;
           }
#endif
      }
   *response = state->pdu;
   return state->status;
   }

void snmp_synch_setup(struct snmp_session *session)
{
   session->callback = &snmp_synch_input;
   session->callback_magic = (void *)&snmp_synch_state;
   }

char *error_string[18] = {
   "No Error",
   "Response message would have been too large.",
   "There is no such variable name in this MIB.",
   "The value given has the wrong type or length.",
   "The two parties used do not have access to use the specified SNMP PDU.",
   "A general failure occured",
   "noAccess",
   "wrongType",
   "wrongLength",
   "wrongEncoding",
   "wrongValue",
   "noCreation",
   "inconsistentValue",
   "resourceUnavailable",
   "commitFailed",
   "undoFailed",
   "authorizationError",
   "notWritable"
   };

char *snmp_errstring(int errstat)
{
   if (errstat <= SNMP_ERR_NOTWRITABLE && errstat >= SNMP_ERR_NOERROR) {
      return error_string[errstat];
      }
   else {
      return "Unknown Error";
      }
   }
