#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>

#include "compat.h"
#include "ber.h"
#include "session.h"
#include "argflags.h"

char SNMP_session::need_newline; 
SNMP_session *SNMP_session::lastprint;
pthread_mutex_t SNMP_session::lastprint_m;

#define MAXPACKSIZE 10240

void cpy_hostent(hostent *first,hostent *second){
  first->h_name=strdup(second->h_name);
  first->h_addrtype=second->h_addrtype;
  first->h_length=second->h_length;
  int i;
  for(i=0;second->h_aliases[i]!=NULL;i++);
  assert(first->h_aliases=new char*[i+1]);
  first->h_aliases[i]=NULL;
  for(;second->h_aliases[i] && i>=0;i--)
    first->h_aliases[i]=strdup(second->h_aliases[i]);

  for(i=0;second->h_addr_list[i]!=NULL;i++);
  assert(first->h_addr_list=new char*[i+1]);
  first->h_addr_list[i]=NULL;
  for(--i;i>=0;i--){
    assert(first->h_addr_list[i]=new char[second->h_length]);
    memcpy(first->h_addr_list[i],second->h_addr_list[i],first->h_length);
  }
}

void del_hostent(hostent *dead){
  int i;
  for(i=0;dead->h_aliases[i]!=NULL;i++)
    delete dead->h_aliases[i];
  for(i=0;dead->h_addr_list[i]!=NULL;i++)
    delete dead->h_addr_list[i];
}

SNMP_error_oid::SNMP_error_oid(const char* str){
  oidstr=strdup(str);
}

SNMP_error_oid::~SNMP_error_oid(){
  free(oidstr);
}

int SNMP_error_oid::operator==(CONST char* otherstr){
  return !strcmp(otherstr,oidstr);
}

OidSeq *SNMP_session::do_req(Tags tag, OidSeq *oids){
  if(flags&SESSION_DISABLED_FLAG)
    return NULL;
  /* ------- Construct the packet ------- */
  BerSequence *opacket,*request;
  long int seqno=random(),seq2;
  assert(request=new BerSequence(tag,4,new BerInt(seqno),new BerInt(0L),
				 new BerInt(0L),oids->Seq()));
  assert(opacket=new BerSequence(SEQUENCE_TAG,3,new BerInt(0L),
				 new BerString(community,strlen(community)),
				 request));

  BerEncodedData *opackdat=opacket->encode();

  if(flags&SESSION_DEBUGSNMP_FLAG){
    write_debug("Sent", opacket);
    write_debug_bin(opackdat->Data(),opackdat->Length());
  }

  /* ------- Send the packet ------- */
  fd_set set;
  int i;
  unsigned char *inbuf;

  BerSequence *top,*cur;
  do{
    int buflen=opackdat->Length();
    //    fprintf(stderr,"debug: Going to do call to %s\n",he->h_name);
    while((inbuf=sock->call(he->h_length,he->h_addrtype,he->h_addr_list[ipidx],
			    (char*)opackdat->Data(),buflen))==NULL){
//       fprintf(stderr,"Warning: dropping IP addr %u.%u.%u.%u for %s.\n",
// 	      he->h_addr_list[ipidx][0]&0xff,he->h_addr_list[ipidx][1]&0xff,
// 	      he->h_addr_list[ipidx][2]&0xff,he->h_addr_list[ipidx][3]&0xff,
// 	      hostname);
      ipidx++;
      if(he->h_addr_list[ipidx]==NULL){
	//	fprintf(stderr,"Warning: no more IP addrs for %s.\n",hostname);
	flags|=SESSION_DISABLED_FLAG;
	return NULL;
      }
    }

//     inbuf=sock->call(he->h_length,he->h_addrtype,he->h_addr_list[ipidx],
// 		     (char*)opackdat->Data(),buflen);
//     assert(inbuf);
    top=new BerSequence(inbuf);
    if(flags&SESSION_DEBUGSNMP_FLAG){
      write_debug("Received", top);
      write_debug_bin(inbuf,buflen);
    }
    
    // make sure that this is a response
    cur=(BerSequence*)top->extract(2);
    assert(cur->type()==GET_RESP_TAG);

    /* make sure that this is a response to this request not some
       previous request. What was happening with slow was that I would
       send a packet then it would time out and then I would assume that
       the packet was lost and then I would send another copy. Right
       after that, the reply to the first packet would arrive and so I
       would move on and send another packet. Then the second reply to
       the first packet would arrive and the program would get all
       confused. This could also fix the problem where table lines are
       sometimes repeated over slow links. */
    assert((cur->peek(0)->edatacache->Data())[0]==INT_TAG);
    seq2=((BerInt*)cur->peek(0))->value();
  }while(seq2!=seqno);
  //  printf("Outside the loop.\n");

  // make sure that no errors came back
  unsigned char *dat=cur->peek(1)->edatacache->Data();
  assert(dat[0]==INT_TAG && dat[1]==1); /* if this fails then the device is not
					   sending back a properly constructed
					   packet */ 
  if(dat[2]!=0){
    dat=cur->peek(2)->edatacache->Data();
    assert(dat[0]==INT_TAG && dat[1]==1); /* if this fails something more 
					    sophisticated will have to be 
					    written -- hopefully this will 
					    never fail. */
    delete top;
    top=cur;
    /*cur should now point to the problem oid */
    top=(BerSequence*)top->peek(3);
    top=(BerSequence*)top->peek(dat[2]-1);
    cur=(BerSequence*)top->peek(0);
    char buf[256];
    cur->print(buf,256);
    throw new SNMP_error_oid(buf);
  } 
  delete top;
  top=cur;
  cur=(BerSequence*)top->extract(3);
  delete top;
  //  printf("leaving doreq\n");
  return new OidSeq(cur);
}

SNMP_session::SNMP_session(SNMP_socket *sockp, char *host,const char *comm):
  flags(0),ipidx(0),sock(sockp){
  if(comm)
    community=strdup(comm);
  else
    community=strdup("public");
  hostname=strdup(host);

  hostent *tmp;
  if((tmp=gethostbyname(host))==NULL){
    fprintf(stderr,"SNMP: cannot resolve hostname \"%s\".\n",host);
    exit(-4);
  }
  assert(he=new hostent);
  cpy_hostent(he,tmp);
}

SNMP_session::~SNMP_session(){
  delete community;
  del_hostent(he);
  delete he;
  delete hostname;
}

void SNMP_session::setDebug(){
  flags|=SESSION_DEBUGSNMP_FLAG;      
  int filenum=0;
  char namebuf[20];
  struct stat dummy;
  int retval;

  snprintf(namebuf,19,"snmplog.%d",filenum);
  while((retval=stat(namebuf,&dummy))!=-1){
    filenum++;
    snprintf(namebuf,19,"snmplog.%d",filenum);
  }
  //stat returned a different error than we were expecting.
  assert(errno=ENOENT); 
  
  assert(debugfile=open(namebuf,O_WRONLY|O_CREAT|O_TRUNC,
			S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH));
  char buf[256];
  int buflen=snprintf(buf,256,"Contacting %u.%u.%u.%u\n",
		      ((unsigned)he->h_addr_list[ipidx][0] & 0xff),
		      ((unsigned)he->h_addr_list[ipidx][1] & 0xff),
		      ((unsigned)he->h_addr_list[ipidx][2] & 0xff),
		      ((unsigned)he->h_addr_list[ipidx][3] & 0xff));
  write(debugfile,buf,buflen);
}

void SNMP_session::write_debug(CONST char *dirstr, BerSequence *packet){
  unsigned int sizeleft=MAXPACKSIZE;
  char prntbuf[MAXPACKSIZE];
  char *curpos=prntbuf;
  unsigned int lenused;
  
  lenused=sprintf(prntbuf,"%s\n",dirstr);
  sizeleft-=lenused+1;
  curpos+=lenused;
  
  // overflowed the buffer
  assert((lenused=packet->print(curpos,sizeleft))!=-1); 
  curpos+=lenused;
  sizeleft-=lenused;
  
  assert((lenused=snprintf(curpos,sizeleft,"\n"))!=-1);
  sizeleft-=lenused;
  curpos+=lenused;
  
  sizeleft=curpos-prntbuf; // reusing a variable
  assert(sizeleft==write(debugfile,prntbuf,sizeleft));

}

// write the binary version of the packet
void SNMP_session::write_debug_bin(unsigned char *data, unsigned len){
  unsigned int sizeleft=MAXPACKSIZE;
  char prntbuf[MAXPACKSIZE];
  char *curpos=prntbuf;
  unsigned int lenused;

  for( unsigned idx=0; idx<len; idx++){
    assert((lenused=snprintf(curpos,sizeleft,"%02x ",data[idx]))!=-1);
    sizeleft-=lenused;
    curpos+=lenused;
    if(idx>0 && (idx+1)%16==0){
      assert((lenused=snprintf(curpos,sizeleft,"\n"))!=-1);
      sizeleft-=lenused;
      curpos+=lenused;
    }
  }
  assert((lenused=snprintf(curpos,sizeleft,"\n"))!=-1);
  sizeleft-=lenused;
  curpos+=lenused;

  sizeleft=curpos-prntbuf; // reusing a variable
  assert(sizeleft==write(debugfile,prntbuf,sizeleft));  
}

void SNMP_session::printstr(unsigned long *argflags,char neednl,char *str){
  static char *basestr[]={"%s%s","\n%s%s","hostname=\"%s\";%s",
			  "\nhostname=\"%s\";%s"};
  char *hn="";
  char idx=0;
  pthread_mutex_lock(&lastprint_m);
  if(lastprint!=this){
    if(need_newline)
      idx=1;
    if(CK_NAME_FLAG){
      idx|=2;
      hn=hostname;
    }
  }else{
    if(!neednl && CK_NAME_FLAG){
      idx|=2;
      hn=hostname;
    }
    if(need_newline && !neednl){
      idx=1;
    } 
  }
  need_newline=neednl;
  lastprint=this;
  pthread_mutex_unlock(&lastprint_m);

  printf(basestr[idx],hn,str);
}

void SNMP_session::end(){
  pthread_mutex_lock(&lastprint_m);
  if(need_newline)
    printf("\n");
  pthread_mutex_unlock(&lastprint_m);
}


syntax highlighted by Code2HTML, v. 0.9.1