main.c

pdirt/drv/src/main.c · 37.2 KB

From the archive pDirt-1_tar.gz

Download the archive   « Back to the archive contents

/****************************************************************************
 ** MAIN STARTUP ROUTINES
 ** 
 ** Authors: Alf Sarte and G. Sorseth (Alf & NickNack)
 ** Additions: Various Aber fanatics.
 **   - Rewritten parts of the reboot code (file read/write calls)
 ****************************************************************************/

/******************************************************************************
 ** START CODE
 ******************************************************************************/
#define MAIN_C

#define ERIC_DB
#include <sys/file.h>
#include "kernel.h"
#include <errno.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <sys/socket.h>
#ifdef RS6000
#include <sys/select.h>
#endif
#include <arpa/inet.h>
#include <netdb.h>
#include "config.h"
#include <stdarg.h>
#include <string.h>
#include "kernel.h"
#include "config.h"
#include "machines.h"
#include "sendsys.h"
#include "mail.h"
#include "mobile.h"
#include "mud.h"
#include "main.h"
#include "jmp.h"
#include "levels.h"
#include "log.h"
#include "bprintf.h"
#include "timing.h"
#include "pflags.h"
#include "bootstrap.h"
#include "s_socket.h"
#include "rooms.h"
#include "calendar.h"
#include "zones.h"
#include <gdbm.h>
#include "uaf.h"
#include "commands.h"
#include "fight.h"
#include "exit.h"
#include "parse.h"
#include "calendar.h"
#include "special.h"
#include "recover.h"
#include "hate.h"
#include "party.h"
#ifdef IDENT
# include "ident.h"
#endif
#include "dns.h"

#ifdef INTERMUD
#include "InterMud/intermud.h"
EXTERN int __iConn(char *addr, int port);
#endif

#ifdef ABERCHAT
#include "AberChat/client.h"
EXTERN int 	aberfd;
EXTERN Boolean  aber_output;
#endif

#ifdef KEEP_LINKDEAD
static void cleanup_link(void);
#endif

static int xmain (int fd);
static int xmain_reboot (int fd);
static int go_background (int pid_fd);
static int check_pid (void);
static void get_options (int argc, char **argv);
static void usage (void);
static void main_loop (int m_socket);
void   sysreboot(Boolean crash,int will_update);
void   rm_pid_file (void);
static void end_connection (void);
static void new_connection (int fd);
static void handle_packet (int fd);
static void dump_info (void);
static void sig_handler (int sig);
static void usage (void);
void initialize_slot(int slot);

/* Some local variables */
fd_set sockets_fds;
fd_set buffer_fds;
int    mud_port = PORT;
int    main_socket;
int    width;
int    fildes[2];
char   pidFileName[256];
#ifdef REBOOT
int    old_proc_num = 0;
int    port_number=PORT;
#endif

Boolean kill_other_mud     = False;
Boolean clear_syslog_file  = False;
Boolean stay_foreground    = False;
Boolean sig_term_happened  = False;
Boolean sig_timer_happened = False;
#ifdef DEBUG
Boolean Debug		   = True;
#else
Boolean Debug              = False;
#endif
Boolean kill_and_exit      = False;

static int inp_buf_c = 0;
static struct timeval zerotime = {0, 0};
extern int dnsfd;

void main (int argc, char **argv, char **ep)
{ int fd, x;
  char path[1024];
  char binary[1024];
  
  sigsetmask(0);
  envp = ep;
  progname = argv[0];
  width = getdtablesize ();
  
#ifdef HPUX /* hpux doesnt know getwd */
  sprintf (binary, "/internet/mud/pdirt/%s",argv[0]);
#else
  getcwd (path,1023);
  sprintf (binary, "%s/%s", path, argv[0]);
#endif  

  get_options (argc, argv);	/* Parse command line */
 
  printf("[%s AberMUD Startup]\n\n",MUDNAME);
  printf("    o Game Port   : %.4d       o Player limit  : %d\n",mud_port, max_players);
  printf("    o Clear Syslog: %-3.3s        o Data Directory: %s\n",
         (clear_syslog_file ? "Yes" : "No "), data_dir);
  printf("    o Debugging   : %s", Debug ? "On " : "Off");
  printf("        o Kill other MUD: %s\n",kill_other_mud ? "Yes" : "Ask user");
  
  if (data_dir != NULL)
    chdir (data_dir);		/* Do chdir if specified */
  
  /* Check if PID_FILE is there...and what it contains */
  fd = check_pid ();
  
  /* We arrive here only if we are to continue and now we are alone. */
  /* Also, the PID_FILE is opened */
  
  if (kill_and_exit)
    exit (0);

  last_startup = last_backup = time(0);  /* Set the last cold startup  */
  numresets    = 0;               /* Initialise these to keep track of */
  numreboots   = 0;               /* Some statistics.                  */
  numcrashes   = 0;
  
  printf("\n[Bootstrapping Daemon]\n\n");

#ifdef REBOOT
  if (!old_proc_num)
    x = xmain (fd);
  else x = xmain_reboot (fd);
#else
  x = xmain (fd);
#endif
  
  /* The Mud has terminated for some reason, lets clean up some of the mess */
  /* we made and give a message to say how it is terminated.                */
  unlink (pidFileName);    

  if (x < 0)
  {
      mudlog ("BOOTSTRAP: Abnormal termination of mud");
      exit (1);
  }
  mudlog ("BOOTSTRAP: Normal termination of mud");
}

static void connect_ok (char *h, int port)
{ char b[80];
  
  /* Generate a connected message */
  sprintf (b, "== Connected to port %d of %s (PID: %d)==\n\001\n", port, h,getpid());

  if (stay_foreground)
  {   if (write (1, b, strlen (b) - 2) == -1)
	 progerror ("write(1,b,strlen(b)).1 failed");
  }
  else
  { /*  if (write (fildes[1], b, strlen (b)) == -1)
	progerror ("write(1,b,strlen(b)).2 failed");*/
      /* Wait for parent to die */	
      while (getppid () > 1);
      close (fildes[1]);
  }
}

static int xmain (int fd)
{ int s;
  int k,i;
  struct sockaddr_in sin;
  
  /* We arrive here only if we are to continue and now we are alone. */
  /* Also, the PID_FILE is opened */
  
  if (open_logfile (LOG_FILE, clear_syslog_file) < 0)
  {  close (fd);
     return -1;
  }
  
  if (bootstrap () < 0)
  {				/* Initialize data structures */
      close (fd);
      return -1;
  }
 
/* 
  init_userfile();
  reorg_userfile();
*/  
  if (mud_port == -1)
    mud_port = PORT;
  
  /* Now we go background */
  if (go_background (fd) < 0)
     return -1;
  
  for (i=0; i < max_players; i++)
    initialize_slot(i);

  k = 10;
  bzero (&sin, sizeof (struct sockaddr_in));
  
  while ((s = main_socket = make_service (mud_port, my_hostname,
					  sizeof (my_hostname),
					  &my_hostent, &sin)) == -4
	 && errno == EADDRINUSE && --k >= 0)
  {
      sleep (2);
  }
  
  if (s < 0)
  {   mudlog ("BOOTSTRAP: Error code %d from make_service", s);
      progerror ("make_service");
      return -1;
  }
  
#ifndef REBOOT
  if (s > 0)
  {				/* We want the main socket at fd 0 */
      dup2 (s, 0);
      close (s);
      s = main_socket = 0;
  }
#endif
  
  connect_ok (my_hostname, mud_port);
  
  FD_ZERO (&sockets_fds);
  FD_ZERO (&buffer_fds);
  FD_SET (s, &sockets_fds);
  
  /* Main program loop */
  
  init_calendar ();
  update_calendar ();
  boot_reset ();
  last_reset = last_healall = time(0);

  main_loop (s);
  
#ifdef INTERMUD
  imShutdown(0);
#endif  
  close (s);
  return 0;
}

static int go_background (int fd)
{ char b[80];
  int tty ;
  
  /* Go background */
  signal (SIGHUP, SIG_IGN);
  signal (SIGINT, SIG_IGN);
  signal (SIGQUIT, SIG_IGN);
  signal (SIGTSTP, SIG_DFL);
  signal (SIGTTOU, SIG_DFL);
  signal (SIGTTIN, SIG_DFL);
  if (!stay_foreground)
  {  if (pipe (fildes) < 0)
     {  progerror ("go_background/pipe");
        exit (1);
     }
     switch (pid = fork ()) {
     case -1:                         /* Fork Failed for some reason */
	  progerror ("fork");
	  close (fd);
	  return -1;
     case 0:                          /* Child Code */
	  break;
     default:                         /* Parent Code */
	  printf ("%s AberMUD is using PID: %d\n", MUDNAME,pid); 
	  close (fd);
	  fflush (stdout);	/* Flush stdout */
	  close (fildes[1]);
#if 0
	  while ((x = read (fildes[0], b, sizeof (b))) > 0)
	  {  for (s = b, y = 0; y < x && s[y] != '\001'; ++y)
	     {  if (s[y] != '\n')
		    continue;
	        if (*s == '\001')
		    break;
	        if (write (1, s, y + 1) == -1)
		    progerror ("write(1, s, y + 1)  failed");
		s += y + 1;
		x -= y + 1;
		y = -1;
	     }
	     if (*s == '\001')
		break;
	     if (x > 0)
	     {  if (write (1, s, x) == -1)
		    progerror ("write(1, s, x)  failed");
	     }
	  }
#endif
	  exit (0);		/* Let our parent process die */
     }
     if (stdin)
	fclose (stdin);
     if (stdout)
	fclose (stdout);
     close (fildes[0]);
  }
  
  pid = getpid ();		/* Get our process id */
  sprintf (b, "%d\n", pid);
  if (write (fd, b, strlen (b)) == -1)
    progerror ("write(fd, b, strlen(b)) failed");
  close (fd);
  
  
  if (!stay_foreground)
  {  if ((tty = open ("/dev/tty", O_RDWR, S_IRUSR | S_IWUSR)) >= 0)
     {  if (ioctl (tty, TIOCNOTTY, 0) < 0)
        {  progerror ("ioctl,TIOCNOTTY");
	   return -1;
	}
	close (tty);

#if defined(LINUX) || defined(HPUX) || defined(RS6000) 
       	setpgrp();
#else
	setpgrp (pid, pid);	/* Make our own process group */
#endif

     }
     else if (errno != ENXIO)
     {  progerror ("open,tty");
        return -1;
     }
      
     signal (SIGINT, SIG_IGN);
     signal (SIGQUIT, SIG_IGN);
  }
  else
  {  signal (SIGINT, SIG_DFL);
     signal (SIGQUIT, SIG_DFL);
  }
  
  signal (SIGTERM, sig_handler);
  signal (SIGTSTP, SIG_DFL);
  signal (SIGCONT, SIG_DFL);
  signal (SIGTTOU, SIG_DFL);
  signal (SIGTTIN, SIG_DFL);
#ifndef DEBUG
  signal (SIGSEGV, sig_handler); /* Segmentation fault */
  signal (SIGBUS, sig_handler);	 /* Bus error */
  signal (SIGSYS, sig_handler);	 /* Bad argument to system call */
#endif
  signal (SIGPIPE, SIG_IGN);	/* Broken pipe */
  signal (SIGHUP, SIG_IGN);     /* hang up */
  return 1;
}

static int check_pid (void)
{ int fd;
  pid_t pid = -1;
  int c;
  FILE *f;
  char b[80];
  
  sprintf(pidFileName,"%s/%s.%d",data_dir,PID_FILE,mud_port);
  if ((fd = open (pidFileName, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR)) < 0)
  {   /* The file exist already */
      if (errno == EEXIST)
      {  if ((f = fopen (pidFileName, "r")) != NULL)
         {  if (fgets (b, sizeof b, f))
		pid = atoi(b);
	    else
		pid = 0;
            fclose (f);
	  }
	  else
	  {   perror ("fopen," PID_FILE);
	      exit (1);
	  }
	  if (pid > 0)
	  {  if (!kill_other_mud)
	     {  printf ("\n    o %s is running (or PID file exists), kill it [Y/N]: ", MUDNAME);
		while ((c = getchar ()) != 'N' && c != 'n' && c != 'Y' &&
			 c != 'y' && c != '\n' && c != '\r');
		  if (c == 'Y' || c == 'y')
		    kill_other_mud = True;
	     }
	     if (!kill_other_mud)
	     {  printf ("    - Startup aborted by user.\n");
	        exit (0);
	     }
	     printf ("    o Killing other MUD (pid %d)\n", pid);
	     if (kill (pid, SIGTERM) < 0)
             {  if (errno != ESRCH)
	        {  perror ("kill");
		   exit (1);
		}
		else if (unlink (pidFileName) < 0)
		{		/* PID_FILE without process */
		      perror ("unlink");
		      exit (1);
		}
	     }
	  }
	  else
	  {  if (unlink (pidFileName) < 0)
	     {		/* PID_FILE without process */
		  perror ("unlink");
		  exit (1);
	     }
	  }
	  c = 6;
	  while (True)
          {  sleep (1);
	     if ((fd = open (pidFileName, O_WRONLY | O_CREAT | O_EXCL,
			      S_IRUSR | S_IWUSR)) >= 0)
		break;
	     if (--c < 0)
	     {  printf ("    - Timeout occured. Can't kill the MUD, Startup Aborted!\n");
	        exit (0);
	     }
	  } 
      }
      else 
      {  perror ("open");
         exit (1);
      }
  }
  return fd;
}


static void get_options (int argc, char **argv)
{ char *s;
  int x;
  
  if (argc == 1)
  {   stay_foreground = False;      /* I Always send it to background - M */
      clear_syslog_file = False;    /* The rest are defaults              */
      kill_other_mud = False;
      mud_port = PORT;
      max_players = MAX_USERS;
      return;
  }
  
  /**
   ** since we make odd defaults with no args, we have to add
   ** an option to say 'use real defaults', I select option a for that.
   ** mudd -a is what usually should be just 'mudd'. -Alf
   **/

  while (--argc > 0)
  {  s = *++argv;
  
     if (*s++ != '-')         /* Wrong parameter format, we expect every */
     {  usage ();             /* param to start with a '-' sign - M      */
        exit (1);
     }
     
     x = *s++;
     switch (x) {  
     case 'a':                /* -a is the same as default */
	  break;

#ifdef REBOOT
     case 'r':                /* Param used by reboot code */
 	  if ((*s != '\0') || ((--argc > 0) && (*(s = *++argv) != '\0')))
	  {  old_proc_num = atoi(s);
             kill_other_mud = True;
          }
	  break;
#endif

     case 'p':                /* Connect to another port than default */
	  if ((*s != '\0') || ((--argc > 0) && (*(s = *++argv) != '\0')))
	  {  if ((mud_port = atoi (s)) < 1024 || mud_port > 65535)
	        mud_port = PORT;
	
	  }
	  break;
     case 'f':
	  stay_foreground = True;
	  break;
     case 'k':
	  kill_other_mud = True;
	  break;
     case 'c':
	  clear_syslog_file = True;
	  break;
     case 'x':
	  kill_other_mud = True;
	  kill_and_exit = True;
	  break;
     case 'i':
	  dump_info ();
	  exit (0);
	  break;
     case 'n':
	  if ((*s != '\0') || ((--argc > 0) && (*(s = *++argv) != '\0')))
	  {  if ((max_players = atoi (s)) < 1 || max_players > 1000)
	        max_players = MAX_USERS;
	
	  }
	  break;
     case 'd':
	  if ((*s != '\0') || ((--argc > 0) && (*(s = *++argv) != '\0')))
	     data_dir = s;
	  break;
     case 'v':
	   printf("%s Dyrt system information.\n",MUDNAME);
	   printf("----------------------------------------\n"
                  "%s - 1996\n"
	          "Dyrt code by Rex, iDirt code by Illusion\n"
	          "Derived from AberMud (3.1) 1990, 1993\n"
	          "by Alf & NickNack\n",VERSION);
	   exit(0);
	   break;
     default:
	  usage ();
	  exit (1);
     }
  }
  if (argc > 0)
  {  usage ();
     exit (1);
  }
}

static void usage (void)
{
  fprintf (stderr, "AberMUD IV Server (%s revision)\
\nUsage: %s [-p port] [-d dir] [-k] [-c] [-f] [-n count] [-x] [-v]\
\n\
Where:\n\
\tp port         port to attach to.\n\
\td directory    data directory.\n\
\tk              kill other mud.\n\
\tc              clear log file.\n\
\tn count        maximum users.\n\
\tf              stay in foregreound.\n\
\ti              some interesting information.\n\
\tv              Version Information
\tx              just kill the running mud, don't run.\n\
", MUDNAME, progname);
  
  exit (1);
}

static void new_connection (int fd);

static void main_loop (int m_socket)
{ int w = width;
  int v;
  int fd;
  int plx = 0;
  struct timeval *tv;
  fd_set r_fds, e_fds;
  
  signal (SIGALRM, sig_handler);

  for(v = 0; v < 32; v++) 
      signal(v,sig_handler);        

  signal(SIGCHLD, SIG_IGN);     /* See if this stops continuous reboots */	
  signal(SIGTRAP, SIG_DFL);     /* Debug Signal (for dbx gdb) */
  signal(SIGTERM, sig_handler); /* Terminate mud */
  signal(SIGTSTP, SIG_DFL);
  signal(SIGCONT, SIG_DFL);
  signal(SIGTTOU, SIG_DFL);
  signal(SIGTTIN, SIG_DFL);
  signal(SIGSEGV, sig_handler); /* Segmentation fault */
  signal(SIGPIPE, SIG_IGN);     /* Broken pipe */
 
  /*  reset(); */
  cur_player = NULL;
  quit_list = -1;
  global_clock = time(0);
  set_timer ();

#ifdef ABERCHAT
  aberchat_boot();
#endif
#ifdef INTERMUD
  imfd = -1;
#endif

  bootmuddns();

  while (!sig_term_happened)
  {   
      switch (v = setjmp (to_main_loop)) {
      case JMP_QUITTING:
	  bflush ();
	  end_connection ();
	  setup_globals (-1);
	  ++fd;
	  break;
      }
      if (sig_timer_happened)
      {  sig_timer_happened = False;
         signal (SIGALRM, sig_handler);
	 setup_globals (-1);	/* bflush() and disable mynum */
	 set_timer ();
	 on_timer ();
      }
      else
      {
	  r_fds = e_fds = sockets_fds;
	  
	  if (inp_buf_c > 0)
	    tv = &zerotime;
	  else
	    tv = NULL;
	  
#ifdef HPUX
          if ((v = select (w, (int *) &r_fds, NULL, (int *) &e_fds,tv)) < 0)
#else
	  if ((v = select (w, &r_fds, NULL, &e_fds, tv)) <0)
#endif
          {
	      if (errno == EINTR)
		continue;
	      progerror ("select");
	      exit (1);
          }
          for (fd=0; fd < width;fd ++)
          {   
              if (FD_ISSET (fd, &e_fds))
	      {   int plx;
	      
#ifdef INTERMUD
		  if (fd == imfd)
                  {   mudlog("INTERMUD: Exception. Shutting down connection");
                      FD_CLR(fd,&sockets_fds);
                      close(fd);
                      imfd = -1;
                  }
#endif
                  plx = find_pl_index(fd);
                      
                  if(plx<0) 
                  { end_connection();
                    return;
                  }
                      
                  setup_globals(plx);

                  if(cur_player->stream==NULL) 
                       continue;
    
            	if(is_in_game(plx)) 
	    	{
	           cleanup_link();
	      	   errno = 0;
	        } 
	        else 
	        {
	            crapup(NULL,CRAP_SAVE|CRAP_UNALIAS|CRAP_RETURN|CRAP_LINKLOSS);
	            errno = 0;                   /* Loose link */
	            quit_player();
	        }
                  mudlog ("Exception pending with fd = %d", fd);
		  --v;
	      }
	      if (FD_ISSET (fd, &r_fds) || FD_ISSET (fd, &buffer_fds))
	      {
		  --v;
		  if (fd == m_socket) 
		      new_connection (fd);
#ifdef INTERMUD
                  else if (fd == imfd)
                  {   if (imPacket(fd) == -1)
                      {  FD_CLR(fd,&r_fds);
                         FD_CLR(fd,&sockets_fds);
                         imfd = -1;
                      }
                  }
#endif
#ifdef ABERCHAT
	          else if (aberfd != -1 && fd == aberfd)
                      aberchat_readpacket();
#endif
		  else if (fd == dnsfd)
                      read_lookup(fd);
                  else 
		      handle_packet (fd);

		  bflush ();
	      }
	  }
#ifdef ABERCHAT
	if (aber_output)
	   aberchat_writepacket();
#endif
	  while (quit_list >= 0)
	     end_connection ();
      }
      while (quit_list >= 0)
           end_connection ();
  }

  mudlog ("SIGNAL: SIGTERM Handled");
  for (plx = 0; plx < max_players; plx++)
  {
      if (!EMPTY (pname (plx)))
      {
	  setup_globals (plx);
	  crapup ("Due to an unknown event the mud has been closed for all players.\n"
                  "We cant say how long this will take, or how serious this problem is\n"
                  "Since this is just a standard message ;).\n"
                  "We do however seriously appologise for this terrible intervention in\n"
                  "the satisfaction of your mud addiction.\n" ,
		  CRAP_UNALIAS | CRAP_SAVE | CRAP_RETURN);
          saveme();
          bflush();
          quit_player();
          end_connection();
      }
  }
  rm_pid_file ();
}

void rm_pid_file (void)
{ if (unlink (pidFileName) < 0) 
      progerror ("rm_pid_file");
}

static void end_connection (void)
{ INP_HANDLER *i, *j;
  int fd;
  int me = real_mynum;
  int x;
  
  if ((x = quit_list) < 0)
    return;
  if (x == real_mynum)
    me = -1;

  setup_globals (x);
  quit_list = cur_player->quit_next;
  cur_player->quit_next = -2;
  
  fd = cur_player->fil_des;

  if (cur_player->inmailer)
     abort_mail();
     
  if (mob_fun(mynum) != NULL)
  {  mob_fun(mynum)(E_EXIT);
     clear_mob_fun(mynum);
  }

  bflush ();

  i = cur_player->inp_handler;
  while (i != NULL)
  {
      j = i;
      i = i->next;
      free ((char *) j);
  }
  cur_player->inp_handler = NULL;

  /* Attempt to get those blody sockets to close correctly */
  cur_player->inp_buffer_p = cur_player->inp_buffer_end = cur_player->inp_buffer;
  cur_player->sock_buffer_p = cur_player->sock_buffer_end = cur_player->sock_buffer;
  bzero(cur_player->inp_buffer,MAX_COM_LEN);
  bzero(cur_player->sock_buffer,MAX_COM_LEN);

  pname(mynum)[0] = '\0';
  setploc(mynum,0);
  cur_player->iamon= False;
  cur_player->linkdead = False;

  if (fd < 0)
  {  if (cur_player->stream != NULL)
     {   fclose(cur_player->stream);
         cur_player->stream = NULL;
     } 
     cur_player->fil_des = -1;
     cur_player->stream = NULL;
     setup_globals (me);
     return;
  }

  shutdown(fd,2);
  if (FD_ISSET (fd, &buffer_fds))
    inp_buf_c--;
  FD_CLR (fd, &sockets_fds);
  FD_CLR (fd, &buffer_fds);

  close (fd);
  if (cur_player->stream != NULL)
    fclose (cur_player->stream);

  cur_player->fil_des = -1;
  cur_player->stream = NULL;

#ifdef ABERCHAT
  aberchat_newconn(mynum);
  if (cur_player->atarget != NULL)
     free(cur_player->atarget);
  if (cur_player->amud != NULL)
     free(cur_player->amud);
  cur_player->atarget = cur_player->amud = NULL;
#endif
  setup_globals (me);
}

static void 
new_connection (int m_socket)
{
  PLAYER_REC *pl;
  FILE *f;
  struct hostent *h;
  int plx;
  int fd;
  int sin_len;
  Boolean host_banned = False, host_b2 = False;
  Boolean host_locked = False;
  Boolean needs_lookup = True;
  struct sockaddr_in sin;
  char *host, *s;
  char hostnum[MAXHOSTNAMELEN + 20];
  char full_hostname[MAXHOSTNAMELEN + 20];
  char real_hostname[MAXHOSTNAMELEN + 20];
  
  bzero ((char *) &sin, sizeof (struct sockaddr_in));
  sin_len = sizeof (struct sockaddr_in);
  if ((fd = accept (m_socket, (struct sockaddr *)&sin, &sin_len)) < 0) {
      progerror ("accept");
      exit(1);
  }
  else if ((f = fdopen (fd, "w")) == NULL)   {
      progerror ("fdopen");
      exit (1);
  }
  else
  {
#ifdef BROKEN_GCC
      strncpy (hostnum,inet_ntoa (&sin.sin_addr), MAXHOSTNAMELEN);
#else
      strncpy (hostnum, inet_ntoa (sin.sin_addr), MAXHOSTNAMELEN);
#endif
      host_b2 = is_host_banned (hostnum);
      host = hostnum;
     
      if (dnsfd == -1) 
      {    if ((h = gethostbyaddr ((char *) &sin.sin_addr, sizeof (sin.sin_addr),
                AF_INET)) == NULL)
           {
#ifdef LOG_HOSTERROR
                mudlog ("gethostbyaddr: Couldn't find hostentry for %s", hostnum);
#endif
           }
           else
           {
               host_banned = is_host_banned ((char *)h->h_name);
               host = (char *)h->h_name;
           }
           host_locked = is_locked_host(host);

           strcpy(real_hostname,host);
           needs_lookup = False;
      }
      else
      {   strcpy(real_hostname,host);
          strcpy(host,full_hostname);
          host_locked = is_locked_host(host);
          host_banned = is_host_banned(host);
      }

      if ((plx = find_free_player_slot ()) < 0)
	{
	  fprintf (f, "\nSorry, this mud is full. Please come back later.\n");
	  fflush (f);
	  fclose (f);
	  return;
	}
      
      
      setup_globals (plx);
      pl = cur_player;
      
      pl->sock_buffer_p = pl->sock_buffer_end = pl->sock_buffer;
      pl->sin_len = sin_len;
      pl->sin = sin;
      pl->fil_des = fd;
      pl->stream = f;
      pl->isforce = False;
      pl->linkdead = False;
      s = pl->hostname;
      if (host_banned || host_b2)
	*s++ = '*';
      else if (host_locked)
        *s++ = '!';
      
      strncpy (s, host,MAXHOSTNAMELEN);
      strncpy (pl->realhostname,real_hostname,MAXHOSTNAMELEN);
      strncpy (pl->hostname,real_hostname,MAXHOSTNAMELEN);
      
      /* Include this socket as a socket to listen to */
      FD_SET (fd, &sockets_fds);
      if (needs_lookup)
         request_lookup(plx,pl->realhostname);
#ifdef ABERCHAT
      aberchat_newconn(plx);
#endif
      new_player ();
    }
}


void handle_packet (int fd)
{ int plx = find_pl_index (fd);
  register int x, y, g;
  char *b, *c, *k;
  char *p;
  
  setup_globals (plx);
 
  if ((cur_player->inp_handler == NULL || phandler(plx) == NULL) && cur_player->iamon)
  {   crapup("Fatal Error occured, lost your input handler, please mail what you did\n"
             "before you got this message to the Mud Account.",CRAP_SAVE|CRAP_RETURN);
      mudlog("ERROR: %s lost input handler, %s",(cur_player->inp_handler == NULL) ?
	"No Memory allocated for handler or Primary Pointer set to NULL" :
	"Secondary Pointer set to NULL or Handler POPed to NULL");
      return;
  } 

  g = 0;

  if (cur_player->inp_buffer_p >= cur_player->inp_buffer_end)
  {
      if ((x = read (fd, cur_player->inp_buffer, MAX_COM_LEN - 5)) < 0)
      {
	  if (errno == ECONNRESET ||	/* Connection reset by peer */
	      errno == EHOSTUNREACH ||	/* No route to host */
	      errno == ETIMEDOUT ||	/* Connection timed out */
	      errno == ENETUNREACH ||	/* Network is unreachable */
	      errno == ENETRESET ||	/* Net dropped connection on reset */
	      errno == ENETDOWN)	/* Network is down */
	  {	
#ifdef KEEP_LINKDEAD	  		
	      if(is_in_game(real_mynum)) 
	      {
	         cleanup_link();
	         errno = 0;
	         return;
	      } 
#endif	      
	      mudlog ("Connection failure: %s [%s]", strerror(errno), pname (mynum));
	      crapup (NULL, CRAP_SAVE | CRAP_UNALIAS | CRAP_LINKLOSS);
	      
	      send_msg (DEST_ALL, MODE_QUIET | MODE_BRACKET, Max (pvis (mynum), LVL_ARCHWIZARD),
			LVL_MAX, mynum, NOBODY,
			"%s (%s) Link error: %s", pname (mynum), cur_player->hostname, strerror(errno));
	      
	      errno = 0;
              /*
	      longjmp (to_main_loop, JMP_QUITTING);
	      */
              quit_player();
	      return;
          }
          if (ublock[mynum].pname[0] != '\0')
	  {  mudlog ("SOCKET: error when reading data from %s", pname (mynum));
	     progerror (pname (mynum));
          }
          else
          {  mudlog("SOCKET: Error when reading data from host %s",players[mynum].realhostname);
	     progerror (players[mynum].realhostname);
          }
	  return;
      }
      else if (x == 0)
      {   
#ifdef KEEP_LINKDEAD	  		
          if(is_in_game(real_mynum)) 
          {
	         cleanup_link();
	         errno = 0;
	         return;
          } 
#else	      
	  if (is_in_game(mynum))
	  {  send_msg(DEST_ALL,MODE_QUIET|MODE_BRACKET,LVL_WIZARD,LVL_MAX,mynum,NOBODY,
                   "%s has cut (lost) link to this realm",pname(mynum));
             mudlog("CONN: Exit %s (link cut)",pname(mynum));
	  }
#endif	  
	  crapup (NULL, CRAP_SAVE | CRAP_UNALIAS|CRAP_LINKLOSS);
	  errno = 0;
	  quit_player ();
	  return;
      }
      else if (*(cur_player->inp_buffer) == '\377')
      {
	  return;
      }
      else
      {
            inp_buf_c++;
      
            FD_SET (fd, &buffer_fds);
            b = cur_player->inp_buffer_p = (char *) cur_player->inp_buffer;
            cur_player->inp_buffer_end = b + x;
      }
  }
  else
  {
      b = cur_player->inp_buffer_p;
      x = cur_player->inp_buffer_end - b;
  }

  c = cur_player->sock_buffer_p;
  
  
  for (y = 0; 
       b != 0 && y < x && c < (cur_player->sock_buffer + MAX_COM_LEN - 6) && b[y] != '\n' && b[y] != '\r';
       ++y)
  {
      if ((b[y] == '\010') || (b[y] == '\177'))
      {
	  if (c > cur_player->sock_buffer)
	    c--;
      }
      else
	*c++ = b[y];
  }

  cur_player->sock_buffer_p = c;

  if (y >= (MAX_COM_LEN - 6))
  {  *c = '\0';
     
     /* Notify player we have cut their longest sentence record attempt.
      */
     bprintf("&+w(&+wMaximum Input Exceeded, Cutting Input after: &*%s&+w)\n",
          cur_player->sock_buffer + MAX_COM_LEN - 16);

     *(c-2) = '\n';
     *(c-1) = '\n';
     y -= 2;          /* We want the packet handled */
     x = y+1;
     /* Read all the remaining input from socket, so we can get a clear start.
      * causes lag, but prevents mud from crashing, or socket from hanging.
      */
     while (read(fd,cur_player->inp_buffer,MAX_COM_LEN) > 0)
        ;
     FD_CLR(fd,&buffer_fds);
/*
     bprintf("y = %d, x = %d, c = %d/%p, b= %d/%p\n",y,x,*c,c,*b,b);
 */
  }

  if ((y < x && c < (cur_player->sock_buffer + MAX_COM_LEN - 5)) && b != 0)
    {
      while (++y < x && (b[y] == '\n' || b[y] == '\r'))
         ;

      *c = 0;
      k = c;
      c = cur_player->sock_buffer;
      
      for (p = c; *p != '\0'; p++)
      {
	  if (iscntrl (*p) && *p != 'å' && *p != 'Å'&& *p != 'ä' && *p != 'Ä' && 
              *p != 'Ö' && *p != 'ö')
	    *p = ' ';
      }
      
      if (cur_player->snooped > 0)
      {   char tmp[MAX_COM_LEN + 2];

          strcpy(tmp,"&+wI&+w>&* ");
	  *k++ = '\n';
	  *k-- = 0;
          strcat(tmp,c);
	  print_buf (tmp, True);
	  *k = 0;
      }

      g = 1;
  }

  cur_player->sock_buffer_p = c;
  cur_player->inp_buffer_p = b + y;
  
  if (y >= x)
  {
      FD_CLR (fd, &buffer_fds);
      --inp_buf_c;
  }
  
  if (g)
  {   /* Handle Input */
      cur_player->inp_handler->inp_handler (c);
      cur_player->sock_buffer_p = cur_player->sock_buffer;
  };
}


static void sig_handler (int sig)
{ char msg[30];
  
  switch (sig) {
  case SIGTERM:
      sig_term_happened = True;
      return;
  case SIGQUIT:
      mudlog ("SIGNAL: SIGQUIT");
      sprintf(msg,"SIGQUIT[%d]",sig);
      return;
  case SIGALRM:
      sig_timer_happened = True;
      return;
  case SIGSEGV:
      mudlog ("SIGNAL: SIGSEGV[%d] received", sig);
      sprintf(msg,"SIGSEGV[%d]",sig);
      break;
  case SIGBUS:
      mudlog ("SIGNAL: SIGBUS[%d] received", sig);
      sprintf(msg,"SIGBUS[%d]",sig);
      break;
  case SIGINT:
      mudlog ("SIGNAL: SIGINT[%d] received",sig);
      sprintf(msg,"SIGINT[%d]",sig);
      break;
  case SIGUSR1:
      mudlog ("SIGNAL: SIGUSR1[%d] received",sig);
      sprintf(msg,"SIGUSR2[%d]",sig);
      break;
  case SIGUSR2:
      mudlog ("SIGNAL: SIGUSR2[%d] received",sig);
      sprintf(msg,"SIGUSR2[%d]",sig);
      break;
  default:
      mudlog ("SIGNAL: Unknown %d received", sig);
      sprintf(msg,"Unknown[%d]",sig);
      break;
  }

  rm_pid_file();
  sig_exit(msg,sig);
}


void dump_info (void)
{ time_t x;
  
  x = time (0);
  printf ("Current time : %s", ctime (&x));
  printf ("Version      : %s (%s)\n", VERSION,MBANNER);
  printf ("Last Compile : "__DATE__" "__TIME__"\n");
  printf ("Mud Owner    : %s\n",MASTERUSER);       
#ifdef REBOOT
  printf ("Reboot Crash handler has been installed.\n");
#endif
  return;
}

#ifdef REBOOT
void sysreboot(Boolean crash, int will_update)
{ int in_bin;
  char filename[256];
  char portinfo[256];
  
  FILE *lock;

  lock = fopen(".lock", "r");
  if (lock != NULL)
  {
     broad("&+wREBOOT CANCELLED: COMPILE IN PROGRESS\n");
     fclose(lock);
     return;
  }
  if (crash)
  {
    broad("&+w[&+wWorld will update to prevent crash&+w]&*\n");
    broad("As you look at the sky you can see a red glow appearing on the blue skyline.\n"
          "You can hear the church bells ringing, as a sign to seek shelter. The Driver\n"
          "desperately tries to get a grip on things, but slowly the world crashes into\n"
          "oblivion, leaving the Driver to reconstruct the world.\n");
  } 
  else
     broad("As you look around you can see the edges of the world slowly fading away\n"
        "in one giant black hole, which seems to be feeding itself on the very\n"
        "soil you stand on.\n");
 
  sprintf(portinfo,"-p %d",port_number);
  if (access ("../drv/bin/aberd", F_OK) != -1)
    in_bin = 1;
  else if (access ("../drv/src/aberd", F_OK) != -1)
    in_bin = 0;
  else {
    bprintf ("Sorry, couldn't find aberd in ../drv/bin/ or ../drv/src/\n");
    return;
  }

#ifdef ABERCHAT 
  aberchat_shutdown(); 
#endif

  signal (SIGALRM, SIG_IGN);
  dump_recovery(will_update);
  close_userfile(); 
  sprintf (filename, "%d", getpid ());
  mudlog ("SYSTEM: %s %s(file: %s)", will_update ? "UPDATE" : "REBOOT",
	(crash) ? "Crash occured " : "",filename);
  unlink (pidFileName);
  if (in_bin)
    execl ("../drv/bin/aberd", "../drv/bin/aberd", "-r", filename, portinfo, NULL);
  else
    execl ("../drv/src/aberd", "../drv/src/aberd", "-r", filename, portinfo, NULL);
}

static int xmain_reboot (int fd)
{ Boolean will_update;
  char p[10];
  char *str= "Slowly but surely the world returns to its natural form to begin.\n"
           "a new life on the other side of the black hole.\n";
 
  if (open_logfile(LOG_FILE,clear_syslog_file) < 0) 
  {  close(fd);
     return -1;
  }

  /* Write PID in PID_FILE */
  sprintf(p,"%d",getpid());
  write(fd,p,strlen(p));
  close(fd);
  
  load_recovery(old_proc_num,&will_update);

  if (will_update)
  {  broad(str);
     send_msg(DEST_ALL,MODE_BRACKET,LVL_ARCHWIZARD,LVL_MAX,NOBODY,NOBODY,
              "Update Completed");
  } 
  else 
  {   broad("Slowly but surely the world takes back it's normal form as it is being\n"
            "reconstructed by the game driver.\n");
  }
  
  main_loop(main_socket);
  mudlog( "SYSTEM: Closing listening socket");

#ifdef INTERMUD
  imShutdown(0);
#endif
  close(main_socket);
  return 0;
}

#endif

void initialize_slot(int slot)
{    players[slot].fil_des = -1;
     players[slot].stream = NULL;
     players[slot].board = NULL;
     players[slot].writer = NULL;
     players[slot].defrob = NULL;
     players[slot].editor.active = False;
     players[slot].no_echo = False;
     players[slot].announced = False;
     players[slot].isawiz = False;
     players[slot].linkdead = False;
     players[slot].ismonitored = False;
     players[slot].iamon = False;
     players[slot].in_pbfr = False;
     players[slot].aliased = False;
     players[slot].me_ivct = 0;
     players[slot].polymorphed = -1;
     players[slot].i_follow = -1;
     players[slot].snooptarget = -1;
     players[slot].pretend = -1;
     players[slot].snooped = 0;
     players[slot].asmortal = 0;
     players[slot].inmailer = 0;
     players[slot].tr.trace_item = -1;
     players[slot].converse.active = False;
     players[slot].converse.talking_to = -1;
     players[slot].last_cmd = players[slot].logged_on = global_clock;
     players[slot].last_command = global_clock;
     strcpy (players[slot].prev_com, "quit");
     players[slot].quit_next = -2;
     players[slot].wd_it = NULL;
#ifdef ABERCHAT
     players[slot].amud = players[slot].atarget = NULL;
#endif
     players[slot].wd_them = players[slot].wd_him;
     *players[slot].wd_him = *players[slot].wd_her = '\0';
#ifdef GROUP
     players[slot].party = NULL;
     players[slot].share = 0;
#endif 
     setpwpn(slot,-1);
     setphelping(slot, -1);
     setpfighting(slot, -1);
     setpsitting(slot, 0);
     setpname(slot,"\000\000\000");
}


#ifdef KEEP_LINKDEAD
/*
**  Cleanup and close the file descriptor of a linkdead player, without 
**  actually kicking them out of the game.  -Ithor
*/
static void cleanup_link(void)
{ INP_HANDLER *i, *j;
  char b[256];
  int fd;
  int me = real_mynum;

  send_msg(ploc(me), 0, pvis(me), LVL_MAX, me, NOBODY,
	   "%s turns into a stone statue.\n", pname(me), psex(me)?"her":"his");
  
if (pvis(mynum) < LVL_DEMI)
{
  if (pfighting(mynum) >= 0) 
  {
    int plx;
    
    if (cur_player->aliased) 
    {
      send_msg(DEST_ALL, MODE_QUIET|MODE_BRACKET,Max(pvis(me), LVL_WIZARD), LVL_MAX, mynum, me,
	       "%s (aliased to %s) has lost link in %s&+w (%s)&+w]\n"
	       "&+w[&+w%s (str %d) was fighting %s (str %d)",
	       pname(me), pname(mynum), sdesc(ploc(mynum)),
	       xshowname(b,ploc(mynum)),
	       pname(mynum), pstr(mynum),
	       pname(pfighting(mynum)),
	       pstr(pfighting(mynum)));
       if (pvis(mynum) > (LVL_GOD+1))
       {  mudlog("CONN: %s (aliased to %s) (str %d) has lost their link",
	               pname(me), pname(mynum), pstr(mynum));
	        mudlog("CONN (%s): while fighting %s (str %d)",
	               pname(me), pname(pfighting(mynum)), pstr(pfighting(mynum)));
       }
    } 
    else 
    {
      send_msg(DEST_ALL, MODE_QUIET|MODE_COLOR,
	       Max(pvis(mynum), LVL_WIZARD),
	       LVL_MAX, mynum, NOBODY,
	       "[&+w%s has lost link in %s&+w (%s)&+w]\n"
	       "&+w[&+w%s (str %d) was fighting %s (str %d)&+w]&*\n",
	       pname(mynum), sdesc(ploc(mynum)),
	       xshowname(b,ploc(mynum)),
	       pname(mynum), pstr(mynum),
	       pname(pfighting(mynum)),
	       pstr(pfighting(mynum)));                             
     	  if (pvis(mynum) > (LVL_GOD+1))
        {  mudlog("CONN: %s (str %d) has lost their link",
	               pname(mynum), pstr(mynum)); 
	         mudlog("CONN (%s):while fighting %s (str %d)",
	               pname(mynum),pname(pfighting(mynum)), pstr(pfighting(mynum)));
        }
    }
    
    for (plx = 0; plx < numchars; plx++) 
    {
      if (pfighting(plx) == mynum) 
      {
	setpfighting(plx, -1);
	set_hate(plx, mynum);
      }
    }
    setpfighting(mynum, -1);
  } 
  else 
  {
    if (cur_player->aliased) 
    {
      send_msg(DEST_ALL, MODE_QUIET|MODE_BRACKET, 
	       Max(pvis(me), LVL_WIZARD), 
	       LVL_MAX, me, NOBODY,
	       "%s (aliased to %s) has lost link in %s&+w (%s)",
	       pname(me), pname(mynum), sdesc(ploc(mynum)),
	       xshowname(b,ploc(mynum)));
	    if (pvis(mynum) > (LVL_GOD+1))
         mudlog("CONN: %s (aliased to %s) has lost their link",
	       pname(me), pname(mynum));
    } 
    else 
    {
      send_msg(DEST_ALL, MODE_QUIET|MODE_BRACKET,
	       Max(pvis(mynum), LVL_WIZARD), 
	       LVL_MAX, mynum, NOBODY,
	       "%s has lost link in %s&+w (%s)",
	       pname(mynum), sdesc(ploc(mynum)),
	       xshowname(b,ploc(mynum)));
	    if (pvis(mynum) > (LVL_GOD+1))
         mudlog("CONN: %s has lost their link", pname(mynum));
    }
  }
}

  if (P_GROUP(real_mynum) != NULL)
  {   sprintf(b,"%s has gone linkdead.",pname(real_mynum));
      partyannounce(b);
  }

  save_player(real_mynum,True);

#if 0
  if (mob_fun(real_mynum) != NULL)
  {   param_s.plx = real_mynum;
      mob_fun(real_mynum)(E_STORE);
  }
#endif

  fd = cur_player->fil_des;
  
  if (cur_player->inmailer)
    abort_mail();
    
  bflush();

  /* Reset idle time if we idle link dead people out at special time */
  if (KEEP_LINKDEAD > 0)
    cur_player->last_cmd = global_clock;

  /*  Free all the input handlers */
  i = cur_player->inp_handler;
  while (i != NULL) 
  {
    j = i;
    i = i->next;
    free(j);
  }
  cur_player->inp_handler = NULL;
  cur_player->linkdead = True;

  if (cur_player->stream != NULL) 
  {
    fclose(cur_player->stream);
    cur_player->stream = NULL;
  }

  if(cur_player->fil_des != -1 && cur_player->fil_des) 
  {
    if(FD_ISSET(fd,&buffer_fds))          /* Erkk! Hopefully the fix      */
      inp_buf_c--;                        /* for the processor eating bug */
    FD_CLR(fd,&sockets_fds);
    FD_CLR(fd,&buffer_fds);
    close(fd);
  }
  
  cur_player->fil_des = -1;
  
}

#endif 

Site Stats

Snippets: 1791
Codebases: 571