#include <stdio.h>		/* for stderr, fprintf() */
#include <stdlib.h>
#include <errno.h>
#include <syslog.h>		/* for LOG_ALERT, syslog() */
#include <sys/fcntl.h>
#include <sys/types.h>		/* for uid_t */
#include <pwd.h>		/* for struct passwd, getpwnam */
#include <unistd.h>		/* for seteuid() */
#include <sys/time.h>		/* for stuff in resource.h */
#include <sys/resource.h>	/* for struct rlimit, RLIM_INFINITY,
				 * RLIMIT_NPROC, setrlimit() */
#include <netdb.h>
#include <sys/param.h>
#include <signal.h>
#include <comdef.h>
#include <misc.h>
#include <log.h>
#include <poserr.h>
#include <x25io.h>
#include <inetcis-types.h>

#ifndef MAXSTRLEN
#define MAXSTRLEN 255
#endif

void 
become_user (char *user_name)
{
  struct passwd  *user_passwd_entry_ptr;
  uid_t           new_uid;
  int             status;

  /*
   * Get uid for user user_name.  If this doesn't work, we cannot continue
   * because we would end up opening a xpad as root, which screw up whoever
   * was already using that xpad.
   */

  user_passwd_entry_ptr = getpwnam (user_name);
  if (user_passwd_entry_ptr == GETPWNAM_ERROR) {
    Write_System_Error_To_Log (LOG_LEVEL_ALERT, __FILE__, __LINE__,
			       errno, user_name, "getpwnam",
			       "USR", "Gateway user error");
    exit (EXIT_FAILURE);
  }
  new_uid = user_passwd_entry_ptr->pw_uid;

  /*
   * Set the effective uid for this process to be the uid of the user
   * user_name.  If this doesn't work we cannot continue for the same reason
   * as specified for getpwnam.
   */

  status = seteuid (new_uid);
  if (status == SETEUID_ERROR) {
    char            str_new_uid[16];
    snprintf (str_new_uid, 15, "%d", new_uid);
    Write_System_Error_To_Log (LOG_LEVEL_ALERT, __FILE__, __LINE__,
			       errno, str_new_uid, "seteuid", "UID",
			       "Gateway user id error");
    exit (EXIT_FAILURE);
  }
  Write_Va_Message_To_Log (LOG_LEVEL_DEBUG0, __FILE__, __LINE__,
			   "became user %s", user_name);

  /*
   * Change working directory to home directory of the user as who we are now
   * running.  This is mainly done so that core files can successfully be
   * written to a directory that we have write access to.  We don't really
   * need to exit or return failure if it doesn't work.  Just logging the
   * error will be enough.
   */

  status = chdir (user_passwd_entry_ptr->pw_dir);
  if (status == CHDIR_ERROR) {
    Write_System_Error_To_Log (LOG_LEVEL_ERR, __FILE__, __LINE__,
			       errno, user_passwd_entry_ptr->pw_dir,
			       "chdir", "DIR", "Gateway directory error");
  }
}
/* end of become_user */



void 
increase_process_limit ()
{
  struct rlimit   process_limit_struct;
  int             status;

  /*
   * Set limits for number of processes to RLIM_INFINITY.  If this doesn't
   * work we can still continue in hopes that the soft limit hasn't been
   * reached yet.
   */

  status = getrlimit (RLIMIT_NPROC, &process_limit_struct);
  if (status == GETRLIMIT_ERROR) {
    Log_Hidden_System_Error (LOG_LEVEL_ALERT, __FILE__, __LINE__, errno,
			     "process limit information", "getrlimit",
			     "Could not get process limit structure");
  }
  process_limit_struct.rlim_cur = process_limit_struct.rlim_max;

  status = setrlimit (RLIMIT_NPROC, &process_limit_struct);
  if (status == SETRLIMIT_ERROR) {
    Log_Hidden_System_Error (LOG_LEVEL_ALERT, __FILE__, __LINE__, errno,
			     "process limit", "setrlimit",
			     "Could not set process limit");
  } else {
    Write_Va_Message_To_Log (LOG_LEVEL_DEBUG0, __FILE__, __LINE__,
			     "Set process limit to %d",
			     process_limit_struct.rlim_max);
  }
}


void 
Strip_Leading_CRs_And_LFs (char *s_in, char *s_out, int size_in,
			   int *size_out)
/*
 * Functional Description:
 * 
 * Removes any carriage returns or line feeds found at the beginning of s_in.
 * It processes s_in until it finds a character other than a carriage return
 * or line feed.
 * 
 * Formal Parameters:
 * 
 * s_in (read only)incoming string which is not NULL terminated s_out    -
 * outgoing string which is not NULL terminated size_in  - number of
 * characters in s_in size_out - number of characters in the resulting string
 * s_out
 * 
 * Implicit Parameters:
 * 
 * none
 * 
 * Return Values:
 * 
 * s_out, size_out
 * 
 * Side Effects:
 * 
 * none
 * 
 */

{
  int             i = 0;
  int             j = 0;

  while (s_in[i] == '\r' || s_in[i] == '\n')
    i++;

  while (i < size_in) {
    s_out[j++] = s_in[i++];
  }

  *size_out = j;
}







void 
signal_handler (int signal_number)
{
  char            signal_number_ascii[10];

  (void) signal (SIGSEGV, SIG_DFL);
  (void) signal (SIGPIPE, SIG_DFL);

  switch (signal_number) {
  case SIGSEGV:
    Write_Error_To_Log (LOG_LEVEL_CRIT, __FILE__, __LINE__, "SIGSEGV",
			"unknown - check core dump", "INE",
			"Gateway software internal error");
    abort ();
    break;

  case SIGPIPE:
    Write_Error_To_Log (LOG_LEVEL_ERR, __FILE__, __LINE__, "SIGPIPE",
			"most likely a disconnect caused by SO_KEEPALIVE",
			"NRT", "No response timeout");
    exit (EXIT_FAILURE);
    break;

  default:
    sprintf (signal_number_ascii, "%d", signal_number);
    Write_Error_To_Log (LOG_LEVEL_ERR, __FILE__, __LINE__,
			signal_number_ascii,
			"unknown", "UEX", "Unexpected signal caught");
    exit (EXIT_FAILURE);
    break;
  }

  exit (EXIT_FAILURE);
}

u_short 
Convert_Service_To_Port (char *service)
{
  struct servent *service_info_ptr;

  service_info_ptr = getservbyname (service, (char *) NULL);
  if (service_info_ptr == GETSERVBYNAME_ERROR) {
    Write_System_Error_To_Log (LOG_LEVEL_WARNING, __FILE__, __LINE__, errno,
			       service, "getservbyname", "N/A",
			       "could not get port number for service");
    if (strcmp (service, "inetcis") == 0)
      return htons (4144);
    else if (strcmp (service, "inetcis-cmd") == 0)
      return htons (4148);
    else {
      Write_Error_To_Log (LOG_LEVEL_ERR, __FILE__, __LINE__, service,
			  "guessing port number", "N/A",
			  "could not guess port number for service");
      return FAILURE;
    }
  } else {
    return service_info_ptr->s_port;
  }
}

int 
Position_File_Descriptor (int *fd_ptr, int position)
{
  int             old_position;
  int             new_position;

  if (fd_ptr == NULL)
    return FAILURE;

  old_position = *fd_ptr;
  if (old_position == position)
    return SUCCESS;
  new_position = fcntl (old_position, F_DUPFD, position);
  if (new_position == FCNTL_ERROR) {
    char            fd_string[MAXSTRLEN + 1];
    sprintf (fd_string, "%d", old_position);
    Write_System_Error_To_Log (LOG_LEVEL_ERR, __FILE__, __LINE__, errno,
			       fd_string, "fcntl", "N/A",
			       "could not duplicate file descriptor");
    return FAILURE;
  }
  Close_Descriptor (old_position);
  *fd_ptr = new_position;  /* change value of *fd_ptr only for SUCCESS */
  return SUCCESS;
}


int
Close_Descriptor (int fd)
{
  int num_interrupts = 0;

  while (close (fd) == CLOSE_ERROR) {
    /* Log the error. */
    char fd_string[MAXSTRLEN + 1];
    int errno_bak;
    errno_bak = errno;
    sprintf (fd_string, "%d", fd);
    Log_Hidden_System_Error (LOG_LEVEL_ERR, __FILE__, __LINE__, errno,
			     fd_string, "close",
			     "failed to close file descriptor");
    if (errno_bak == EINTR) {
      if (num_interrupts++ > 3)
	return FAILURE;
      continue;
    } else if (errno_bak == EBADF) {
      return SUCCESS;
    } else {
      return FAILURE;
    } /* if */
  } /* while */

  return SUCCESS;
}


int
max3 (int one, int two, int three)
{
  int             biggest;

  if (one >= two)
    biggest = one;
  else
    biggest = two;

  if (biggest >= three)
    return biggest;
  else
    return three;
}

/*
 * Set_Nonblock_Mode is unused and untested.
 */

int
Set_Nonblock_Mode (int fd)
{
  int             flags;

  flags = fcntl (fd, F_GETFL, 0);
  if (flags == FCNTL_ERROR) {
    Write_System_Error_To_Log (LOG_LEVEL_WARNING, __FILE__, __LINE__, errno,
			       "flags", "fcntl", "GDF",
			       "Could not get descriptor flags");
    return 0;
  }
  if (flags & O_NONBLOCK)
    return 1;

  flags = fcntl (fd, F_SETFL, O_NONBLOCK);
  if (flags == FCNTL_ERROR) {
    Write_System_Error_To_Log (LOG_LEVEL_WARNING, __FILE__, __LINE__, errno,
			       "flags", "fcntl", "SDF",
			       "Could not set descriptor flags");
    return 0;
  }
}


void
Trim_String (char *s)
{
  int i, j;
  int new_length;

  /* Trim space off the end. */
  i = strlen(s) - 1;
  while (isspace(s[i]))
    i--;
  s[i + 1] = '\0';

  /* Trim space off the beginning. */
  i = 0;
  while (isspace(s[i]))
    i++;

  new_length = strlen(s);
  if (i != 0) {
    j = 0;
    while (i <= new_length)  /* Copy the end of string char too. */
      s[j++] = s[i++];
  }
}
    
