/*
** pident.c                 Another small test program. 
**
** Compile this program and then link with 
*/

#define USAGE "usage: %s localhost localport remotehost remoteport protocol\n"
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <pwd.h>

#include <sys/types.h>
#include <netinet/in.h>

#ifndef HPUX7
#  include <arpa/inet.h>
#endif

#ifdef HAVE_KVM
#  include <kvm.h>
#else
#  include "kvm.h"
#endif

#include <sys/types.h>
#include <sys/stat.h>

#if defined(MIPS) || defined(BSD43)
extern int errno;
#endif

#include "identd.h"
#include "error.h"

#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <netdb.h>
#include <pwd.h>

int debug_flag   = 0;
int syslog_flag   = 1;
char *path_kmem = NULL;
char *path_unix = NULL;
int lport, fport;

syslog(priority, message)
int priority;
char * message;
{
  printf("%s\n", message);
}

main(argc,argv)
  int argc;
  char *argv[];
{
  int fd;
  struct sockaddr_in laddr, faddr;
  struct in_addr *lsin_addr, *fsin_addr;
  int addrlen;
  int uid;
  struct servent *Servent;
  struct hostent *Hostent;
  struct passwd *pwp;
  
  if (argc != 6)
  {
    printf(USAGE, argv[0]);
    exit(2);
  }

  /*
  ** Open the kernel memory device and read the nlist table
  */
  if (k_open() < 0)
      printf("unable to examine memory\n");
  
  laddr.sin_family = AF_INET;
  if ((laddr.sin_addr.s_addr = inet_addr(argv[1])) == -1) {
    if ((Hostent = gethostbyname(argv[1])) == (struct hostent *)0) {
      perror("gethostbyname");
      exit(2);
    }
    laddr.sin_addr.s_addr =
    inet_addr(inet_ntoa(*(struct in_addr *)(Hostent->h_addr_list[0])));
  }
  lport = atoi(argv[2]);
  if ( lport == 0) {
    if ((Servent = getservbyname(argv[2], argv[5])) == (struct servent *)0) {
      perror("getserverbyname");
      exit(2);
    }
    lport = ntohs(Servent->s_port);
  }

  faddr.sin_family = AF_INET;
  if ((faddr.sin_addr.s_addr = inet_addr(argv[3])) == -1) {
    if ((Hostent = gethostbyname(argv[3])) == (struct hostent *)0) {
      perror("gethostbyname");
      exit(2);
    }
    faddr.sin_addr.s_addr =
    inet_addr(inet_ntoa(*(struct in_addr *)(Hostent->h_addr_list[0])));
  }
  fport = atoi(argv[4]);
  if ( fport == 0) {
    if ((Servent = getservbyname(argv[4], argv[5])) == (struct servent *)0) {
      perror("getserverbyname");
      exit(2);
    }
    fport = ntohs(Servent->s_port);
  }
  
  lsin_addr = &laddr.sin_addr;
  fsin_addr = &faddr.sin_addr;
  if (k_getuid(fsin_addr, htons(fport), 
	       lsin_addr, htons(lport), &uid) != -1) {
  pwp = getpwuid(uid);
  printf("uid = %d (%s)\n",uid, pwp ? pwp->pw_name : "unknown user");
  }
    
  exit(0);
}
