/*
 * Copyright 1989 Jon Bennett, Mike Bolotski, David Gagne, Dan Lovinger
 * Copyright 1986 Chris Gutherie
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, 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 the copyright holders not be used in
 * advertising or publicity pertaining to distribution of the software
 * without specific, written prior permission.  The copyright holders make no
 * representations about the suitability of this software for any purpose.
 * It is provided "as is" without express or implied warranty.
 *
 * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL THE COPYRIGHT HOLDERS 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.
 */

#include <X11/Xos.h>

#include <stdio.h>
#include <pwd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <setjmp.h>
#include <netdb.h>
#include <signal.h>
#include <strings.h>
#include <sys/param.h>

#ifndef FD_SET
#define	FD_SET(n, s)	(((s)->fds_bits[0]) |= (1 << n))
#define	FD_CLR(n, s)	(((s)->fds_bits[0]) &= ~(1 << n))
#define	FD_ZERO(s)	bzero((char *)(s), sizeof (*(s)))
#define	FD_ISSET(n, s)	(((s)->fds_bits[0]) & (1 << n))
#endif

struct sockaddr_in sin;
struct sockaddr_in udp_sin;
struct servent *sp;
jmp_buf         sdied;

done()
{
  fprintf(stderr, "broken pipe\n");
  longjmp(sdied);
}

main(ac, av)
  register int    ac;
  register char **av;
{
  register struct hostent *host = (struct hostent *) NULL;
  struct passwd  *pwent;
  int             s, watchvar;
  char           *h, *p;
  char            hostname[80];		/* The xtrek-server-machine */
  char            dname[80];
  char           *display;
  extern struct servent *getservbyname();
  extern char    *getenv();

  p = rindex(av[0], '/');
  if (p == (char *) NULL)
    p = av[0];
  if ((ac != 2) && (ac != 4))
    usage(p);

  pwent = getpwuid(getuid());
  if (pwent == (struct passwd *) NULL) {
    printf("Who are you?\n");
    exit(2);
  }
  display = getenv("DISPLAY");
  if ((strncmp(display, "unix", 4) == 0) || (strncmp(display, ":", 1)) == 0) {
    gethostname(dname, sizeof dname);
    strcat(dname, rindex(display, ':'));
    display = dname;
  }
  if (display == (char *) NULL) {
    printf("Your DISPLAY environment variable is not set.\n");
    exit(3);
  }

  /* Check internet adresses - Brett */

  {
    int gidsetlen, gidset[NGROUPS], num_groups;
    register int foo =0, a=1;
    
    num_groups = getgroups(NGROUPS, gidset);
    for (;(foo < num_groups);foo++)
      {
	if (gidset[foo] == 13271)
	  a = 0;
      }
    if ((a) && (check(av[1], display)))
      exit(1);
  }
  h = av[1];
  sin.sin_addr.s_addr = inet_addr(h);
  if (sin.sin_addr.s_addr != -1) {
    sin.sin_family = AF_INET;
    (void) strcpy(hostname, h);
  }
  else {
    host = gethostbyname(h);
    if (host) {
      sin.sin_family = host->h_addrtype;
      bcopy(host->h_addr, (caddr_t) & sin.sin_addr,
	    host->h_length);
      strcpy(hostname, host->h_name);
/*      strncpy(hostname, host->h_name, strlen(host->h_name));*/
      
    }
    else {
      printf("%s: unknown host\n", h);
      exit(1);
    }
  }

  /* Perform random system commands to set font path and xhost */
  {
    char foo[200];
    strcpy(foo,"xhost ");
    strcat(foo, hostname);
    system(foo);
    system("xset +fp /afs/sipb/project/xtrek/@sys");
  }
  
  sin.sin_port = htons(25876);
  signal(SIGPIPE, done);
  s = socket(AF_INET, SOCK_STREAM, 0);

  if (s < 0) {
    perror("socket");
    exit(1);
  }
  if (connect(s, (struct sockaddr *) & sin, sizeof (sin)) < 0) {
    perror("connect");
    (void) close(s);
    exit(1);
  }

  if (ac == 2)
    watchvar = 0;
  else
    {
      watchvar = (strncmp(av[2], "-c", 2)) ? 1 : 2;
      watchvar = watchvar * 100  + atoi(av[3]);
    }

  if (setjmp(sdied) == 0)
    startup(s, display, pwent->pw_name, watchvar);

  exit(0);
}

startup(s, disp, log, foo)
  register int    s, foo;
  register char  *disp, *log;
{
  char            buf[80];
  int             n = 1;

  sprintf(buf, "Display: %s Login: %s Cowatch: %d", disp, log, foo);
  write(s, buf, strlen(buf));
  write(s, "\015\012", 2);
  fflush(stdout);
  while ((n = read(s, buf, sizeof buf)) >= 0) {
    if (n <= 0) {
      write(s, "DONE\n", 5);		/* Does this cause SIGPIPE? */
      /* No, I think it causes read() above to return -1 */
      sleep(1);
    }
    else
      write(fileno(stdout), buf, n);
  }
  return 1;
}

usage(p)
  register char  *p;
{
  printf("Usage: %s xtrek-server-machine\n", p);
  exit(1);
}

/* Taken from the Xtank code - Brett */
/*
** Checks the internet addresses of each client name against the
** name of the server, the machine this process is running on.
**
** Return code  Meaning
** -----------  -------
**      0       all the addresses are on the same subnet
**      1       the server's name cannot be determined
**      2       the server's location cannot be determined
**      3       client's display name is too long
**      4       client's location cannot be determined
**      5       client is not on the same subnet as the server
*/


int check_internet(server_name, client_name)
     char server_name[256];
     char client_name[256];
{
  char server_addr[5];
  char client_addr[5];
  struct hostent *host;
  char *tmp;
  int newlen;
  
  /* Get the name of the server */
  if(gethostname(client_name,256) != 0)
    return 1;
  
  /* Get the location of the server */
  host = gethostbyname(server_name);
  if(host == (struct hostent *) NULL)
    return 2;
  
  /* Get the network address of the server */
  (void) bcopy(host->h_addr,server_addr,sizeof(host->h_addr));
  
  /* Make sure the client is on same subnet as the server */
  newlen = strlen(client_name);
  
  /* Strip off the :x.y from each display name */
  if((tmp = rindex(client_name,':')) != (char *) NULL)
    newlen -= strlen(tmp);
  client_name[newlen] = '\0';
  
  if(newlen > 225)
    return 3;
  
  /* Client "unix" or "" means the server machine, so it's ok */
  if(!strcmp(client_name,"unix") || client_name[0] == '\0')
    return 0;
  
  /* Get the host information about the client */
  host = gethostbyname(client_name);
  if(host == (struct hostent *) NULL)
    return 4;
  
  /* Get the network address of the client */
  (void) bcopy(host->h_addr,client_addr,sizeof(host->h_addr));
  
  /* Compare subnet of server with subnet of client */
  if (server_addr[1] != client_addr[1])
    {
      client_name[newlen] = ':';
      return 5;
    }
  else
    {
      client_name[newlen] = ':';
      return 0;
    }
}

  /*
   ** Taken from the Xtank code and edited - Brett
   */
int check(host, display)
char *host;
char *display;
{   
  int ret;
  char foo[5];

  printf("Checking internet adresses of server and client\n");
  ret = check_internet(host, display);
  if(ret) {
    if(ret == 5) {
      printf("Client too far away on the network.  Sending large");
      printf(" X-packets over gateways\n");
      printf("tends to be frowned upon.  Network lossage is not taken");
      printf(" lightly, so\n");
      printf("just say NO to network hosure.\n");
      printf;
    }
    return 1;
  }
  printf("Done\n");
  return 0;
}
