gaen.c

src/gaen.c · 545.9 KB

From the archive gaen_M_18_2.tar.gz

Download the archive   « Back to the archive contents

/*****************************************************************************
	    NUTS version 3.3.3 - Copyright (C) Neil Robertson 1996

 This software is provided as is. It is not intended as any sort of bullet
 proof system for commercial operation and I accept no liability for any
 problems that may arise from you using it. Since this is freeware (NOT public
 domain, I have not relinquished the copyright) you may distribute it as you
 see fit and you may alter the code to suit your needs.

 Neil Robertson.
 Email	  : neil@ogham.demon.co.uk
 Home page: http://www.wso.co.uk/neil.html (need JavaScript enabled browser)
 NUTS page: http://www.wso.co.uk/nuts.html
 Newsgroup: alt.talkers.nuts

 *****************************************************************************/
/* Written and modified by Sabin-Corneliu Buraga (c)1996-2002
   (final revision: 18-May-2002)
   
   Email    : busaco@infoiasi.ro
   Home page: http://www.infoiasi.ro/~busaco/
   GAEN page: http://www.infoiasi.ro/~busaco/gaen/	      

   Portions of code written by Victor Tarhon-Onu <mituc@ac.tuiasi.ro>
   For other details, please consult help_credits() function.
  
  ---------------------------------------------------------------------------
*/
#include <stdio.h>
#ifdef _AIX
#include <sys/select.h>
#endif
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <time.h>
#include <fcntl.h>
#include <netdb.h>
#include <dirent.h>
#include <netinet/in.h>
#include <signal.h>
#include <unistd.h>
#include <setjmp.h>
#include <errno.h>
#include <utmp.h>
#include <string.h>
#include <pwd.h>
#include <grp.h>

#include "gaen.h"

#define VERSION  "3.3.3"
#define GAEN_VER "M (18.2)"
#define GAENDTD_VER "1.2"
#define GSH_VER  "2.7"
#define GSL_VER  "4.2"

#define GAEN_UPDATE "18-May-2002"

/* main function */
main (argc, argv)
     int argc;
     char *argv[];
{
  fd_set readmask;
  int i, len;
  char inpstr[ARR_SIZE];
  char *remove_first ();
  UR_OBJECT user, next;
  NL_OBJECT nl;

  strcpy (progname, argv[0]);
/* processing command line parameters... */
  if (argc < 2)
    strcpy (confile, CONFIGFILE);
  else
    {
      if (argc < 2)
	help_usage ();
      else
	{			/* show version */
	  if (!strcmp (argv[1], "-v") || !strcmp (argv[1], "--version"))
	    {
	      printf ("\nGAEN %s @ %s based on NUTS %s\n",
		      GAEN_VER, GAEN_UPDATE, VERSION);
	      exit (14);
	    }
	  if (argc < 3)
	    help_usage ();
	  /* set config file */
	  if (!strcmp (argv[1], "-c") || !strcmp (argv[1], "--config"))
	    strcpy (confile, argv[2]);
	  else
	    /* born a super user account */
	  if (!strcmp (argv[1], "-b") || !strcmp (argv[1], "--born"))
	    born_maxleveluser (argv[2]);
	  else
	    /* wrong options */
	    help_usage ();
	}
    }

/* Startup */
  printf ("\n--->>> GAEN %s - %s (based on NUTS %s) booting... <<<---\n\n",
	  GAEN_VER, GAEN_UPDATE, VERSION);
  init_globals ();
  write_syslog (LOG_CHAT, "\n>>> GAEN ADVANCED TALKER SERVER BOOTING...\n",
		LOG_NOTIME);
  set_date_time ();
  init_signals ();
  load_and_parse_config ();
  load_swear_file (NULL);
  load_commands_file (NULL);
  init_sockets ();
  init_hostsfile ();

  if (auto_connect)
    init_connections ();
  else
    printf ("Skipping connect stage.\n");
  check_messages (NULL, CHK_MSG_BOOT);

/* Run in background automatically. */
  switch (fork ())
    {
    case -1:
      boot_exit (11);		/* fork failure */
    case 0:
      break;			/* child continues */
    default:
      sleep (1);
      exit (0);			/* parent dies */
    }
  reset_alarm ();
  printf ("\n--->>> Booted with PID %d <<<---\n\n", getpid ());
  sprintf (text,
	   ">>> GAEN Advanced Server Talker version %s @ %s ...\n>>> Booted successfully with PID %d %s <<<\n\n",
	   GAEN_VER, GAEN_UPDATE, getpid (), long_date (1));
  for (i = 0; i < MAX_LOGS; i++)
    write_syslog (i, text, LOG_NOTIME);

/**** Main program loop. *****/
  setjmp (jmpvar);		/* rescue if we crash and crash_action = IGNORE */
  while (1)
    {
      /* set up mask then wait */
      setup_readmask (&readmask);
      if (select (FD_SETSIZE, &readmask, 0, 0, 0) == -1)
	continue;

      /* check for connection to listen sockets */
      for (i = 0; i < 3; ++i)
	{
	  if (FD_ISSET (listen_sock[i], &readmask))
	    accept_connection (listen_sock[i], i);
	}

      /* Cycle through client-server connections to other talkers */
      for (nl = nl_first; nl != NULL; nl = nl->next)
	{
	  no_prompt = 0;
	  if (nl->type == UNCONNECTED || !FD_ISSET (nl->socket, &readmask))
	    continue;
	  /* See if remote site has disconnected */
	  if (!(len = read (nl->socket, inpstr, sizeof (inpstr) - 3)))
	    {
	      if (nl->stage == UP)
		sprintf (text, "NETLINK: Remote disconnect by %s.\n",
			 nl->service);
	      else
		sprintf (text, "NETLINK: Remote disconnect by site %s.\n",
			 nl->site);
	      write_syslog (LOG_LINK, text, LOG_TIME);
	      sprintf (text,
		       "~OLGAEN:~RS Lost link to service %s in the %s.\n",
		       nl->service, nl->connect_room->name);
	      write_room (NULL, text);
	      shutdown_netlink (nl);
	      continue;
	    }
	  inpstr[len] = '\0';
	  exec_netcom (nl, inpstr);
	}

      /* Cycle through users. Use a while loop instead of a for because
         user structure may be destructed during loop in which case we
         may lose the user->next link. */
      user = user_first;
      while (user != NULL)
	{
	  next = user->next;	/* store in case user object is destructed */
	  /* If remote user or clone ignore */
	  if (user->type != USER_TYPE)
	    {
	      user = next;
	      continue;
	    }

	  /* see if any data on socket else continue */
	  if (!FD_ISSET (user->socket, &readmask))
	    {
	      user = next;
	      continue;
	    }

	  /* see if client (eg telnet) has closed socket */
	  inpstr[0] = '\0';
	  if (!(len = read (user->socket, inpstr, sizeof (inpstr))))
	    {
	      disconnect_user (user);
	      user = next;
	      continue;
	    }
	  /* ignore control code replies */
	  if ((unsigned char) inpstr[0] == 255)
	    {
	      user = next;
	      continue;
	    }
	  /* Deal with input chars. If the following if test succeeds we
	     are dealing with a character mode client so call function. */
	  if (inpstr[len - 1] >= 32 || user->buffpos)
	    {
	      if (get_charclient_line (user, inpstr, len))
		goto GOT_LINE;
	      user = next;
	      continue;
	    }
	  else
	    terminate (inpstr);

	GOT_LINE:
	  no_prompt = 0;
	  com_num = -1;
	  force_listen = 0;
	  destructed = 0;
	  user->buff[0] = '\0';
	  user->buffpos = 0;
	  user->last_input = time (0);
	  if (user->login)
	    {
	      login_user (user, inpstr);
	      user = next;
	      continue;
	    }
	  /* If a dot on its own then execute last inpstr unless its a misc
	     op or the user is on a remote site */
	  if (!user->misc_op)
	    {
	      if (!strcmp (inpstr, ".") && user->inpstr_old[0])
		{
		  strcpy (inpstr, user->inpstr_old);
		  sprintf (text, "%s\n", inpstr);
		  write_user (user, text);
		}
	      /* else save current one for next time */
	      else
		{
		  if (inpstr[0])
		    strncpy (user->inpstr_old, inpstr, REVIEW_LEN);
		}
	    }

	  /* Main input check */
	  clear_words ();
	  word_count = wordfind (user, inpstr);
	  if (user->afk)
	    {
	      write_user (user, ">>>You are no longer AFK.\n");
	      if (user->vis)
		{
		  sprintf (text, ">>>%s comes back from being AFK.\n",
			   user->name);
		  write_room_except (user->room, text, user);
		}
	      user->afk = 0;
	      event = E_NOAFK;
	      strcpy (event_var, user->savename);
	    }

	  if (!word_count)
	    {
	      if (misc_ops (user, inpstr))
		{
		  user = next;
		  continue;
		}
	      if (user->room == NULL)
		{
		  sprintf (text, "ACT %s NL\n", user->savename);
		  write_sock (user->netlink->socket, text);
		}
	      if (user->command_mode)
		prompt (user);
	      user = next;
	      continue;
	    }
	  if (misc_ops (user, inpstr))
	    {
	      user = next;
	      continue;
	    }
	  com_num = -1;
	  /* Checking for some short-cuts... */
	  if (user->command_mode || strchr (".`;!<>-#?$/'[=\\", inpstr[0]))
	    exec_com (user, inpstr);
	  else
	    say (user, inpstr);
	  if (!destructed)
	    {
	      if (user->room != NULL)
		prompt (user);
	      else
		{
		  switch (com_num)
		    {
		    case -1:	/* Unknown command */
		    case HOME:
		    case QUIT:
		    case MODE:
		    case PROMPT:
		    case SUICIDE:
		    case REBOOT:
		    case SHUTDOWN:
		      prompt (user);
		    }
		}
	    }
	  user = next;
	}
    }				/* end while */
}

/************ COMMAND LINE RESOLVE FUNCTIONS ************/

/*** Write help usage ***/
help_usage ()
{
  fprintf (stderr, "%s: help information (GAEN %s @ %s)\n\n",
	   progname, GAEN_VER, GAEN_UPDATE);
  fprintf (stderr, ">>>Usage: %s [ <option> ]\n", progname);
  fprintf (stderr, ">>>Valid options are:\n\n");
  fprintf (stderr,
	   "\t-b, --born <name>   to create an administration account\n");
  fprintf (stderr,
	   "\t-c, --config <file> to use the configuration file <file>\n");
  fprintf (stderr,
	   "\t-v, --version       output version information and exit\n");
  fprintf (stderr,
	   "\n>>>If no options, default configuration file is used.\n\n");
  exit (14);
}

/*** Born a super-user (maximum level) account ***/
born_maxleveluser (name)
     char *name;
{
  int i;
  FILE *fp;
  char filename[80];

  if (strlen (name) < PASS_MIN_LEN || strlen (name) > PASS_MAX_LEN)
    {
      fprintf (stderr, "GAEN: Invalid username length.\n");
      exit (13);
    }
  for (i = 0; i < strlen (name); ++i)
    {
      if (!isalpha (name[i]))
	{
	  fprintf (stderr, "GAEN: Only letters are allowed in a name.\n");
	  exit (13);
	}
    }
  strtolower (name);
  name[0] = toupper (name[0]);
  /* check if user is banned */
  if (user_banned (name))
    {
      fprintf (stderr,
	       "GAEN: That user is banned. Check '%s/%s' file, please.\n",
	       DATAFILES, USERBAN);
      exit (13);
    }
  sprintf (filename, "%s/%s.D", USERFILES, name);
  s_unlink (filename);		/* to backup old file if exists */
  if ((fp = fopen (filename, "w")) == NULL)
    {
      fprintf (stderr, "GAEN: Cannot create user file.\n");
      exit (13);
    }
  /* write the .D file */
  fprintf (fp, "%s\n", (char *) crypt (name, PASS_SALT));
  fprintf (fp, "%d %d %d %d %d %d %d %d %d %d\n",
	   0, 0, 0, 0, SGOD, 0, 0, 0, 0, 1);
  fprintf (fp, "gaen.ro\na real ~FG~OL!!!\nenters\ngoes\n");
  fclose (fp);
  printf ("\nGAEN: Maximum level user %s created (see '%s' file).\n",
	  name, filename);
  /* adjust the allow user files */
  for (i = MIN_LEV_ALLOW; i <= MAX_LEV_ALLOW; i++)
    {
      sprintf (filename, "%s/%s.%d", DATAFILES, ALLOWFILE, i);
      if ((fp = fopen (filename, "a")) == NULL)
	{
	  fprintf (stderr, "GAEN: Warning, cannot append allow file '%s'.\n",
		   filename);
	}
      else
	{
	  fprintf (fp, "%s\n", name);
	  printf ("GAEN: User added to allow file '%s'...\n", filename);
	  fclose (fp);
	}
    }
  exit (12);
}

/************ MAIN LOOP FUNCTIONS ************/

/*** Set up readmask for select ***/
setup_readmask (mask)
     fd_set *mask;
{
  UR_OBJECT user;
  NL_OBJECT nl;
  int i;

  FD_ZERO (mask);
  for (i = 0; i < 3; ++i)
    FD_SET (listen_sock[i], mask);
/* Do users */
  for (user = user_first; user != NULL; user = user->next)
    if (user->type == USER_TYPE)
      FD_SET (user->socket, mask);

/* Do client-server stuff */
  for (nl = nl_first; nl != NULL; nl = nl->next)
    if (nl->type != UNCONNECTED)
      FD_SET (nl->socket, mask);
}


/*** Accept incoming connections on listen sockets ***/
accept_connection (lsock, num)
     int lsock, num;
{
  UR_OBJECT user, create_user ();
  NL_OBJECT create_netlink ();
  char *get_ip_address (), site[80], filename[80];
  struct sockaddr_in acc_addr;
  int accept_sock, size;

  size = sizeof (struct sockaddr_in);
  accept_sock = accept (lsock, (struct sockaddr *) &acc_addr, &size);
  if (num == 2)
    {
      accept_server_connection (accept_sock, acc_addr);
      return;
    }
  strcpy (site, get_ip_address (acc_addr));
  if (site_banned (site))
    {
      write_sock (accept_sock,
		  "\n\r>>>Logins from your site are banned. Sorry...\n\n\r");
      close (accept_sock);
      sprintf (text, "~OLGAEN:~RS Attempted login from banned site %s.\n",
	       site);
      write_syslog (LOG_CHAT, text, LOG_TIME);
      write_level (MIN_LEV_NOTIFY, text, NULL);
      return;
    }
  sprintf (filename, "%s.%d", PRELOG_MSG, random () % prelog_msgs + 1);
  more (NULL, accept_sock, filename);	/* send pre-login message */
  if (num_of_users + num_of_logins >= max_users && !num)
    {
      write_sock (accept_sock,
		  "\n\r>>>Sorry, the talker is full at the moment. Please, return later...\n\n\r");
      close (accept_sock);
      return;
    }
  if ((user = create_user ()) == NULL)
    {
      sprintf (text,
	       "\n\r%s: unable to create session. Sorry... Please, return later...\n\n\r",
	       syserror);
      write_sock (accept_sock, text);
      close (accept_sock);
      return;
    }
  user->socket = accept_sock;
  user->login = 3;
  user->last_input = time (0);
  if (!num)
    user->port = port[0];
  else
    {
      user->port = port[1];
      write_user (user,
		  "--->>> Super port login (only for superior users) <<<---\n\n");
      user->dimension = MAX_DIMENS - 1;
    }
  strcpy (user->site, site);
  user->site_port = (int) ntohs (acc_addr.sin_port);
  if (user->site_port == port[0] || user->site_port == port[1] ||
      user->site_port == port[2] || !user->site_port)
    {
      sprintf (text, "~OLGAEN:~RS Wrong port for %s from site %s\n",
	       user->savename, site);
      write_syslog (LOG_CHAT, text, LOG_TIME);
      write_level (MIN_LEV_NOTIFY, text, NULL);
      disconnect_user (user);
    }
  echo_on (user);
  write_user (user, DEF_NAME_MSG);
  num_of_logins++;
}


/*** Get net address of accepted connection ***/
char *
get_ip_address (acc_addr)
     struct sockaddr_in acc_addr;
{
  static char site[80];
  struct hostent *host;

  strcpy (site, (char *) inet_ntoa (acc_addr.sin_addr));	/* get number addr */
  if (!check_host (site))
    {				/* host name not found in hosts file */
      if ((host = gethostbyaddr ((char *) &acc_addr.sin_addr, 4, AF_INET)) !=
	  NULL)
	{			/* not found in hosts file... then it will be added */
	  add_host (site, host->h_name);

	  strcpy (site, host->h_name);	/* copy name addr. */
	}
    }
  strtolower (site);
  return site;
}

/*** Check if a host is in hosts file ***/
check_host (site)
     char *site;
{
  FILE *fp;
  char siteaddr[82], sitename[82], filename[80];

  if (!use_hostsfile)
    return 0;
  sprintf (filename, "%s/%s", DATAFILES, HOSTSFILE);
  if (!(fp = fopen (filename, "r")))
    return 0;
  fscanf (fp, "%s %s", siteaddr, sitename);
  while (!feof (fp))
    {
      if (!strcmp (site, siteaddr))
	{
	  fclose (fp);
	  strcpy (site, sitename);
	  return 1;
	}
      fscanf (fp, "%s %s", siteaddr, sitename);
    }
  fclose (fp);
  return 0;
}

/*** Init the hosts file ***/
init_hostsfile ()
{
  FILE *fp;
  char filename[80];

  if (!use_hostsfile)
    return;
  sprintf (filename, "%s/%s", DATAFILES, HOSTSFILE);
  if (!(fp = fopen (filename, "r")))
    {
      if (!(fp = fopen (filename, "w")))
	{
	  write_syslog (LOG_ERR, "Cannot read file in add_host().\n",
			LOG_NOTIME);
	  return;
	}
      /* store the default IP for localhost */
      fprintf (fp, "127.0.0.1 localhost\n");
      fclose (fp);
      return;
    }
}

/*** Add a site in hosts file ***/
add_host (siteaddr, sitename)
     char *siteaddr, *sitename;
{
  FILE *fp;
  char filename[80], asite[80], aname[80];

  if (!use_hostsfile)
    return;
  sprintf (filename, "%s/%s", DATAFILES, HOSTSFILE);
  if (!(fp = fopen (filename, "r")))
    {
      write_syslog (LOG_ERR, "Cannot read file in add_host().\n", LOG_NOTIME);
      return;
    }
  fscanf (fp, "%s %s", asite, aname);
  while (!feof (fp))
    {
      if (!strcmp (asite, siteaddr))
	{
	  fclose (fp);		/* found, so don't want to write it to file */
	  return;
	}
      fscanf (fp, "%s %s", asite, aname);
    }
  fclose (fp);
  if (!(fp = fopen (filename, "a")))
    {
      write_syslog (LOG_ERR, "Cannot append file in add_host().\n",
		    LOG_NOTIME);
      return;
    }
  fprintf (fp, "%s %s\n", siteaddr, sitename);
  fclose (fp);
}

/*** See if users site is banned ***/
site_banned (site)
     char *site;
{
  FILE *fp;
  char line[82], filename[80];

  sprintf (filename, "%s/%s", DATAFILES, SITEBAN);
  if (!(fp = fopen (filename, "r")))
    return 0;
  fscanf (fp, "%s", line);
  while (!feof (fp))
    {
      if (strstr (site, line))
	{
	  fclose (fp);
	  return 1;
	}
      fscanf (fp, "%s", line);
    }
  fclose (fp);
  return 0;
}


/*** See if user is banned ***/
user_banned (name)
     char *name;
{
  FILE *fp;
  char line[82], filename[80];

  sprintf (filename, "%s/%s", DATAFILES, USERBAN);
  if (!(fp = fopen (filename, "r")))
    return 0;
  fscanf (fp, "%s", line);
  while (!feof (fp))
    {
      if (!strcmp (line, name))	/* found */
	{
	  fclose (fp);
	  return 1;
	}
      fscanf (fp, "%s", line);
    }
  fclose (fp);
/* not found */
  return 0;
}


/*** Attempt to get '\n' terminated line of input from a character
     mode client else store data read so far in user buffer. ***/
get_charclient_line (user, inpstr, len)
     UR_OBJECT user;
     char *inpstr;
     int len;
{
  int l;

  for (l = 0; l < len; ++l)
    {
      /* see if delete entered */
      if (inpstr[l] == 8 || inpstr[l] == 127)
	{
	  if (user->buffpos)
	    {
	      user->buffpos--;
	      if (user->charmode_echo)
		write_user (user, "\b \b");
	    }
	  continue;
	}
      user->buff[user->buffpos] = inpstr[l];
      /* See if end of line */
      if (inpstr[l] < 32 || user->buffpos + 2 == ARR_SIZE)
	{
	  terminate (user->buff);
	  strcpy (inpstr, user->buff);
	  if (user->charmode_echo)
	    write_user (user, "\n");
	  return 1;
	}
      user->buffpos++;
    }
  if (user->charmode_echo
      && ((user->login != 2 && user->login != 1) || password_echo))
    write (user->socket, inpstr, len);
  return 0;
}


/*** Put string terminate char. at first char < 32 ***/
terminate (str)
     char *str;
{
  int i;
  for (i = 0; i < ARR_SIZE; ++i)
    {
      if (*(str + i) < 32)
	{
	  *(str + i) = 0;
	  return;
	}
    }
  str[i - 1] = 0;
}


/*** Get words from sentence. This function prevents the words in the
     sentence from writing off the end of a word array element. This is
     difficult to do with sscanf() hence we use this function instead. ***/
wordfind (user, inpstr)
     UR_OBJECT user;
     char *inpstr;
{
  int wn, wpos;

  wn = 0;
  wpos = 0;
  do
    {
      while (*inpstr < 33)
	if (!*inpstr++)
	  return wn;
      while (*inpstr > 32 && wpos < WORD_LEN - 1)
	{
	  word[wn][wpos] = *inpstr++;
	  wpos++;
	}
      word[wn][wpos] = '\0';
      if (word[wn][0] == '{')	/* substitution of pre-defined variables */
	strcpy (word[wn], user->var1);
      else if (word[wn][0] == '}')
	strcpy (word[wn], user->var2);
      else if (word[wn][0] == '*')
	strcpy (word[wn], event_var);
      wn++;
      wpos = 0;
    }
  while (wn < MAX_WORDS);

  return wn - 1;
}


/*** clear word array etc. ***/
clear_words ()
{
  int w;
  for (w = 0; w < MAX_WORDS; ++w)
    word[w][0] = '\0';
  word_count = 0;
}

/************ PARSE CONFIG FILE **************/

load_and_parse_config ()
{
  FILE *fp;
  char line[81];		/* Should be long enough */
  char c, filename[80];
  int d, i, section_in, got_init, got_rooms;
  RM_OBJECT rm1, rm2;
  NL_OBJECT nl;

  section_in = 0;
  got_init = 0;
  got_rooms = 0;

  sprintf (filename, "%s/%s", CONFFILES, confile);
  printf ("Parsing config file \"%s\"... ", filename);
  fflush (stdout);
  if (!(fp = fopen (filename, "r")))
    {
      perror ("cannot open");
      boot_exit (1);
    }
  printf ("found.\n");
/* Main reading loop */
  config_line = 0;
  fgets (line, 81, fp);
  while (!feof (fp))
    {
      config_line++;
      for (i = 0; i < 8; ++i)
	wrd[i][0] = '\0';
      sscanf (line, "%s %s %s %s %s %s %s %s",
	      wrd[0], wrd[1], wrd[2], wrd[3], wrd[4], wrd[5], wrd[6], wrd[7]);
      if (wrd[0][0] == '#' || wrd[0][0] == '\0')
	{
	  fgets (line, 81, fp);
	  continue;
	}
      /* See if new section */
      if (wrd[0][strlen (wrd[0]) - 1] == ':')
	{
	  if (!strcmp (wrd[0], "INIT:"))	/* INIT section */
	    section_in = 1;
	  else if (!strcmp (wrd[0], "ROOMS1:"))	/* ROOMSx sections */
	    section_in = 2;
	  else if (!strcmp (wrd[0], "ROOMS2:"))
	    section_in = 3;
	  else if (!strcmp (wrd[0], "ROOMS3:"))
	    section_in = 4;
	  else if (!strcmp (wrd[0], "SITES:"))	/* SITES section */
	    section_in = 5;
	  else
	    {			/* unknown section */
	      fprintf (stderr,
		       "GAEN: Unknown section header on line %d.\n",
		       config_line);
	      fclose (fp);
	      boot_exit (1);
	    }
	}
      switch (section_in)
	{			/* parse sections */
	case 1:
	  parse_init_section ();
	  got_init = 1;
	  break;
	case 2:
	  parse_rooms_section (0);
	  got_rooms = 1;
	  break;
	case 3:
	  parse_rooms_section (1);
	  got_rooms = 2;
	  break;
	case 4:
	  parse_rooms_section (2);
	  got_rooms = 3;
	  break;
	case 5:
	  parse_sites_section ();
	  break;
	default:
	  fprintf (stderr, "GAEN: Section header expected on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      fgets (line, 100, fp);
    }
  fclose (fp);

/* See if required sections were present (SITES is optional) and if
   required parameters were set. */
  if (!got_init)
    {
      fprintf (stderr, "GAEN: INIT section missing from config file.\n");
      boot_exit (1);
    }
  if (!got_rooms)
    {
      fprintf (stderr,
	       "GAEN: One of the ROOMSx sections missing from config file.\n");
      boot_exit (1);
    }
  if (!verification[0])
    {
      fprintf (stderr, "GAEN: Verification not set in config file.\n");
      boot_exit (1);
    }
  if (!port[0])
    {
      fprintf (stderr, "GAEN: Main port number not set in config file.\n");
      boot_exit (1);
    }
  if (!port[1])
    {
      fprintf (stderr, "GAEN: Saint port number not set in config file.\n");
      boot_exit (1);
    }
  if (!port[2])
    {
      fprintf (stderr, "GAEN: Link port number not set in config file.\n");
      boot_exit (1);
    }
  if (port[0] == port[1] || port[1] == port[2] || port[0] == port[2])
    {
      fprintf (stderr, "GAEN: Port numbers must be unique.\n");
      boot_exit (1);
    }
  if (room_first == NULL)
    {
      fprintf (stderr, "GAEN: No skies configured in config file.\n");
      boot_exit (1);
    }

/* Parsing done, now check data is valid. Check room stuff first. */
  for (d = 0; d < MAX_DIMENS; d++)
    for (rm1 = room_first[d]; rm1 != NULL; rm1 = rm1->next)
      {
	for (i = 0; i < MAX_LINKS; ++i)
	  {
	    if (!rm1->link_label[i][0])
	      break;
	    for (rm2 = room_first[d]; rm2 != NULL; rm2 = rm2->next)
	      {
		if (rm1 == rm2)
		  continue;
		if (!strcmp (rm1->link_label[i], rm2->label))
		  {
		    rm1->link[i] = rm2;
		    break;
		  }
	      }
	    if (rm1->link[i] == NULL)
	      {
		fprintf (stderr,
			 "GAEN: Sky %s has undefined link label '%s'.\n",
			 rm1->name, rm1->link_label[i]);
		boot_exit (1);
	      }
	  }
      }

/* Check external links */
  for (d = 0; d < MAX_DIMENS; d++)
    for (rm1 = room_first[d]; rm1 != NULL; rm1 = rm1->next)
      {
	for (nl = nl_first; nl != NULL; nl = nl->next)
	  {
	    if (!strcmp (nl->service, rm1->name))
	      {
		fprintf (stderr,
			 "GAEN: Service name %s is also the name of a sky.\n",
			 nl->service);
		boot_exit (1);
	      }
	    if (rm1->netlink_name[0]
		&& !strcmp (rm1->netlink_name, nl->service))
	      {
		rm1->netlink = nl;
		break;
	      }
	  }
	if (rm1->netlink_name[0] && rm1->netlink == NULL)
	  {
	    fprintf (stderr,
		     "GAEN: Service name %s not defined for sky %s.\n",
		     rm1->netlink_name, rm1->name);
	    boot_exit (1);
	  }
      }

/*** Load room descriptions & default topics (if any) ***/
  for (d = 0; d < MAX_DIMENS; d++)
    for (rm1 = room_first[d]; rm1 != NULL; rm1 = rm1->next)
      {
	sprintf (filename, "%s/%s.R", DATAFILES, rm1->name);
	if (!(fp = fopen (filename, "r")))
	  {
	    fprintf (stderr,
		     "GAEN: Can't open description file for sky %s.\n",
		     rm1->name);
	    sprintf (text,
		     "Warning: Couldn't open description file for sky %s.\n",
		     rm1->name);
	    write_syslog (LOG_ERR, text, LOG_TIME);
	    continue;
	  }
	i = 0;
	c = getc (fp);
	while (!feof (fp))
	  {
	    if (i == ROOM_DESC_LEN)
	      {
		fprintf (stderr, "GAEN: Description too long for sky %s.\n",
			 rm1->name);
		sprintf (text, "Warning: Description too long for sky %s.\n",
			 rm1->name);
		write_syslog (LOG_ERR, text, LOG_TIME);
		break;
	      }
	    rm1->desc[i] = c;
	    c = getc (fp);
	    ++i;
	  }
	rm1->desc[i] = '\0';
	fclose (fp);
	/* try to load topic for a room... */
	sprintf (filename, "%s/%s.T", DATAFILES, rm1->name);
	if (!(fp = fopen (filename, "r")))
	  {
	    sprintf (text, "Warning: Couldn't open topic file for sky %s.\n",
		     rm1->name);
	    write_syslog (LOG_ERR, text, LOG_TIME);
	    continue;
	  }
	fgets (line, TOPIC_LEN + 2, fp);
	line[strlen (line) - 1] = '\0';
	strcpy (rm1->topic, line);
	fclose (fp);
      }
}

/*** Parse init section ***/
parse_init_section ()
{
  static int in_section = 0;
  int op, val;
  char *options[] = {
    "mainport", "stport", "linkport", "logging", "minlogin_level",
    "mesg_life",
    "stport_level", "prompt_def", "gatecrash_level", "min_private",
    "ignore_mp_level",
    "rem_user_maxlevel", "rem_user_deflevel", "verification",
    "mesg_check_time",
    "max_users", "heartbeat", "login_idle_time", "user_idle_time",
    "password_echo",
    "ignore_sigterm", "auto_connect", "max_clones", "ban_swearing",
    "crash_action",
    "colour_def", "time_out_afks", "allow_caps_in_name", "max_hints",
    "max_quotes",
    "def_mirror", "safety", "use_hosts_file", "words_dict", "gshell",
    "paged_lines",
    "time_out_maxlevel", "def_pballs", "chk_spass_tests", "utmpfile",
    "wtmpfile",
    "autosave_action", "enable_events", "susers_restrict", "enable_rndgo",
    "random_bhole", "prelog_msgs", "newuser_deflevel", "wrap_cols",
    "hint_at_help",
    "emote_spacer", "accept_prelog_comm", "allow_born_maxlev", "*"
  };

  if (!strcmp (wrd[0], "INIT:"))
    {
      if (++in_section > 1)
	{
	  fprintf (stderr,
		   "GAEN: Unexpected INIT section header on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;
    }
  op = 0;
  while (strcmp (options[op], wrd[0]))
    {
      if (options[op][0] == '*')
	{
	  fprintf (stderr, "GAEN: Unknown INIT option on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      ++op;
    }
  if (!wrd[1][0])
    {
      fprintf (stderr, "GAEN: Required parameter missing on line %d.\n",
	       config_line);
      boot_exit (1);
    }
  if (wrd[2][0] && wrd[2][0] != '#')
    {
      fprintf (stderr,
	       "GAEN: Unexpected word following init parameter on line %d.\n",
	       config_line);
      boot_exit (1);
    }
  val = atoi (wrd[1]);
  switch (op)
    {
    case 0:			/* ports used for connect (main, superior, link) */
    case 1:
    case 2:
      if ((port[op] = val) < 1 || val > 65535)
	{
	  fprintf (stderr, "GAEN: Illegal port number on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 3:			/* system logging flag */
      if ((system_logging[LOG_CHAT] = yn_check (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: System_logging must be YES or NO on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      for (val = 0; val < MAX_LOGS; val++)
	system_logging[val] = yn_check (wrd[1]);
      return;

    case 4:			/* minimum level of users who can login */
      if ((minlogin_level = get_level (wrd[1])) == -1)
	{
	  if (strcmp (wrd[1], "NONE"))
	    {
	      fprintf (stderr, "GAEN: Unknown level specifier on line %d.\n",
		       config_line);
	      boot_exit (1);
	    }
	  minlogin_level = -1;
	}
      return;

    case 5:			/* message lifetime */
      if ((mesg_life = val) < 1)
	{
	  fprintf (stderr, "GAEN: Illegal message lifetime on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 6:			/* stport_level */
      if ((stport_level = get_level (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: Unknown level specifier for superusers port on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 7:			/* prompt defaults */
      if ((prompt_def = onoff_check (wrd[1])) == -1)
	{
	  fprintf (stderr, "GAEN: Prompt_def must be ON or OFF on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 8:			/* gatecrash level */
      if ((gatecrash_level = get_level (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: Unknown level specifier for gatecrash level on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 9:			/* minimum number of users for a private room */
      if (val < 1)
	{
	  fprintf (stderr,
		   "GAEN: Minimum number of users for a private room too low on line %d (.\n",
		   config_line);
	  boot_exit (1);
	}
      min_private_users = val;
      return;

    case 10:			/* minimum level to ignore above */
      if ((ignore_mp_level = get_level (wrd[1])) == -1)
	{
	  fprintf (stderr, "GAEN: Unknown level specifier on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 11:
      /* Max level a remote user can remotely log in as if he has an account
         ie if level set to SAINT a GOD can only be a SAINT if logging in from
         another server. */
      if ((rem_user_maxlevel = get_level (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: Unknown level specifier for maximum level of a remote user on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 12:
      /* Default level of remote user who does not have an account on site */
      if ((rem_user_deflevel = get_level (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: Unknown level of remote user who does not have an account on site specifier on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 13:			/* verification string to connect to other talkers */
      if (strlen (wrd[1]) > SERV_NAME_LEN)
	{
	  fprintf (stderr, "GAEN: Verification too long on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      strcpy (verification, wrd[1]);
      return;

    case 14:			/* mesg_check_time */
      if (wrd[1][2] != ':'
	  || strlen (wrd[1]) > 5
	  || !isdigit (wrd[1][0])
	  || !isdigit (wrd[1][1])
	  || !isdigit (wrd[1][3]) || !isdigit (wrd[1][4]))
	{
	  fprintf (stderr,
		   "GAEN: Invalid time on line %d (correct syntax is 'hh:mm').\n",
		   config_line);
	  boot_exit (1);
	}
      wrd[1][2] = ' ';
      sscanf (wrd[1], "%d %d", &mesg_check_hour, &mesg_check_min);
      if (mesg_check_hour > 23 || mesg_check_min > 59)
	{
	  fprintf (stderr, "GAEN: Invalid time on line %d.\n", config_line);
	  boot_exit (1);
	}
      return;

    case 15:			/* number of users who can connect to usual port */
      if ((max_users = val) < 1)
	{
	  fprintf (stderr, "GAEN: Invalid value for max_users on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 16:			/* heartbeat value */
      if ((heartbeat = val) < 1)
	{
	  fprintf (stderr, "GAEN: Invalid value for heartbeat on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 17:			/* login idle time (in seconds) */
      if ((login_idle_time = val) < 10)
	{
	  fprintf (stderr,
		   "GAEN: Invalid value for login_idle_time on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 18:			/* user idle time (in seconds) */
      if ((user_idle_time = val) < 10)
	{
	  fprintf (stderr,
		   "GAEN: Invalid value for user_idle_time on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 19:			/* echo password flag */
      if ((password_echo = yn_check (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: Password_echo must be YES or NO on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 20:			/* ignoring SIGTERM flag */
      if ((ignore_sigterm = yn_check (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: Ignore_sigterm must be YES or NO on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 21:			/* auto connection to other talkers flag */
      if ((auto_connect = yn_check (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: Auto_connect must be YES or NO on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 22:			/* user maximum clones */
      if ((max_clones = val) < 0)
	{
	  fprintf (stderr, "GAEN: Invalid value for max_clones on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 23:			/* ban swears flag */
      if ((ban_swearing = yn_check (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: Ban_swearing must be YES or NO on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 24:			/* action when talker is crashing (NONE, IGNORE, REBOOT) */
      if (!strcmp (wrd[1], "NONE"))
	crash_action = 0;
      else if (!strcmp (wrd[1], "IGNORE"))
	crash_action = 1;
      else if (!strcmp (wrd[1], "REBOOT"))
	crash_action = 2;
      else
	{
	  fprintf (stderr,
		   "GAEN: Crash_action must be NONE, IGNORE or REBOOT on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 25:			/* colour default flag for new users */
      if ((colour_def = onoff_check (wrd[1])) == -1)
	{
	  fprintf (stderr, "GAEN: Colour_def must be ON or OFF on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 26:			/* if AFK users are timed out flag */
      if ((time_out_afks = yn_check (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: Time_out_afks must be YES or NO on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 27:			/* allow caps in user name flag */
      if ((allow_caps_in_name = yn_check (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: Allow_caps_in_name must be YES or NO on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

      /* options added in GAEN versions */
    case 28:			/* maximum hints files */
      if ((max_hints = val) < 0)
	{
	  fprintf (stderr,
		   "GAEN: Invalid value for max_hints on line %d. A decimal number is required.\n",
		   config_line);
	  boot_exit (1);
	}
      if (max_hints == 0)
	max_hints = MAX_HINTS;
      return;

    case 29:			/* maximum quotes files */
      if ((max_quotes = val) < 0)
	{
	  fprintf (stderr,
		   "GAEN: Invalid value for max_quotes on line %d. A decimal number is required.\n",
		   config_line);
	  boot_exit (1);
	}
      if (max_quotes == 0)
	max_quotes = MAX_QUOTES;
      return;

    case 30:			/* default mirror */
      if ((mirror = val) < 0 || mirror >= MAX_MIRRORS)
	{
	  fprintf (stderr, "GAEN: Invalid value for def_mirror on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      for (val = 0; val <= MAX_LEVELS; val++)	/* level names */
	strcpy (level_name[val], level_name_mirror[mirror][val]);
      return;

    case 31:			/* safety erase file flag */
      if ((safety = yn_check (wrd[1])) == -1)
	{
	  fprintf (stderr, "GAEN: Safety must be YES or NO on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 32:			/* using hostfile flag */
      if ((use_hostsfile = yn_check (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: Use_hostsfile parameter must be YES or NO on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 33:			/* number of dictionaries words for Hangman */
      if ((gm_max_words = val) < 0)
	{
	  fprintf (stderr,
		   "GAEN: Invalid value for words_dict on line %d. A decimal number is required.\n",
		   config_line);
	  boot_exit (1);
	}
      if (!gm_max_words)
	gm_max_words = GM_MAX_WORDS;
      return;

    case 34:			/* using gshell flag */
      if ((exec_gshell = onoff_check (wrd[1])) == -1)
	{
	  fprintf (stderr, "GAEN: gshell must be ON or OFF on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 35:			/* default lines in more() */
      if ((def_lines = val) <= 0)
	{
	  fprintf (stderr,
		   "GAEN: Invalid value for def_lines on line %d. A decimal number is required.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 36:			/* maximum level of time-out users  */
      if ((timeout_maxlevel = get_level (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: Unknown level specifier for time_out_maxlevel on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 37:			/* default munition for Paintball */
      if ((def_pballs = val) < 0)
	{
	  fprintf (stderr,
		   "GAEN: Invalid value for def_pballs on line %d. A decimal number is required.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 38:			/* check secure passwords number of tests */
      if ((chk_spass_tests = val) < 0)
	{
	  fprintf (stderr,
		   "GAEN: Invalid value for chk_spass_tests on line %d. A decimal number is required.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 39:			/* set utmpfile name for gsh_last() */
      strcpy (utmpfile, wrd[1]);
      return;

    case 40:			/* set wtmpfile name for gsh_who() */
      strcpy (wtmpfile, wrd[1]);
      return;

    case 41:			/* set autosave users performed actions */
      if (!strcmp (wrd[1], "none"))
	autosave_action = AS_NONE;
      else if (!strcmp (wrd[1], "greet"))
	autosave_action = AS_GREET;
      else if (!strcmp (wrd[1], "quote"))
	autosave_action = AS_QUOTE;
      else if (!strcmp (wrd[1], "all"))
	autosave_action = AS_ALL;
      else
	{
	  fprintf (stderr,
		   "GAEN: Invalid value for autosave_action on line %d.\n(Use only 'none', 'quote', 'greet' or 'all').\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 42:			/* execute events flag */
      if ((enable_event = onoff_check (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: enable_events must be ON or OFF on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 43:			/* default restrictions mask for superior users */
      strcpy (susers_restrict, wrd[1]);
      return;

    case 44:			/* enable random .go sky at login time */
      if ((enable_rndgo = onoff_check (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: enable_rndgo must be ON or OFF on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 45:			/* enable random .blackhole */
      if ((random_bhole = onoff_check (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: random_bhole must be ON or OFF on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 46:			/* number of prelogin messages */
      if ((prelog_msgs = val) <= 0)
	{
	  fprintf (stderr,
		   "GAEN: Invalid value for prelog_msgs on line %d. A decimal number is required.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 47:			/* new users default level */
      if ((newuser_deflevel = get_level (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: Unknown level specifier for newuser_deflevel on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      /* security check */
      if (newuser_deflevel > MAX_LEV_NEWUSER)
	newuser_deflevel = MAX_LEV_NEWUSER;
      return;

    case 48:			/* wrap columns */
      if ((wrap_cols = val) <= 1)
	wrap_cols = WRAP_COLS;
      return;

    case 49:			/* hint at help flag */
      if ((hint_at_help = onoff_check (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: hint_at_help must be ON or OFF on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 50:			/* add a space to each emote speech flag */
      if ((emote_spacer = yn_check (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: emote_spacer must be YES or NO on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 51:			/* accept prelogin commands ('who', 'version', 'quit') flag */
      if ((accept_prelog_comm = yn_check (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: accept_prelog_comm must be YES or NO on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    case 52:			/* allow to .born max-level (superior) users flag */
      if ((allow_born_maxlev = yn_check (wrd[1])) == -1)
	{
	  fprintf (stderr,
		   "GAEN: allow_born_maxlev must be YES or NO on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;

    }				/* end switch */
}

/*** Parse rooms section ***/
parse_rooms_section (dimension)
     int dimension;
{
  static int in_section = 0;
  int i;
  char *ptr1, *ptr2, c;
  RM_OBJECT room;

  sprintf (text, "ROOMS%d:", dimension + 1);
  if (!strcmp (wrd[0], text))
    {
      if (++in_section > 5)
	{
	  fprintf (stderr,
		   "GAEN: Unexpected ROOMSx section header on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;
    }
  if (!wrd[2][0])
    {
      fprintf (stderr, "GAEN: Required parameter(s) missing on line %d.\n",
	       config_line);
      boot_exit (1);
    }
  if (strlen (wrd[0]) > ROOM_LABEL_LEN)
    {
      fprintf (stderr, "GAEN: Room label too long on line %d.\n",
	       config_line);
      boot_exit (1);
    }
  if (strlen (wrd[1]) > ROOM_NAME_LEN)
    {
      fprintf (stderr, "GAEN: Room name too long on line %d.\n", config_line);
      boot_exit (1);
    }
/* Check for duplicate label or name */
  for (room = room_first[dimension]; room != NULL; room = room->next)
    {
      if (!strcmp (room->label, wrd[0]))
	{
	  fprintf (stderr, "GAEN: Duplicate room label on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      if (!strcmp (room->name, wrd[1]))
	{
	  fprintf (stderr, "GAEN: Duplicate room name on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
    }
  room = create_room (dimension);
  strcpy (room->label, wrd[0]);
  strcpy (room->name, wrd[1]);

/* Parse internal links bit, ie hl,gd,of etc. 
   MUST NOT be any spaces between the commas */
  i = 0;
  ptr1 = wrd[2];
  ptr2 = wrd[2];
  while (1)
    {
      while (*ptr2 != ',' && *ptr2 != '\0')
	++ptr2;
      if (*ptr2 == ',' && *(ptr2 + 1) == '\0')
	{
	  fprintf (stderr, "GAEN: Missing link label on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      c = *ptr2;
      *ptr2 = '\0';
      if (!strcmp (ptr1, room->label))
	{
	  fprintf (stderr, "GAEN: Room has a link to itself on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      strcpy (room->link_label[i], ptr1);
      if (c == '\0')
	break;
      if (++i >= MAX_LINKS)
	{
	  fprintf (stderr, "GAEN: Too many links on line %d.\n", config_line);
	  boot_exit (1);
	}
      *ptr2 = c;
      ptr1 = ++ptr2;
    }

/* Parse access privs */
  if (wrd[3][0] == '#')
    {
      room->access = PUBLIC;
      return;
    }
  if (!wrd[3][0] || !strcmp (wrd[3], "BOTH"))
    room->access = PUBLIC;
  else if (!strcmp (wrd[3], "PUB"))
    room->access = FIXED_PUBLIC;
  else if (!strcmp (wrd[3], "PRIV"))
    room->access = FIXED_PRIVATE;
  else
    {
      fprintf (stderr, "GAEN: Unknown room access type on line %d.\n",
	       config_line);
      boot_exit (1);
    }
/* Parse external link stuff */
  if (!wrd[4][0] || wrd[4][0] == '#')
    return;
  if (!strcmp (wrd[4], "ACCEPT"))
    {
      if (wrd[5][0] && wrd[5][0] != '#')
	{
	  fprintf (stderr,
		   "GAEN: Unexpected word following ACCEPT keyword on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      room->inlink = 1;
      return;
    }
  if (!strcmp (wrd[4], "CONNECT"))
    {
      if (!wrd[5][0])
	{
	  fprintf (stderr, "GAEN: External link name missing on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      if (wrd[6][0] && wrd[6][0] != '#')
	{
	  fprintf (stderr,
		   "GAEN: Unexpected word following external link name on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      strcpy (room->netlink_name, wrd[5]);
      return;
    }
  fprintf (stderr, "GAEN: Unknown connection option on line %d.\n",
	   config_line);
  boot_exit (1);
}



/*** Parse sites section ***/
parse_sites_section ()
{
  NL_OBJECT nl;
  static int in_section = 0;

  if (!strcmp (wrd[0], "SITES:"))
    {
      if (++in_section > 1)
	{
	  fprintf (stderr,
		   "GAEN: Unexpected SITES section header on line %d.\n",
		   config_line);
	  boot_exit (1);
	}
      return;
    }
  if (!wrd[3][0])
    {
      fprintf (stderr, "GAEN: Required parameter(s) missing on line %d.\n",
	       config_line);
      boot_exit (1);
    }
  if (strlen (wrd[0]) > SERV_NAME_LEN)
    {
      fprintf (stderr, "GAEN: Link name length too long on line %d.\n",
	       config_line);
      boot_exit (1);
    }
  if (strlen (wrd[3]) > SERV_NAME_LEN)
    {
      fprintf (stderr, "GAEN: Verification too long on line %d.\n",
	       config_line);
      boot_exit (1);
    }
  if ((nl = create_netlink ()) == NULL)
    {
      fprintf (stderr,
	       "GAEN: Memory allocation failure creating netlink on line %d.\n",
	       config_line);
      boot_exit (1);
    }
  if (!wrd[4][0] || wrd[4][0] == '#' || !strcmp (wrd[4], "ALL"))
    nl->allow = ALL;
  else if (!strcmp (wrd[4], "IN"))
    nl->allow = IN;
  else if (!strcmp (wrd[4], "OUT"))
    nl->allow = OUT;
  else
    {
      fprintf (stderr, "GAEN: Unknown netlink access type on line %d.\n",
	       config_line);
      boot_exit (1);
    }
  if ((nl->port = atoi (wrd[2])) < 1 || nl->port > 65535)
    {
      fprintf (stderr, "GAEN: Illegal port number on line %d.\n",
	       config_line);
      boot_exit (1);
    }
  strcpy (nl->service, wrd[0]);
  strtolower (wrd[1]);
  strcpy (nl->site, wrd[1]);
  strcpy (nl->verification, wrd[3]);
}

/*** Load swear words list from file ***/
load_swear_file (user)
     UR_OBJECT user;
{
  FILE *fp;
  char filename[80], line[WORD_LEN + 1];
  int i = 0;

  sprintf (filename, "%s/%s", DATAFILES, SWEARFILE);
  if (user == NULL)
    printf ("Loading swear words file \"%s\"...", filename);
  else
    write_user (user, ">>>Loading swear words file...");
  if (!(fp = fopen (filename, "r")))
    {
      strcpy (swear_words[0], "*");
      if (user == NULL)
	printf (" not found.\n");
      else
	write_user (user, " not found.\n");
      return;
    }
  fgets (line, WORD_LEN + 2, fp);
  while (!feof (fp))
    {
      line[strlen (line) - 1] = '\0';
      strcpy (swear_words[i], line);
      if (user == NULL)
	printf (" '%s'", swear_words[i]);
      else
	{
	  sprintf (text, " '%s'", swear_words[i]);
	  write_user (user, text);
	}
      i++;
      if (i >= MAX_SWEARS)
	break;
      fgets (line, WORD_LEN + 2, fp);
    }
  fclose (fp);
  strcpy (swear_words[i], "*");
  if (user == NULL)
    printf (" done (%d words).\n", i);
  else
    {
      sprintf (text, " done (~FT%d~RS words).\n", i);
      write_user (user, text);
    }
}

yn_check (wd)
     char *wd;
{
  if (!strcmp (wd, "YES"))
    return 1;
  if (!strcmp (wd, "NO"))
    return 0;
  return -1;
}


onoff_check (wd)
     char *wd;
{
  if (!strcmp (wd, "ON"))
    return 1;
  if (!strcmp (wd, "OFF"))
    return 0;
  return -1;
}


/************ INITIALISATION FUNCTIONS *************/

/*** Initialise globals ***/
init_globals ()
{
  int i;
  verification[0] = '\0';
  port[0] = 0;
  port[1] = 0;
  port[2] = 0;
  auto_connect = 1;
  max_users = 50;
  max_clones = 1;
  ban_swearing = 0;
  heartbeat = 2;
  keepalive_interval = 60;	/* DO NOT TOUCH!!! */
  net_idle_time = 300;		/* Must be > than the above */
  login_idle_time = 180;
  user_idle_time = 300;
  time_out_afks = 0;
  stport_level = SPIRIT;
  newuser_deflevel = GUEST;
  minlogin_level = -1;
  mesg_life = 1;
  no_prompt = 0;
  num_of_users = 0;
  num_of_logins = 0;
  for (i = 0; i < MAX_LOGS; i++)
    system_logging[i] = 1;
  password_echo = 0;
  ignore_sigterm = 0;
  crash_action = 2;
  prompt_def = 1;
  colour_def = 1;
  mesg_check_hour = 0;
  mesg_check_min = 0;
  allow_caps_in_name = 1;
  rs_countdown = 0;
  rs_announce = 0;
  rs_which = -1;
  rs_user = NULL;
  gatecrash_level = GOD;	/* minimum user level which can enter private rooms */
  min_private_users = 2;	/* minimum num. of users in room before can set to priv */
  ignore_mp_level = GOD;	/* user level which can ignore the above var. */
  rem_user_maxlevel = SOUL;
  rem_user_deflevel = SOUL;
  user_first = NULL;
  user_last = NULL;
  for (i = 0; i < MAX_DIMENS; i++)
    {
      room_first[i] = NULL;
      room_last[i] = NULL;	/* This variable isn't used yet */
    }
  clear_watch ();
  nl_first = NULL;
  nl_last = NULL;
  autosave_counter = 0;
  autosave_maxiter = AUTOSAVE_MAXITER;
  autosave_action = AS_ALL;
  max_quotes = MAX_QUOTES;
  max_hints = MAX_HINTS;
  prayer_number = 0;
  use_hostsfile = 0;
  mirror = 1;
  for (i = 0; i <= MAX_LEVELS; i++)	/* invisibility ... */
    strcpy (level_name[i], level_name_mirror[mirror][i]);
  strcpy (invisname, "A digit");
  strcpy (invisenter, "~FT>>>A digit enters the sky...\n");
  strcpy (invisleave, "~FT>>>A digit leaves the sky...\n");
  no_disable_mirror = 0;
  cnt_in = 0;
  cnt_out = 0;
  cnt_swp = 0;
  safety = 0;
  if (getcwd (homedir, SITE_NAME_LEN) == NULL)
    {
      printf ("Warning! Cannot get talker's home directory.\n");
      write_syslog (LOG_CHAT,
		    "Warning! Cannot get talker's home directory.\n",
		    LOG_NOTIME);
      write_syslog (LOG_ERR, "Warning! Cannot get talker's home directory.\n",
		    LOG_NOTIME);
    }
  event = E_NONE;
  enable_event = 1;
  enable_rndgo = 1;
  strcpy (event_var, "*");
  clear_words ();
  for (i = 0; i <= MAX_SWEARS; i++)
    swear_words[i][0] = '\0';
  gm_max_words = GM_MAX_WORDS;
  exec_gshell = 1;
  def_lines = DEF_LINES;
  timeout_maxlevel = SPIRIT;
  def_pballs = GM_MAX_PBALLS;
  chk_spass_tests = CHK_SPASS_ALL;
  strcpy (utmpfile, UTMPFILE);
  strcpy (wtmpfile, WTMPFILE);
  strcpy (susers_restrict, RESTRICT_MASK);
  id_readtimeout = ID_READTIMEOUT;
  random_bhole = 1;
  prelog_msgs = MAX_PRELOG_MSGS;
  wrap_cols = WRAP_COLS;
  hint_at_help = 1;
  emote_spacer = 1;
  accept_prelog_comm = 1;
  allow_born_maxlev = 1;

/* set time and random seed */
  time (&boot_time);
  srandom (boot_time);
}


/*** Initialise the signal traps etc ***/
init_signals ()
{
  void sig_handler ();

  signal (SIGTERM, sig_handler);
  signal (SIGSEGV, sig_handler);
  signal (SIGBUS, sig_handler);
  signal (SIGILL, SIG_IGN);
  signal (SIGTRAP, SIG_IGN);
  signal (SIGIOT, SIG_IGN);
  signal (SIGTSTP, SIG_IGN);
  signal (SIGCONT, SIG_IGN);
  signal (SIGHUP, SIG_IGN);
  signal (SIGINT, SIG_IGN);
  signal (SIGQUIT, SIG_IGN);
  signal (SIGABRT, SIG_IGN);
  signal (SIGFPE, SIG_IGN);
/*signal (SIGURG, SIG_IGN);*/
  signal (SIGPIPE, SIG_IGN);
  signal (SIGTTIN, SIG_IGN);
  signal (SIGTTOU, SIG_IGN);
}

/*** Some signal trapping functions ***/

void
sig_handler (sig)
     int sig;
{
  force_listen = 1;
  switch (sig)
    {
    case SIGTERM:
      if (ignore_sigterm)
	{
	  write_syslog (LOG_CHAT, "SIGTERM signal received - ignoring.\n",
			LOG_TIME);
	  return;
	}
      write_room (NULL,
		  "\n\n~OLGAEN:~FY~LI SIGTERM recieved, initiating shutdown.\n\n");
      talker_shutdown (NULL, "a termination signal (SIGTERM)", 0);

    case SIGSEGV:
      sprintf (text, "Last command: %s (%d)\n", command[com_num], com_num);
      write_syslog (LOG_CHAT, text, LOG_TIME);
      switch (crash_action)
	{
	case 0:
	  write_room (NULL,
		      "\n\n\07~OLGAEN:~FR~LI PANIC - Segmentation fault, initiating shutdown! Return later...\n\n");
	  talker_shutdown (NULL, "a segmentation fault (SIGSEGV)", 0);

	case 1:
	  write_room (NULL,
		      "\n\n\07~OLGAEN:~FR~LI WARNING - A segmentation fault has just occured!\n\n");
	  write_syslog (LOG_CHAT, "WARNING: A segmentation fault occured!\n",
			LOG_TIME);
	  longjmp (jmpvar, 0);

	case 2:
	  write_room (NULL,
		      "\n\n\07~OLGAEN:~FR~LI PANIC - Segmentation fault, initiating reboot! Return later...\n\n");
	  talker_shutdown (NULL, "a segmentation fault (SIGSEGV)", 1);
	}

    case SIGBUS:
      sprintf (text, "Last command: %s (%d)\n", command[com_num], com_num);
      write_syslog (LOG_CHAT, text, LOG_TIME);
      switch (crash_action)
	{
	case 0:
	  write_room (NULL,
		      "\n\n\07~OLGAEN:~FR~LI PANIC - Bus error, initiating shutdown! Return later...\n\n");
	  talker_shutdown (NULL, "a bus error (SIGBUS)", 0);

	case 1:
	  write_room (NULL,
		      "\n\n\07~OLGAEN:~FR~LI WARNING - A bus error has just occured!\n\n");
	  write_syslog (LOG_CHAT, "WARNING: A bus error occured!\n",
			LOG_TIME);
	  longjmp (jmpvar, 0);

	case 2:
	  write_room (NULL,
		      "\n\n\07~OLGAEN:~FR~LI PANIC - Bus error, initiating reboot! Return later...\n\n");
	  talker_shutdown (NULL, "a bus error (SIGBUS)", 1);
	}
    }
}


/*** Initialise sockets on ports ***/
init_sockets ()
{
  struct sockaddr_in bind_addr;
  int i, on, size;

  printf ("Initialising sockets on ports: %d, %d, %d.\n", port[0], port[1],
	  port[2]);
  on = 1;
  size = sizeof (struct sockaddr_in);
  bind_addr.sin_family = AF_INET;
  bind_addr.sin_addr.s_addr = INADDR_ANY;
  for (i = 0; i < 3; ++i)
    {
      /* create sockets */
      if ((listen_sock[i] = socket (AF_INET, SOCK_STREAM, 0)) == -1)
	boot_exit (i + 2);

      /* allow reboots on port even with TIME_WAITS */
      setsockopt (listen_sock[i], SOL_SOCKET, SO_REUSEADDR, (char *) &on,
		  sizeof (on));

      /* bind sockets and set up listen queues */
      bind_addr.sin_port = htons (port[i]);
      if (bind (listen_sock[i], (struct sockaddr *) &bind_addr, size) == -1)
	boot_exit (i + 5);
      if (listen (listen_sock[i], 10) == -1)
	boot_exit (i + 8);

      /* Set to non-blocking , do we need this? not really */
      fcntl (listen_sock[i], F_SETFL, O_NDELAY);
    }
}

/*** Initialise connections to remote servers. Basically this does all the
     client shit which creates standard sockets in the NL_OBJECT linked list
     which the talker then uses ***/
init_connections ()
{
  NL_OBJECT nl;
  RM_OBJECT rm;
  int i, ret, cnt = 0;

  printf ("Connecting to remote servers...\n");
  errno = 0;
  for (i = 0; i < MAX_DIMENS; i++)
    for (rm = room_first[i]; rm != NULL; rm = rm->next)
      {
	if ((nl = rm->netlink) == NULL)
	  continue;
	++cnt;
	printf ("  Trying service %s at %s %d: ", nl->service, nl->site,
		nl->port);
	fflush (stdout);
	if ((ret = connect_to_site (nl)))
	  {
	    if (ret == 1)
	      {
		printf ("%s.\n", sys_errlist[errno]);
		sprintf (text, "NETLINK: Failed to connect to %s: %s.\n",
			 nl->service, sys_errlist[errno]);
	      }
	    else
	      {
		printf ("Unknown hostname.\n");
		sprintf (text,
			 "NETLINK: Failed to connect to %s: Unknown hostname.\n",
			 nl->service);
	      }
	    write_syslog (LOG_LINK, text, LOG_TIME);
	  }
	else
	  {
	    printf ("CONNECTED.\n");
	    sprintf (text, "NETLINK: Connected to %s (%s %d).\n",
		     nl->service, nl->site, nl->port);
	    write_syslog (LOG_LINK, text, LOG_TIME);
	    nl->connect_room = rm;
	  }
      }
  if (cnt)
    printf
      ("  See system log (in '%s' directory) for any further information.\n",
       LOGFILES);
  else
    printf ("  No remote connections configured.\n");
}

/*** Do the actual connection ***/
connect_to_site (nl)
     NL_OBJECT nl;
{
  struct sockaddr_in con_addr;
  struct hostent *he;
  int inetnum;
  char *sn;

  sn = nl->site;
/* See if number address */
  while (*sn && (*sn == '.' || isdigit (*sn)))
    sn++;

/* Name address given */
  if (*sn)
    {
      if (!(he = gethostbyname (nl->site)))
	return 2;
      memcpy ((char *) &con_addr.sin_addr, he->h_addr, (size_t) he->h_length);
    }
/* Number address given */
  else
    {
      if ((inetnum = inet_addr (nl->site)) == -1)
	return 1;
      memcpy ((char *) &con_addr.sin_addr, (char *) &inetnum,
	      (size_t) sizeof (inetnum));
    }
/* Set up stuff and disable interrupts */
  if ((nl->socket = socket (AF_INET, SOCK_STREAM, 0)) == -1)
    return 1;
  con_addr.sin_family = AF_INET;
  con_addr.sin_port = htons (nl->port);
  signal (SIGALRM, SIG_IGN);

/* Attempt the connect. This is where the talker may hang. */
  if (connect (nl->socket, (struct sockaddr *) &con_addr, sizeof (con_addr))
      == -1)
    {
      reset_alarm ();
      return 1;
    }
  reset_alarm ();
  nl->type = OUTGOING;
  nl->stage = VERIFYING;
  nl->last_recvd = time (0);
  return 0;
}

/************* WRITE FUNCTIONS ************/

/*** Write a NULL terminated string to a socket ***/
write_sock (sock, str)
     int sock;
     char *str;
{
  write (sock, str, strlen (str));
}


/*** Send message to user ***/
write_user (user, str)
     UR_OBJECT user;
     char *str;
{
  int buffpos, sock, i, cnt, wrapping;
  char *start, buff[OUT_BUFF_SIZE], mesg[ARR_SIZE], *colour_com_strip ();

  if (user == NULL)
    return;
  if (user->blind)
    return;
  if (user->type == REMOTE_TYPE)
    {
      if (user->netlink->ver_major <= 3 && user->netlink->ver_minor < 2)
	str = colour_com_strip (str);
      if (str[strlen (str) - 1] != '\n')
	sprintf (mesg, "MSG %s\n%s\nEMSG\n", user->savename, str);
      else
	sprintf (mesg, "MSG %s\n%sEMSG\n", user->savename, str);
      write_sock (user->netlink->socket, mesg);
      return;
    }
  start = str;
  buffpos = 0;
  sock = user->socket;
/* Process string and write to buffer. We use pointers here instead of arrays 
   since these are supposedly much faster (though in reality I guess it depends
   on the compiler) which is necessary since this routine is used all the 
   time. */
  cnt = 0;
  wrapping = 0;
  while (*str)
    {
      if (*str == '\n')
	{
	  if (wrapping)
	    {
	      wrapping = 0;
	      ++str;
	    }
	  else
	    {
	      if (buffpos > OUT_BUFF_SIZE - 6)
		{
		  write (sock, buff, buffpos);
		  buffpos = 0;
		}
	      /* Reset terminal before every newline */
	      if (user->colour % 2)
		{
		  memcpy (buff + buffpos, "\033[0m", 4);
		  buffpos += 4;
		}
	      *(buff + buffpos) = '\n';
	      *(buff + buffpos + 1) = '\r';
	      buffpos += 2;
	      ++str;
	      cnt = 0;
	    }
	}
      else if (*str == '\b')
	{
	  if (wrapping)
	    {
	      *(buff + buffpos) = '\b';
	      ++buffpos;
	    }
	  ++str;
	  --cnt;
	}
      else if (user->wrap && cnt == wrap_cols)
	{
	  if (buffpos > OUT_BUFF_SIZE - 2)
	    {
	      write (sock, buff, buffpos);
	      buffpos = 0;
	    }
	  *(buff + buffpos) = '\n';
	  *(buff + buffpos + 1) = '\r';
	  buffpos += 2;
	  cnt = 0;
	  wrapping = 1;
	}
      else
	{
	  /* See if its a / before a ~ , if so then we print colour command
	     as text */
	  if (*str == '/' && *(str + 1) == '~')
	    {
	      ++str;
	      continue;
	    }
	  if (str > start && *str == '~' && *(str - 1) == '/')
	    {
	      *(buff + buffpos) = *str;
	      wrapping = 0;
	      goto CONT;
	    }
	  /* Process colour commands eg ~FR. We have to strip out the commands 
	     from the string even if user doesnt have colour switched on hence 
	     the user->colour check isnt done just yet */
	  if (*str == '~')
	    {
	      if (buffpos > OUT_BUFF_SIZE - 6)
		{
		  write (sock, buff, buffpos);
		  buffpos = 0;
		}
	      ++str;
	      for (i = 0; i < NUM_COLS; ++i)
		{
		  if (!strncmp (str, colcom[i], 2))
		    {
		      if (user->colour % 2)
			{
			  memcpy (buff + buffpos, colcode[i],
				  strlen (colcode[i]));
			  buffpos += strlen (colcode[i]) - 1;
			}
		      else
			buffpos--;
		      ++str;
		      --cnt;
		      goto CONT;
		    }
		}
	      *(buff + buffpos) = *(--str);
	      wrapping = 0;
	    }
	  else
	    *(buff + buffpos) = *str;
	  wrapping = 0;
	CONT:
	  ++buffpos;
	  ++str;
	  ++cnt;
	}
      if (buffpos == OUT_BUFF_SIZE)
	{
	  write (sock, buff, OUT_BUFF_SIZE);
	  buffpos = 0;
	}
    }
  if (buffpos)
    write (sock, buff, buffpos);
/* Reset terminal at end of string */
  if (user->colour % 2)
    write_sock (sock, "\033[0m");
}

/*** Write to users of level 'level' and above. ***/
write_level (level, str, user)
     int level;
     char *str;
     UR_OBJECT user;
{
  UR_OBJECT u;

  for (u = user_first; u != NULL; u = u->next)
    {
      if (u != user && u->level >= level &&
	  !u->login && u->type != CLONE_TYPE)
	write_user (u, str);
    }
}



/*** Subsid function to below but this one is used the most ***/
write_room (rm, str)
     UR_OBJECT rm;
     char *str;
{
  write_room_except (rm, str, NULL);
}



/*** Write to everyone in room rm except for "user". If rm is NULL write
     to all rooms. ***/
write_room_except (rm, str, user)
     RM_OBJECT rm;
     char *str;
     UR_OBJECT user;
{
  UR_OBJECT u;
  char text2[ARR_SIZE];

  for (u = user_first; u != NULL; u = u->next)
    {
      if (u->login
	  || u->room == NULL
	  || (u->room != rm && rm != NULL)
	  || (u->ignall && !force_listen)
	  || (u->ignshout &&
	      (com_num == SHOUT || com_num == MSHOUT || com_num == SEMOTE))
	  || u == user || is_ignoring (u, user))
	continue;
      if (u->type == CLONE_TYPE)
	{
	  if (u->clone_hear == CLONE_HEAR_NOTHING || u->owner->ignall)
	    continue;
	  /* Ignore anything not in clones room, eg shouts, system messages
	     and semotes since the clones owner will hear them anyway. */
	  if (rm != u->room)
	    continue;

	  if (is_ignoring (u->owner, user))
	    continue;

	  if (u->clone_hear == CLONE_HEAR_SWEARS)
	    {
	      if (!contains_swearing (str))
		continue;
	    }
	  sprintf (text2, "~FT[ %s ]:~RS %s", u->room->name, str);
	  write_user (u->owner, text2);
	}
      else
	write_user (u, str);
    }
}


/*** Write a string to system logs ***/
write_syslog (type, str, write_time)
     int type;
     char *str;
     int write_time;
{
  FILE *fp;
  char filename[80];

  sprintf (filename, "%s/%s.%s", LOGFILES, SYSLOG, logtype[type]);

  if (!system_logging[type] || !(fp = fopen (filename, "a")))
    return;
  if (write_time == LOG_NOTIME)
    fputs (str, fp);
  else
    fprintf (fp, "%02d-%02d %02d:%02d:%02d: %s",
	     tmday, tmonth + 1, thour, tmin, tsec, str);
  fclose (fp);
}

/*** Write usage of a command ***/
write_usage (user, msg)
     UR_OBJECT user;
     char *msg;
{
  sprintf (text, ">>>Usage: ~FT%s\n", msg);
  write_user (user, text);
}


/******** LOGIN/LOGOUT FUNCTIONS ********/

/*** Login function - all mostly inline code ***/
login_user (user, inpstr)
     UR_OBJECT user;
     char *inpstr;
{
  UR_OBJECT u;
  int i;
  char name[ARR_SIZE], passwd[ARR_SIZE];

  name[0] = '\0';
  passwd[0] = '\0';
  switch (user->login)
    {
    case 3:
      sscanf (inpstr, "%s", name);
      if (name[0] < 33)
	{
	  write_user (user, "\n");
	  write_user (user, DEF_NAME_MSG);
	  return;
	}
      if (!strcmp (name, "quit"))
	{
	  if (!accept_prelog_comm)
	    {
	      write_user (user, NOPRELOG_MSG);
	      disconnect_user (user);
	      return;
	    }
	  write_user (user, "\n\n--->>> Abandoning login attempt <<<---\n\n");
	  disconnect_user (user);
	  return;
	}
      if (!strcmp (name, "who"))
	{
	  if (!accept_prelog_comm)
	    {
	      write_user (user, NOPRELOG_MSG);
	      disconnect_user (user);
	      return;
	    }
	  who (user, LIST_WHO);
	  write_user (user, "\n");
	  write_user (user, DEF_NAME_MSG);
	  return;
	}
      if (accept_prelog_comm && !strcmp (name, "version"))
	{
	  if (!accept_prelog_comm)
	    {
	      write_user (user, NOPRELOG_MSG);
	      disconnect_user (user);
	      return;
	    }
	  version (user);
	  write_user (user, "\n");
	  write_user (user, DEF_NAME_MSG);
	  return;
	}
      if (accept_prelog_comm && !strcmp (name, "quote"))
	{
	  if (!accept_prelog_comm)
	    {
	      write_user (user, NOPRELOG_MSG);
	      disconnect_user (user);
	      return;
	    }
	  quote (user, 0);
	  write_user (user, "\n");
	  write_user (user, DEF_NAME_MSG);
	  return;
	}
      if (strlen (name) < USER_MIN_LEN)
	{
	  write_user (user, "\n>>>Name too short.\n\n");
	  attempts (user);
	  return;
	}
      if (strlen (name) > USER_NAME_LEN)
	{
	  write_user (user, "\n>>>Name too long.\n\n");
	  attempts (user);
	  return;
	}
      /* see if only letters in login */
      for (i = 0; i < strlen (name); ++i)
	{
	  if (!isalpha (name[i]))
	    {
	      write_user (user,
			  "\n>>>Only letters are allowed in a name.\n\n");
	      attempts (user);
	      return;
	    }
	}
      if (!allow_caps_in_name)
	strtolower (name);
      name[0] = toupper (name[0]);
      if (user_banned (name))
	{
	  write_user (user, "\n>>>You are banned from this talker.\n\n");
	  disconnect_user (user);
	  sprintf (text, "~OLGAEN:~RS Attempted login by banned user %s.\n",
		   name);
	  write_syslog (LOG_CHAT, text, LOG_TIME);
	  write_level (MIN_LEV_NOTIFY, text, NULL);
	  return;
	}
      strcpy (user->name, name);
      strcpy (user->savename, name);
      /* If user has hung on another login clear that session */
      for (u = user_first; u != NULL; u = u->next)
	{
	  if (u->login && u != user && !strcmp (u->savename, user->savename))
	    {
	      disconnect_user (u);
	      break;
	    }
	}
      if (!load_user_details (user))
	{
	  if (user->port == port[1])
	    {
	      write_user (user,
			  "\n>>>Sorry, new logins cannot be created on this port.\n\n");
	      sprintf (text,
		       "~OLGAEN:~RS Attempt to create new user %s from %s on port %d.\n",
		       user->savename, user->site, port[1]);
	      write_syslog (LOG_CHAT, text, LOG_TIME);
	      more (user, user->socket, NEWLOG_MSG);
	      disconnect_user (user);
	      return;
	    }
	  if (minlogin_level > -1)
	    {
	      write_user (user,
			  "\n>>>Sorry, new logins cannot be created at this time.\n\n");
	      sprintf (text,
		       "~OLGAEN:~RS Attempt to create new user %s from %s on port %d since minlogin was greater than NONE.\n",
		       user->savename, user->site, port[0]);
	      write_syslog (LOG_CHAT, text, LOG_TIME);
	      more (user, user->socket, MINLOG_MSG);
	      disconnect_user (user);
	      return;
	    }
	  write_user (user, ">>>New user...\n");
	}
      else
	{
	  if (user->port == port[1] && user->level < stport_level)
	    {
	      sprintf (text,
		       "\n>>>Sorry, only users of level %s~RS and above can log in on this port.\n\n",
		       level_name[stport_level]);
	      write_user (user, text);
	      sprintf (text,
		       "~OLGAEN:~RS Attempt to connect user %s from %s with level below stport_level.\n",
		       user->savename, user->site);
	      write_syslog (LOG_CHAT, text, LOG_TIME);
	      write_level (MIN_LEV_NOTIFY, text, NULL);
	      more (user, user->socket, STPORT_MSG);
	      disconnect_user (user);
	      return;
	    }
	  if (user->level < minlogin_level)
	    {
	      write_user (user,
			  "\n>>>Sorry, the talker is locked out to users of your level. Return later...\n\n");
	      sprintf (text,
		       "~OLGAEN:~RS Attempt to connect user %s from %s with level below minlogin_level.\n",
		       user->savename, user->site);
	      write_syslog (LOG_CHAT, text, LOG_TIME);
	      write_level (MIN_LEV_NOTIFY, text, NULL);
	      disconnect_user (user);
	      more (user, user->socket, MINLOG_MSG);
	      return;
	    }
	}
      switch (random () % MAX_MAINPHR)	/* write login extra phrases */
	{
	case 0:
	  sprintf (text, "%s'%s %s! :-)'\n",
		   prelog_msg, prefix_login_phr[0],
		   login_phr1[random () % MAX_PHR1]);
	  break;
	case 1:
	  sprintf (text, "%s'%s %s! :-)'\n",
		   prelog_msg, prefix_login_phr[1],
		   login_phr2[random () % MAX_PHR2]);
	  break;
	case 2:
	  sprintf (text, "%s'%s %s! :-)'\n",
		   prelog_msg, prefix_login_phr[2],
		   login_phr3[random () % MAX_PHR3]);
	}
      write_user (user, text);
      write_user (user, enter_pass);
      echo_off (user);
      user->login = 2;
      return;

    case 2:
      sscanf (inpstr, "%s", passwd);
      if (strlen (passwd) < PASS_MIN_LEN)
	{
	  write_user (user, "\n\n>>>Password too short.\n\n");
	  attempts (user);
	  return;
	}
      if (strlen (passwd) > PASS_MAX_LEN)
	{
	  write_user (user, "\n\n>>>Password too long.\n\n");
	  attempts (user);
	  return;
	}
      /* if new user... */

      if (!user->pass[0])
	{
	  if (!secure_pass (passwd))	/* check password */
	    {
	      write_user (user,
			  "\n\n>>>Password too simple, try to use special characters, please.\n\n");
	      attempts (user);
	      return;
	    }
	  strcpy (user->pass, (char *) crypt (passwd, PASS_SALT));
	  write_user (user, "\n>>>Please confirm password: ");
	  user->login = 1;
	}
      else
	{
	  if (!strcmp (user->pass, (char *) crypt (passwd, PASS_SALT)))
	    {
	      echo_on (user);
	      connect_user (user);
	      if (!secure_pass (passwd))
		write_user (user,
			    "\n\n~EL~EL~FR~OL~LI>>>Warning! Your password is not secure! Please, change it!\n~FR~OL~LI>>>Use a combination of letters, digits and special characters.\n");
	      return;
	    }
	  write_user (user, "\n\n>>>Incorrect login! :-(\n\n");
	  attempts (user);
	}
      return;

    case 1:
      sscanf (inpstr, "%s", passwd);
      if (strcmp (user->pass, (char *) crypt (passwd, PASS_SALT)))
	{
	  write_user (user,
		      "\n\n>>>Passwords do not match. Sorry... :-(\n\n");
	  attempts (user);
	  return;
	}
      echo_on (user);
      strcpy (user->desc, DEF_DESC);
      strcpy (user->in_phrase, "enters");
      strcpy (user->out_phrase, "goes");
      user->last_site[0] = '\0';
      user->dimension = 0;
      user->level = newuser_deflevel;
      user->prompt = prompt_def;
      user->charmode_echo = 0;
      user->afkmesg[0] = '\0';
      user->slevel = newuser_deflevel;
      strcpy (user->ssite, user->site);
      strcpy (user->restrict, RESTRICT_MASK);
      save_user_details (user, 1);
      sprintf (text, "New user %s from %s created.\n",
	       user->savename, user->site);
      write_syslog (LOG_CHAT, text, LOG_TIME);
      connect_user (user);
    }
}

/*** Count up attempts made by user to login ***/
attempts (user)
     UR_OBJECT user;
{

  user->attempts++;
  if (user->attempts == MAX_ATTEMPTS)
    {
      write_user (user, "\n>>>Maximum attempts reached. Sorry...\n\n");
      disconnect_user (user);
      return;
    }
  user->login = 3;
  user->pass[0] = '\0';
  write_user (user, DEF_NAME_MSG);
  echo_on (user);
}


/*** Load the users stats ***/
load_user_details (user)
     UR_OBJECT user;
{
  FILE *fp;
  char line[81], filename[80];
  int temp1, temp2, temp3, i;

  sprintf (filename, "%s/%s.D", USERFILES, user->savename);
  if (!(fp = fopen (filename, "r")))
    return 0;
  fscanf (fp, "%s", user->pass);	/* password */
  fscanf (fp, "%d %d %d %d %d %d %d %d %d %d",
	  &temp1, &temp2, &user->last_login_len, &temp3,
	  &user->level, &user->prompt, &user->muzzled,
	  &user->charmode_echo, &user->command_mode, &user->colour);
  user->last_login = (time_t) temp1;
  user->total_login = (time_t) temp2;
  user->read_mail = (time_t) temp3;
  fscanf (fp, "%s\n", user->last_site);

/* Some verifications */
  if (user->level < GUEST || user->level > SGOD)
    user->level = newuser_deflevel;
  if (user->muzzled < GUEST || user->muzzled > SGOD)
    user->muzzled = GUEST;

/* Need to do the rest like this 'cos they may be more than 1 word each */
  fgets (line, USER_DESC_LEN + 2, fp);
  line[strlen (line) - 1] = 0;
  strcpy (user->desc, line);
  fgets (line, PHRASE_LEN + 2, fp);
  line[strlen (line) - 1] = 0;
  strcpy (user->in_phrase, line);
  fgets (line, PHRASE_LEN + 2, fp);
  line[strlen (line) - 1] = 0;
  strcpy (user->out_phrase, line);
  fclose (fp);
  sprintf (filename, "%s/%s.S", USERFILES, user->savename);	/* load subst file */
  if (!(fp = fopen (filename, "r")))
    {
      user->slevel = user->level;
      strcpy (user->ssite, user->site);
      user->subst = 0;
    }
  else
    {
      fgets (line, SITE_NAME_LEN + 2, fp);
      line[strlen (line) - 1] = 0;
      strcpy (user->ssite, line);
      fscanf (fp, "%d", &user->slevel);
      if (user->slevel < GUEST || user->slevel > SGOD)
	user->slevel = GUEST;
      user->subst = 1;
      fclose (fp);
    }
  if (user->slevel > SGOD)
    user->slevel = GUEST;
  sprintf (filename, "%s/%s.R", USERFILES, user->savename);	/* load restrict file */
  if (!(fp = fopen (filename, "r")))
    strcpy (user->restrict, RESTRICT_MASK);
  else
    {
      fgets (line, MAX_RESTRICT + 2, fp);
      line[strlen (line) - 1] = 0;
      strcpy (user->restrict, line);
      fclose (fp);
    }
  if (user->socket < 0)
    return 1;			/* don't want to check virtual 
				   users created by some functions */
  temp1 = 0;
  while (max_level_users[temp1][0] != '*')
    {
      if (!strcmp (user->savename, max_level_users[temp1]))
	{
	  user->level = SGOD;
	  return 1;
	}
      temp1++;
    }
/* check allow */
  for (i = MAX_LEV_ALLOW; i >= MIN_LEV_ALLOW; i--)
    {
      if (!check_allow (user, i))
	{
	  user->level--;
	  sprintf (text, "~OLGAEN:~RS Allow %s~RS failed for %s\n",
		   level_name[i], user->savename);
	  write_syslog (LOG_CHAT, text, LOG_TIME);
	  write_level (MIN_LEV_NOTIFY, text, NULL);
	}
    }
  return 1;
}

/*** Save an users stats ***/
save_user_details (user, save_current)
     UR_OBJECT user;
     int save_current;
{
  FILE *fp;
  char filename[80];
  int i;

  if (user->type == REMOTE_TYPE || user->type == CLONE_TYPE)
    return 0;
  sprintf (filename, "%s/%s.D", USERFILES, user->savename);
  if (!(fp = fopen (filename, "w")))
    {
      sprintf (text, ">>>%s: failed to save your details.\n", syserror);
      write_user (user, text);
      sprintf (text, "SAVE_USER_STATS: Failed to save %s's details.\n",
	       user->savename);
      write_syslog (LOG_ERR, text, LOG_TIME);
      sprintf (text, "\07~OLGAEN:~RS Failed to save %s's details!\n",
	       user->savename);
      write_level (MIN_LEV_NOTIFY, text, NULL);
      return 0;
    }
/* Insurance against any odd values so we dont crash. Shouldnt be needed if
   there are no bugs but it does no harm to have. */
  if (user->level < GUEST)
    user->level = newuser_deflevel;
  if (user->level > SGOD)
    user->level = SGOD;
  if (user->muzzled < GUEST)
    user->muzzled = GUEST;
  if (user->muzzled > SGOD)
    user->muzzled = SGOD;
  fprintf (fp, "%s\n", user->pass);
  if (save_current)
    fprintf (fp, "%d %d %d ",
	     (int) time (0), (int) user->total_login,
	     (int) (time (0) - user->last_login));
  else
    fprintf (fp, "%d %d %d ", (int) user->last_login, (int) user->total_login,
	     user->last_login_len);
  fprintf (fp, "%d %d %d %d %d %d %d\n", (int) user->read_mail, user->level,
	   user->prompt, user->muzzled, user->charmode_echo,
	   user->command_mode, user->colour);
  if (save_current)
    fprintf (fp, "%s\n", user->site);
  else
    fprintf (fp, "%s\n", user->last_site);
  fprintf (fp, "%s\n", user->desc);
  fprintf (fp, "%s\n", user->in_phrase);
  fprintf (fp, "%s\n", user->out_phrase);
  fclose (fp);
  sprintf (filename, "%s/%s.R", USERFILES, user->savename);	/* save restrictions file */
  if (!(fp = fopen (filename, "w")))
    {
      sprintf (text, ">>>%s: failed to save your restrictions.\n", syserror);
      write_user (user, text);
      sprintf (text, "SAVE_USER_STATS: Failed to save %s's restrictions.\n",
	       user->savename);
      write_syslog (LOG_ERR, text, LOG_TIME);
      return 0;
    }
  if (user->level >= MIN_LEV_AUTORST)	/* set default restriction for superior users */
    {
      for (i = 0; i < strlen (susers_restrict); i++)
	if (susers_restrict[i] != '.')
	  user->restrict[i] = susers_restrict[i];
    }
  fprintf (fp, "%s\n", user->restrict);
  fclose (fp);
  return 1;
}

/*** Connect the user to the talker proper ***/
connect_user (user)
     UR_OBJECT user;
{
  UR_OBJECT u, u2;
  RM_OBJECT rm;
  char temp[30];
  char *strrepl ();

/* See if user already connected */
  for (u = user_first; u != NULL; u = u->next)
    {
      if (user != u && user->type != CLONE_TYPE &&
	  !strcmp (user->savename, u->savename))
	{
	  rm = u->room;
	  if (u->type == REMOTE_TYPE)
	    {
	      write_user (u,
			  "\n~FB~OL>>>You are pulled back through cyberspace...\n");
	      sprintf (text, "REMVD %s\n", u->savename);
	      write_sock (u->netlink->socket, text);
	      sprintf (text, ">>>%s vanishes like an insane comet.\n",
		       u->savename);
	      destruct_user (u);
	      write_room (rm, text);
	      reset_access (rm);
	      num_of_users--;
	      break;
	    }
	  write_user (user,
		      "\n\n>>>You are already connected - switching to old session...\n");
	  sprintf (text, ">>>%s %s~RS swapped sessions (%s).\n", user->name,
		   strrepl (user->desc, "{name}", "somebody"), user->site);
	  write_room_except (NULL, text, user);
	  sprintf (text, "%s swapped sessions (%s).\n",
		   user->savename, user->site);
	  write_syslog (LOG_IO, text, LOG_TIME);
	  /* send Swap event */
	  event = E_SWAP;
	  strcpy (event_var, user->savename);
	  cnt_swp++;
	  close (u->socket);
	  u->socket = user->socket;
	  strcpy (u->site, user->site);
	  u->site_port = user->site_port;
	  strcpy (u->site, user->site);
	  u->misc_op = user->misc_op;
	  destruct_user (user);
	  num_of_logins--;
	  /* if user old session was locked, we must unlock it */
	  echo_on (u);
	  u->blind = 0;
	  u->ignall = 0;
	  /* remote... */
	  if (rm == NULL)
	    {
	      sprintf (text, "ACT %s look\n", u->savename);
	      write_sock (u->netlink->socket, text);
	    }
	  /* normal... */
	  else
	    {
	      look (u);
	      prompt (u);
	    }
	  /* Reset the sockets on any clones */
	  for (u2 = user_first; u2 != NULL; u2 = u2->next)
	    {
	      if (u2->type == CLONE_TYPE && u2->owner == user)
		{
		  u2->socket = u->socket;
		  u->owner = u;
		}
	    }
	  run_commands (u, RUNCOM_SWAP);	/* run Swap commands file */
	  return;
	}
    }

  write_user (user, "\n");
  cnt_in++;
  more (user, user->socket, POSTLOG_MSG);	/* send post-login messages */

  if (user->last_site[0])
    {
      sprintf (temp, "%s", ctime (&user->last_login));
      temp[strlen (temp) - 1] = 0;
      sprintf (text,
	       ">>>Welcome %s...\n\n~FB~OL>>>You were last logged in on %s from %s.\n\n",
	       user->name, temp, user->last_site);
    }
  else
    sprintf (text, ">>>Welcome %s...\n\n", user->name);
  write_user (user, text);

  pick_room (user);
/* check if user is transparent */
  if (!(user->level >= MIN_LEV_TRANSP && user->colour == 2))
    {
      sprintf (text,
	       "~OL~FG~EL>>>IN:~RS %s %s ~RS[%s:%d]...\n~OL~FG>>> --------- %-12s ----------------------------> (%s~RS~OL~FG?)\n",
	       user->name, strrepl (user->desc, "{name}", "somebody"),
	       user->ssite, user->site_port, user->room->name,
	       level_name[user->slevel]);
      write_room (NULL, text);
    }
  else
    {
      sprintf (text,
	       "~OL~FG~EL>>>IN:~RS %s %s ~RS[%s:%d]...(transparent)\n~OL~FG>>> --------- %-12s ----------------------------> (%s~RS~OL~FG?)\n",
	       user->name, strrepl (user->desc, "{name}", "somebody"),
	       user->ssite, user->site_port, user->room->name,
	       level_name[user->slevel]);
      write_level (SGOD, text, user);
    }
  user->last_login = time (0);	/* set to now */
  sprintf (text, "~FT>>>Your level is:~RS~OL %s\n", level_name[user->slevel]);
  write_user (user, text);
  check_watch (user);		/* check watch... */
  look (user);
  run_commands (user, RUNCOM_IN);	/* run IN commands file */
  if (has_unread_mail (user))	/* check mail */
    write_user (user, "~EL~FT~OL~LI--->>> UNREAD MAIL! <<<---\n");
  else
    mail_from (user, 1);
  prompt (user);
/* write some greetings and help messages */
  write_greetings (user);
  if (user->level <= MAX_LEV_LOGHLP)
    {
      version (user);
      write_user (user,
		  "~OLGAEN:~RS If you need help just type ~FG~OL?~RS or ~FG~OL.help~RS then press ~FG~OLENTER~RS key.\n");
      hint (user, 0);
    }
  sprintf (text, ">>>%s logged in on port %d from %s:%d.\n",
	   user->savename, user->port, user->site, user->site_port);
  write_syslog (LOG_IO, text, LOG_TIME);
  num_of_users++;
  num_of_logins--;
  user->login = 0;
/* send In event */
  event = E_IN;
  strcpy (event_var, user->savename);
}


/*** Disconnect user from talker ***/
disconnect_user (user)
     UR_OBJECT user;
{
  RM_OBJECT rm;
  NL_OBJECT nl;
  char *strrepl ();

  rm = user->room;
  if (user->login)
    {
      close (user->socket);
      destruct_user (user);
      num_of_logins--;
      return;
    }
  if (user->type != REMOTE_TYPE)
    {
      save_user_details (user, 1);
      sprintf (text, ">>>%s logged out.\n", user->savename);
      write_syslog (LOG_IO, text, LOG_TIME);
      run_commands (user, RUNCOM_OUT);	/* run OUT commands file */
      write_user (user,
		  "\n~OL~FY--->>> You are removed from this dimension... Go and sleep no more! <<<---\n\n");
      write_user (user, "\n~OL~FG>>>Thank you for using...\n");
      version (user);
      close (user->socket);
      /* check if user is transparent */
      if (!(user->level >= MIN_LEV_TRANSP && user->colour == 2))
	{
	  sprintf (text,
		   "~OL~FR<<<OUT:~RS %s %s\n~OL~FR<<< ------------------------------------------------------< going to sleep...\n",
		   user->name, strrepl (user->desc, "{name}", "somebody"));
	  write_room (NULL, text);
	}
      else
	{
	  sprintf (text,
		   "~OL~FR<<<OUT:~RS %s %s\n~OL~FR<<< ---------------------------- transparent -------------< going to sleep...\n",
		   user->name, strrepl (user->desc, "{name}", "somebody"));
	  write_level (SGOD, text, user);
	}
      /* remote ... */
      if (user->room == NULL)
	{
	  sprintf (text, "REL %s\n", user->savename);
	  write_sock (user->netlink->socket, text);
	  for (nl = nl_first; nl != NULL; nl = nl->next)
	    if (nl->mesg_user == user)
	      {
		nl->mesg_user = (UR_OBJECT) - 1;
		break;
	      }
	}
    }
  else
    {
      write_user (user,
		  "\n~FR~OL>>>You are pulled back in disgrace to your own domain...\n");
      sprintf (text, "REMVD %s\n", user->savename);
      write_sock (user->netlink->socket, text);
      sprintf (text, "~FR~OL>>>%s is banished from here!\n", user->savename);
      write_room_except (rm, text, user);
      sprintf (text, "NETLINK: Remote user %s removed.\n", user->savename);
      write_syslog (LOG_LINK, text, LOG_TIME);
    }
  if (user->malloc_start != NULL)
    free (user->malloc_start);
  num_of_users--;
  cnt_out++;
/* send Out event */
  event = E_OUT;
  strcpy (event_var, user->savename);

/* Destroy any clones */
  destroy_user_clones (user);
  destruct_user (user);
  reset_access (rm);
  destructed = 0;
}

/*** Tell telnet not to echo characters - for password entry and lock command ***/
echo_off (user)
     UR_OBJECT user;
{
  char seq[4];

  if (password_echo)
    return;
  sprintf (seq, "%c%c%c", 255, 251, 1);
  write_user (user, seq);
}


/*** Tell telnet to echo characters ***/
echo_on (user)
     UR_OBJECT user;
{
  char seq[4];

  if (password_echo)
    return;
  sprintf (seq, "%c%c%c", 255, 252, 1);
  write_user (user, seq);
}

/*** check if password is 'secure' ( 1 means 'secure' ) ***/
secure_pass (pass)
     char *pass;
{
  int i, k;

  /* test 1 */
  if (chk_spass_tests <= CHK_SPASS_NONE)
    return 1;
  k = 1;			/* test if password contains only letters or digits */
  for (i = 0; i < strlen (pass); i++)
    if (!isalnum (pass[i]))
      {
	k = 0;
	break;
      }
  if (k)
    return 0;
  /* test 2 */
  if (chk_spass_tests <= CHK_SPASS_ALNUM)
    return 1;
  i = 0;			/* test if there are similar characters... */
  while (pass[i] != '\0' && pass[i + 1] != '\0')
    {
      if (toupper (pass[i]) == toupper (pass[i + 1]) ||
	  pass[i] == pass[i + 1] + 1 || pass[i] == pass[i + 1] - 1)
	return 0;
      i++;
    }
  /* test 3 */
  if (chk_spass_tests <= CHK_SPASS_SIMIL)
    return 1;
  i = 0;			/* test if password is palindrome */
  k = strlen (pass) - 1;
  while (i < k)
    {
      if (tolower (pass[i]) == tolower (pass[k]))
	return 0;
      i++;
      k--;
    }
  return 1;
}

/************ MISCELLANIOUS FUNCTIONS *************/

/*** Actions executed when an user was sweared ***/
swear_action (user, inpstr)
     UR_OBJECT user;
     char *inpstr;
{
  if (user->level >= MIN_LEV_NOSWR)
    {
      write_user (user, "~OLGAEN~RS: Hmm... Superusers don't swear! :-)\n");
      return;			/* for super-users, no effect */
    }
  user->muzzled = 1;		/* set muzzle flag */
  user->restrict[RESTRICT_PROM] = restrict_string[RESTRICT_PROM];
  sprintf (text, "~EL~OL~LI>>>%s just shot himself in the mouth!!!\n",
	   user->savename);
  write_room_except (NULL, text, user);
  write_user (user, noswearing);
  sprintf (text, "%s (%s)\n", user->savename, inpstr);
  write_syslog (LOG_SWEAR, text, LOG_TIME);
  event = E_SWEAR;
  strcpy (event_var, user->savename);
}

/*** Miscellanious operations from user that are not speech or commands ***/
misc_ops (user, inpstr)
     UR_OBJECT user;
     char *inpstr;
{
  switch (user->misc_op)
    {
    case 1:			/* shutdown question... */
      if (toupper (inpstr[0]) == 'Y')
	{
	  if (rs_countdown && !rs_which)
	    {
	      if (rs_countdown > 60)
		sprintf (text,
			 "\n\07~OLGAEN: ~FR~LISHUTDOWN INITIATED, shutdown in %d minutes, %d seconds!\n\n",
			 rs_countdown / 60, rs_countdown % 60);
	      else
		sprintf (text,
			 "\n\07~OLGAEN: ~FR~LISHUTDOWN INITIATED, shutdown in %d seconds!\n\n",
			 rs_countdown);
	      write_room (NULL, text);
	      sprintf (text,
		       "%s initiated a %d seconds SHUTDOWN countdown.\n",
		       user->savename, rs_countdown);
	      write_syslog (LOG_CHAT, text, LOG_TIME);
	      rs_user = user;
	      rs_announce = time (0);
	      user->misc_op = 0;
	      prompt (user);
	      return 1;
	    }
	  talker_shutdown (user, NULL, 0);
	}
      /* This will reset any reboot countdown that was started, oh well */
      rs_countdown = 0;
      rs_announce = 0;
      rs_which = -1;
      rs_user = NULL;
      user->misc_op = 0;
      write_user (user, excellent);
      prompt (user);
      return 1;

    case 2:			/* more() question... */
      if (toupper (inpstr[0]) == 'E'
	  || more (user, user->socket, user->page_file) != 1)
	{
	  user->misc_op = 0;
	  user->filepos = 0;
	  user->page_file[0] = '\0';
	  prompt (user);
	}
      return 1;

    case 3:			/* writing on board */
    case 4:			/* writing mail */
    case 5:			/* doing profile */
    case 10:			/* writing a prayer */
      editor (user, inpstr);
      return 1;

    case 6:			/* suicide question... */
      if (toupper (inpstr[0]) == 'Y')
	{
	  sprintf (text, "~EL~FR~OL>>>%s is commiting suicide!\n",
		   user->savename);
	  write_room_except (NULL, text, user);
	  delete_user (user, 1);
	}
      else
	{
	  user->misc_op = 0;
	  write_user (user, excellent);
	  prompt (user);
	}
      return 1;

    case 7:			/* reboot question... */
      if (toupper (inpstr[0]) == 'Y')
	{
	  if (rs_countdown && rs_which == 1)
	    {
	      if (rs_countdown > 60)
		sprintf (text,
			 "\n\07~OLGAEN: ~FY~LIREBOOT INITIATED, rebooting in %d minutes, %d seconds!\n\n",
			 rs_countdown / 60, rs_countdown % 60);
	      else
		sprintf (text,
			 "\n\07~OLGAEN: ~FY~LIREBOOT INITIATED, rebooting in %d seconds!\n\n",
			 rs_countdown);
	      write_room (NULL, text);
	      sprintf (text, "%s initiated a %d seconds REBOOT countdown.\n",
		       user->savename, rs_countdown);
	      write_syslog (LOG_CHAT, text, LOG_TIME);
	      rs_user = user;
	      rs_announce = time (0);
	      user->misc_op = 0;
	      prompt (user);
	      return 1;
	    }
	  talker_shutdown (user, NULL, 1);
	}
      if (rs_which == 1 && rs_countdown && rs_user == NULL)
	{
	  rs_countdown = 0;
	  rs_announce = 0;
	  rs_which = -1;
	}
      user->misc_op = 0;
      write_user (user, excellent);
      prompt (user);
      return 1;

    case 8:			/* alert question... */
      user->blind = 0;
      if (toupper (inpstr[0]) == 'Y')
	{
	  user->ignall = user->ignall_store;
	  user->afk = 0;
	  event = E_NOAFK;
	  strcpy (event_var, user->savename);
	  user->misc_op = 0;
	  sprintf (text, ">>>%s escapes from the alien creatures.\n",
		   user->vis ? user->name : invisname);
	  write_room_except (NULL, text, user);
	  write_user (user, ">>>You exit from alert mode...\n");
	  prompt (user);
	  return 1;
	}
      user->blind = 1;
      user->misc_op = 8;
      return 1;

    case 9:			/* lock question... */
      user->blind = 0;
      echo_off (user);
      if (!strcmp (word[0], "who"))	/* even the user is locked, he/she can use .who */
	who (user, LIST_WHO);
      else if (!strcmp ((char *) crypt (word[0], PASS_SALT), user->pass))
	{
	  echo_on (user);
	  user->ignall = user->ignall_store;
	  user->afk = 0;
	  event = E_NOAFK;
	  strcpy (event_var, user->savename);
	  user->misc_op = 0;
	  write_user (user, ">>>You exit from lock mode...\n");
	  prompt (user);
	  sprintf (text, ">>>%s exits from lock mode.\n",
		   user->vis ? user->name : invisname);
	  write_room_except (NULL, text, user);
	  return 1;
	}
      /* invalid password */
      sprintf (text,
	       "~OLGAEN:~RS Wrong password - Session owner: %s { ~FT%s~RS }\n",
	       user->savename, user->afkmesg);
      write_user (user, text);
      user->blind = 1;
      user->afk = 1;
      user->misc_op = 9;
      return 1;
    }
  return 0;
}

/*** Show version and other useful info ***/
version (user)
     UR_OBJECT user;
{
  char hostname[SITE_NAME_LEN + 1];

  sprintf (text,
	   "\n~OL>>>NUTS version ~FG%s~RS~OL, GAEN version ~FG%s~RS~OL (update on %s)\n~OL>>>GSL version ~FG%s~RS~OL, gsh version ~FG%s~RS~OL, XML DTD version ~FG%s~RS~OL.\n",
	   VERSION, GAEN_VER, GAEN_UPDATE, GSL_VER, GSH_VER, GAENDTD_VER);
  write_user (user, text);
  if (gethostname (hostname, SITE_NAME_LEN) != -1)
    {
      sprintf (text, "~OL>>>Running on ~FG%s~RS~OL...\n", hostname);
      write_user (user, text);
    }
  write_user (user,
	      "~OL>>>Authors: ~FGNeil Robertson~RS~OL <neil@ogham.demon.co.uk>\n            ~OL~FGSabin Corneliu Buraga~RS~OL <busaco@infoiasi.ro> helped by\n            ~OL~FGVictor Tarhon-Onu~RS~OL <mituc@ac.tuiasi.ro>\n");
  write_user (user,
	      "~OL>>>Made in ~FBEng~FRland~RS~OL and ~FRRo~FYman~FBia~RS~OL.\n\n");
}

/*** See if an user has access to a room. If room is fixed to private then
     it's considered a saint room so grant permission to any user of SAINT 
     and above for those. ***/
has_room_access (user, rm)
     UR_OBJECT user;
     RM_OBJECT rm;
{
  if ((rm->access & PRIVATE) && user->level < gatecrash_level &&
      user->invite_room != rm && !((rm->access & FIXED) &&
				   user->level >= MIN_LEV_ACCPRIV))
    return 0;
  return 1;
}

/*** Safety unlink file ***/
s_unlink (filename)
     char *filename;
{
  char rname[80];
  if (safety)			/* not unlink file, only rename it */
    {
      sprintf (rname, "%s%s%d", filename, SAFETY_EXT,
	       random () % MAX_SAFETY_VAL);
      sprintf (text, "File %s (safety) unlinked - renamed in: %s.\n",
	       filename, rname);
      write_syslog (LOG_ERASE, text, LOG_TIME);
      return rename (filename, rname);
    }
  else
    {
      sprintf (text, "File %s unlinked.\n", filename);
      write_syslog (LOG_ERASE, text, LOG_TIME);
      return unlink (filename);
    }
}

/*** Generate an unique file name ***/
char *
genfilename (basename)
     char *basename;
{
  static char filename[SITE_NAME_LEN + 1];
  sprintf (filename, "%s_%d@%02d:%02d", basename, getpid (), thour, tmin);
  return (filename);
}

/*** Pick a room randomly; used in login process... ***/
pick_room (user)
     UR_OBJECT user;
{
  int num = random () % (user->level + 1);
  RM_OBJECT rm = room_first[user->dimension];

  if (!enable_rndgo)		/* random .go sky is disabled */
    {
      user->room = room_first[user->dimension];
      return;
    }
  while (num >= 0 && rm != NULL)
    {
      rm = rm->next;
      num--;
    }
  user->room = (rm == NULL || user->level <= MAX_LEV_NOPICK) ?
    room_first[user->dimension] : rm;
}

/*** The editor used for writing profiles, mail and messages on the boards ***/
editor (user, inpstr)
     UR_OBJECT user;
     char *inpstr;
{
  int cnt, line, i;
  char *edprompt =
    "\n>>>Your options are: ~FG~OLSave~RS, ~FY~OLRedo~RS, ~FR~OLAbort~RS, ~FB~OLView info~RS (s/r/a/v): ";
  char *ptr, *c;
  char text1[30];

  if (user->edit_op)
    {
      switch (toupper (*inpstr))
	{
	case 'S':		/* save text */
	  sprintf (text, ">>>%s finishes composing some text.\n",
		   user->vis ? user->name : invisname);
	  write_room_except (user->room, text, user);

	  switch (user->misc_op)
	    {
	    case 3:
	      write_board (user, NULL, 1);
	      break;
	    case 4:
	      smail (user, NULL, 1);
	      break;
	    case 5:
	      enter_profile (user, 1);
	      break;
	    case 10:
	      enter_prayer (user, 1);
	      break;
	    }

	  editor_done (user);
	  return;

	case 'R':		/* redo editing */
	  user->edit_op = 0;
	  user->edit_line = 1;
	  user->charcnt = 0;
	  user->malloc_end = user->malloc_start;
	  *user->malloc_start = '\0';
	  sprintf (text, "\n>>>Redo message...\n\n~FG%d>~RS",
		   user->edit_line);
	  write_user (user, text);
	  return;

	case 'A':		/* abort editing */
	  sprintf (text, ">>>%s gives up composing some text.\n",
		   user->vis ? user->name : invisname);
	  write_user (user, "\n>>>Message aborted.\n");
	  editor_done (user);
	  return;

	case 'V':		/* view text info */
	  switch (user->misc_op)
	    {
	    case 3:
	      strcpy (text1, "a message on the board");
	      break;
	    case 4:
	      strcpy (text1, "a mail");
	      break;
	    case 5:
	      strcpy (text1, "a profile");
	      break;
	    case 10:
	      strcpy (text1, "a prayer");
	      break;
	    default:
	      strcpy (text1, "an unknown letter");
	    }
	  i = 0;
	  c = user->malloc_start;
	  while (c != user->malloc_end)	/* count number of chars */
	    {
	      i++;
	      c++;
	    }
	  sprintf (text,
		   ">>>~FT%d~RS lines (~FT%d~RS characters) to write %s.\n",
		   user->edit_line, i, text1);
	  write_user (user, text);
	  write_user (user, edprompt);
	  return;

	default:
	  write_user (user, edprompt);
	  return;
	}
    }
  if (user->malloc_start == NULL)
    {
      if ((user->malloc_start = (char *) malloc (MAX_LINES * 81)) == NULL)
	{
	  sprintf (text, ">>>%s: failed to allocate buffer memory.\n",
		   syserror);
	  write_user (user, text);
	  write_syslog (LOG_ERR,
			"ERROR: Failed to allocate memory in editor().\n",
			LOG_NOTIME);
	  user->misc_op = 0;
	  prompt (user);
	  return;
	}
      user->ignall_store = user->ignall;
      user->ignall = 1;		/* Dont want chat mucking up the edit screen */
      user->edit_line = 1;
      user->charcnt = 0;
      user->malloc_end = user->malloc_start;
      *user->malloc_start = '\0';
      sprintf (text,
	       "~FT>>>Maximum of ~FG%d~FT lines, end with a '~FG.~FT' on a line by itself.\n\n~FG1>~RS",
	       MAX_LINES);
      write_user (user, text);
      sprintf (text, ">>>%s starts composing some text...\n",
	       user->vis ? user->name : invisname);
      write_room_except (user->room, text, user);
      return;
    }

/* Check for empty line */
  if (!word_count)
    {
      if (!user->charcnt)
	{
	  sprintf (text, "~FG%d>~RS", user->edit_line);
	  write_user (user, text);
	  return;
	}
      *user->malloc_end++ = '\n';
      if (user->edit_line == MAX_LINES)
	goto END;
      sprintf (text, "~FG%d>~RS", ++user->edit_line);
      write_user (user, text);
      user->charcnt = 0;
      return;
    }
/* If nothing carried over and a dot is entered then end */
  if (!user->charcnt && !strcmp (inpstr, "."))
    goto END;

  line = user->edit_line;
  cnt = user->charcnt;

/* loop through input and store in allocated memory */
  while (*inpstr)
    {
      *user->malloc_end++ = *inpstr++;
      if (++cnt == 80)
	{
	  user->edit_line++;
	  cnt = 0;
	}
      if (user->edit_line > MAX_LINES
	  || user->malloc_end - user->malloc_start >= MAX_LINES * 81)
	goto END;
    }
  if (line != user->edit_line)
    {
      ptr = (char *) (user->malloc_end - cnt);
      *user->malloc_end = '\0';
      sprintf (text, "~FG%d>~RS%s", user->edit_line, ptr);
      write_user (user, text);
      user->charcnt = cnt;
      return;
    }
  else
    {
      *user->malloc_end++ = '\n';
      user->charcnt = 0;
    }
  if (user->edit_line != MAX_LINES)
    {
      sprintf (text, "~FG%d>~RS", ++user->edit_line);
      write_user (user, text);
      return;
    }

/* User has finished his message , prompt for what to do now */
END:
  *user->malloc_end = '\0';
  if (*user->malloc_start)
    {
      write_user (user, edprompt);
      user->edit_op = 1;
      return;
    }
  write_user (user, "\n>>>No text.\n");
  sprintf (text, ">>>%s gives up composing some text.\n",
	   user->vis ? user->name : invisname);
  write_room_except (user->room, text, user);
  editor_done (user);
}

/* Done editing */
editor_done (user)
     UR_OBJECT user;
{
  user->misc_op = 0;
  user->edit_op = 0;
  user->edit_line = 0;
  free (user->malloc_start);
  user->malloc_start = NULL;
  user->malloc_end = NULL;
  user->ignall = user->ignall_store;
  prompt (user);
}


/*** Record speech and emotes in the room. It stores 2 lines of speech
     per room. ***/
record (rm, str)
     RM_OBJECT rm;
     char *str;
{
  strncpy (rm->revbuff[rm->revline], str, REVIEW_LEN);
  rm->revbuff[rm->revline][REVIEW_LEN] = '\n';
  rm->revbuff[rm->revline][REVIEW_LEN + 1] = '\0';
  rm->revline = (rm->revline + 1) % REVIEW_LINES;
}

/*** Records tells, whispers, replies and pemotes sent to the user. ***/
record_tell (user, str)
     UR_OBJECT user;
     char *str;
{
  strncpy (user->revbuff[user->revline], str, REVIEW_LEN);
  user->revbuff[user->revline][REVIEW_LEN] = '\n';
  user->revbuff[user->revline][REVIEW_LEN + 1] = '\0';
  user->revline = (user->revline + 1) % REVTELL_LINES;
}

/*** Records pictures sent to the user. ***/
record_pict (user, str)
     UR_OBJECT user;
     char *str;
{
  strncpy (user->revpict[user->revpictline], str, REVPICT_LEN);
  user->revpict[user->revpictline][REVPICT_LEN] = '\n';
  user->revpict[user->revpictline][REVPICT_LEN + 1] = '\0';
  user->revpictline = (user->revpictline + 1) % REVPICT_LINES;
}

/*** Set room access back to public if not enough users in room ***/
reset_access (rm)
     RM_OBJECT rm;
{
  UR_OBJECT u;
  int cnt;

  if (rm == NULL || rm->access != PRIVATE)
    return;
  cnt = 0;
  for (u = user_first; u != NULL; u = u->next)
    if (u->room == rm)
      ++cnt;
  if (cnt < min_private_users)
    {
      write_room (rm, ">>>Sky access returned to ~FGPUBLIC.\n");
      rm->access = PUBLIC;

      /* Reset any invites into the room & clear review buffer */
      for (u = user_first; u != NULL; u = u->next)
	{
	  if (u->invite_room == rm)
	    u->invite_room = NULL;
	}
      clear_rbuff (rm);
    }
}



/*** Exit cos of error during bootup ***/
boot_exit (code)
     int code;
{
  switch (code)
    {
    case 1:
      write_syslog (LOG_CHAT,
		    "BOOT FAILURE: Error while parsing configuration file.\n",
		    LOG_NOTIME);
      exit (1);

    case 2:
      write_syslog (LOG_CHAT,
		    "BOOT FAILURE: Can't open main port listen socket.\n",
		    LOG_NOTIME);
      perror ("GAEN: Can't open main listen socket");
      exit (2);

    case 3:
      write_syslog (LOG_CHAT,
		    "BOOT FAILURE: Can't open superuser port listen socket.\n",
		    LOG_NOTIME);
      perror ("GAEN: Can't open superuser listen socket");
      exit (3);

    case 4:
      write_syslog (LOG_CHAT,
		    "BOOT FAILURE: Can't open link port listen socket.\n",
		    LOG_NOTIME);
      perror ("GAEN: Can't open info listen socket");
      exit (4);

    case 5:
      write_syslog (LOG_CHAT, "BOOT FAILURE: Can't bind to main port.\n",
		    LOG_NOTIME);
      perror ("GAEN: Can't bind to main port");
      exit (5);

    case 6:
      write_syslog (LOG_CHAT, "BOOT FAILURE: Can't bind to superuser port.\n",
		    LOG_NOTIME);
      perror ("GAEN: Can't bind to superuser port");
      exit (6);

    case 7:
      write_syslog (LOG_CHAT, "BOOT FAILURE: Can't bind to link port.\n",
		    LOG_NOTIME);
      perror ("GAEN: Can't bind to link port");
      exit (7);

    case 8:
      write_syslog (LOG_CHAT, "BOOT FAILURE: Listen error on main port.\n",
		    LOG_NOTIME);
      perror ("GAEN: Listen error on main port");
      exit (8);

    case 9:
      write_syslog (LOG_CHAT,
		    "BOOT FAILURE: Listen error on superuser port.\n",
		    LOG_NOTIME);
      perror ("GAEN: Listen error on superuser port");
      exit (9);

    case 10:
      write_syslog (LOG_CHAT, "BOOT FAILURE: Listen error on link port.\n",
		    LOG_NOTIME);
      perror ("GAEN: Listen error on link port");
      exit (10);

    case 11:
      write_syslog (LOG_CHAT, "BOOT FAILURE: Failed to fork.\n", LOG_NOTIME);
      perror ("GAEN: Failed to fork");
      exit (11);
    }
}

/*** User prompt ***/
prompt (user)
     UR_OBJECT user;
{
  int hr, min;

  if (no_prompt)
    return;
  if (user->type == REMOTE_TYPE)
    {
      sprintf (text, "PRM %s\n", user->savename);
      write_sock (user->netlink->socket, text);
      return;
    }
  if (user->command_mode && !user->misc_op)
    {
      write_user (user, "~FTCOM>~RS ");
      return;
    }
  if (!user->prompt || user->misc_op)
    return;
  hr = (int) (time (0) - user->last_login) / 3600;
  min = ((int) (time (0) - user->last_login) % 3600) / 60;
  if (user->room != NULL)
    sprintf (text,
	     "~FY[%02d:%02d, %02d:%02d, ~FT%s~FY * %s * reply: %s~RS~FY * %d ball(s)]\n",
	     thour, tmin, hr, min, user->name, user->room->name,
	     user->reply_user[0] ? user->reply_user : "?", user->pballs);
  else
    sprintf (text,
	     "~FY[%02d:%02d, %02d:%02d, ~FT%s~FY * %s * reply: %s~RS~FY * %d ball(s)]\n",
	     thour, tmin, hr, min, user->name,
	     user->netlink->connect_room->name, "?", user->pballs);
  write_user (user, text);
}

/*** Write greetings in function of week day ***/
write_greetings (user)
     UR_OBJECT user;
{
  write_user (user, greetings[twday]);
}

/*** Page a file out to user. Colour commands in files will only work if the
     user!=NULL since if NULL we dont know if his terminal can support colour
     or not.
     Return value 0=cannot find file, 1= found file, 2=found and finished ***/
more (user, sock, filename)
     UR_OBJECT user;
     int sock;
     char *filename;
{
  int i, buffpos, num_chars, lines, retval, len;
  char buff[OUT_BUFF_SIZE], text2[81], *str, *colour_com_strip ();
  FILE *fp;

  if (!(fp = fopen (filename, "r")))
    {
      if (user != NULL)
	user->filepos = 0;
      return 0;
    }
/* jump to reading posn in file */
  if (user != NULL)
    fseek (fp, user->filepos, 0);

  text[0] = '\0';
  buffpos = 0;
  num_chars = 0;
  retval = 1;
  len = 0;

/* This is a hack to fix an annoying bug I cannot solve */
  if (sock == -1)
    {
      lines = 1;
      fgets (tex

Showing the first 100 KB of 545.9 KB. Download the archive for the full file.

Site Stats

Snippets: 1791
Codebases: 571