#include <stdio.h>
#include <fcntl.h>

#define HOSTS "/etc/tsh.hosts"
#define TELNET "/usr/bin/telnet"
#define MAXHOSTSSIZE 4096
#define MAXHOSTLENGTH 32
#define LCCTYPE "LC_CTYPE=iso_8859_1"

extern char **environ;

char **readhosts(void)
{
  char tmp[MAXHOSTSSIZE+1],*ptr;
  char **hosts=NULL;
  int j=0,fd,cnt,ncnt;

  tmp[MAXHOSTSSIZE]='\0';

  if((fd=open(HOSTS,O_RDONLY,0)) == -1) {
    perror("can't open hosts file");
    exit(1);
  }
  cnt=read(fd,tmp,MAXHOSTSSIZE);
  close(fd);

  for(ptr=tmp; *ptr!=0; ptr++)
    if(*ptr=='\n') ncnt++;
  
  hosts=(char**)malloc((ncnt+1)*sizeof(char*));
  hosts[j++]=tmp;
  for(ptr=tmp; *ptr!=0; ptr++) {
    if(*ptr=='\n') {
      *ptr=0;
      hosts[j++]=ptr+1;
    }
  }
  hosts[--j]=NULL;
  return(hosts);
}

int main(argc, argv)
     int argc;
     char **argv;
{
  char host[MAXHOSTLENGTH],*ptr;
  char **hosts=readhosts();
  
  putenv(LCCTYPE);
  printf("host? ");
  fgets(host,MAXHOSTLENGTH,stdin);
  for(ptr=host; *ptr!=0; ptr++)
    if(*ptr=='\n') *ptr=0;
  while(*hosts) {
    if(strncmp(*hosts,host,MAXHOSTLENGTH-1)==0) {
      execle(TELNET,"telnet","-EK",host,NULL,environ);
      perror("exec failed");
      exit(2);
    }
    hosts++;
  }
  fprintf(stderr,"illegal host\n");
}
