/*
 * Part of Very Secure FTPd
 * Licence: GPL v2
 * Author: Chris Evans
 * 
 * sysutil.c
 *
 * Routines to make the libc/syscall API more pleasant to use. Long term,
 * more libc/syscalls will go in here to reduce the number of .c files with
 * dependencies on libc or syscalls.
 */

#define PRIVATE_HANDS_OFF_syscall_retval syscall_retval
#define PRIVATE_HANDS_OFF_exit_status exit_status
#include "sysutil.h"
#include "utility.h"
#include "tunables.h"
#include "sysdeputil.h"

/* Activate 64-bit file support on Linux/32bit plus others */
#define _FILE_OFFSET_BITS 64
#define _LARGEFILE_SOURCE 1
#define _LARGEFILE64_SOURCE 1
#define _LARGE_FILES 1

/* For Linux, this adds nothing :-) */
#include "port/porting_junk.h"

#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <stdio.h>
#include <dirent.h>
#include <time.h>
#include <arpa/inet.h>
#include <errno.h>
#include <pwd.h>
#include <grp.h>
#include <ctype.h>
#include <sys/wait.h>
#include <sys/time.h>
/* Must be before netinet/ip.h. Found on FreeBSD, Solaris */
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <limits.h>
#include <syslog.h>
#include <utime.h>
#include <netdb.h>
#include <sys/resource.h>

/* Private variables to this file */
/* Current umask() */
static unsigned int s_current_umask;
/* Cached time */
static struct timeval s_current_time;
/* Current pid */
static int s_current_pid = -1;
/* Exit function */
static exitfunc_t s_exit_func;
/* Difference in timezone from GMT in seconds */
static long s_timezone;

/* Our internal signal handling implementation details */
static struct vsf_sysutil_sig_details
{
  vsf_sighandle_t sync_sig_handler;
  void* p_private;
  volatile sig_atomic_t pending;
  int running;
  int use_alarm;
} s_sig_details[NSIG];

static vsf_context_io_t s_io_handler;
static void* s_p_io_handler_private;
static int s_io_handler_running;

struct vsf_sysutil_sockaddr
{
  union
  {
    struct sockaddr u_sockaddr;
    struct sockaddr_in u_sockaddr_in;
    struct sockaddr_in6 u_sockaddr_in6;
  } u;
};

/* File locals */
static void vsf_sysutil_common_sighandler(int signum);
static void vsf_sysutil_alrm_sighandler(int signum);
static int vsf_sysutil_translate_sig(const enum EVSFSysUtilSignal sig);
static void vsf_sysutil_set_sighandler(int sig, void (*p_handlefunc)(int));
static int vsf_sysutil_translate_memprot(
  const enum EVSFSysUtilMapPermission perm);
static int vsf_sysutil_translate_openmode(
  const enum EVSFSysUtilOpenMode mode);
static void vsf_sysutil_alloc_statbuf(struct vsf_sysutil_statbuf** p_ptr);
void vsf_sysutil_sockaddr_alloc(struct vsf_sysutil_sockaddr** p_sockptr);
static int lock_internal(int fd, int lock_type);

static void
vsf_sysutil_alrm_sighandler(int signum)
{
  (void) signum;
  alarm(1);
}

static void
vsf_sysutil_common_sighandler(int signum)
{
  if (signum < 0 || signum >= NSIG)
  {
    /* "cannot happen" */
    return;
  }
  if (s_sig_details[signum].sync_sig_handler)
  {
    s_sig_details[signum].pending = 1;
    /* Since this synchronous signal framework has a small race (signal coming
     * in just before we start a blocking call), there's the option to fire an
     * alarm repeatedly until the signal is handled.
     */
    if (s_sig_details[signum].use_alarm)
    {
      alarm(1);
    }
  }
}

/* Notes. This signal check is evaluated after potentially blocking system
 * calls, i.e. at highly defined points in the code. Since we only interrupt
 * at these definite locations, the signal handlers can be non-trivial
 * without us having to worry about re-entrancy.
 *
 * We guarantee that a handler for a given signal is not re-entrant. This
 * is taken care of by the "running" flag.
 *
 * This call itself can only be re-entered once we dereference the actual
 * hander function pointer, so we are safe with respect to races modifying
 * the "running" flag.
 */
void
vsf_sysutil_check_pending_actions(
  const enum EVSFSysUtilInterruptContext context, int retval, int fd)
{
  unsigned int i;
  /* Check the i/o handler before the signal handlers */
  if (s_io_handler && !s_io_handler_running && context == kVSFSysUtilIO)
  {
    s_io_handler_running = 1;
    (*s_io_handler)(retval, fd, s_p_io_handler_private);
    s_io_handler_running = 0;
  }
  for (i=0; i < NSIG; ++i)
  {
    if (s_sig_details[i].pending && !s_sig_details[i].running)
    {
      s_sig_details[i].running = 1;
      if (s_sig_details[i].use_alarm)
      {
        alarm(0);
      }
      if (s_sig_details[i].sync_sig_handler)
      {
        s_sig_details[i].pending = 0;
        (*(s_sig_details[i].sync_sig_handler))(s_sig_details[i].p_private);
      }
      s_sig_details[i].running = 0;
    }
  }
}

static int
vsf_sysutil_translate_sig(const enum EVSFSysUtilSignal sig)
{
  int realsig = 0;
  switch (sig)
  {
    case kVSFSysUtilSigALRM:
      realsig = SIGALRM;
      break;
    case kVSFSysUtilSigTERM:
      realsig = SIGTERM;
      break;
    case kVSFSysUtilSigCHLD:
      realsig = SIGCHLD;
      break;
    case kVSFSysUtilSigPIPE:
      realsig = SIGPIPE;
      break;
    case kVSFSysUtilSigURG:
      realsig = SIGURG;
      break;
    case kVSFSysUtilSigHUP:
      realsig = SIGHUP;
      break;
    case kVSFSysUtilSigUSR1:
      realsig = SIGUSR1;
      break;
    default:
      bug("unknown signal in vsf_sysutil_translate_sig");
      break;
  }
  if (realsig < 0 || realsig >= NSIG)
  {
    bug("signal out of range in vsf_sysutil_translate_sig");
  }
  return realsig;
}

void
vsf_sysutil_install_sighandler(const enum EVSFSysUtilSignal sig,
                               vsf_sighandle_t handler,
                               void* p_private,
                               int use_alarm)
{
  int realsig = vsf_sysutil_translate_sig(sig);
  s_sig_details[realsig].p_private = p_private;
  s_sig_details[realsig].sync_sig_handler = handler;
  s_sig_details[realsig].use_alarm = use_alarm;
  vsf_sysutil_set_sighandler(realsig, vsf_sysutil_common_sighandler);
  if (use_alarm && realsig != SIGALRM)
  {
    vsf_sysutil_set_sighandler(SIGALRM, vsf_sysutil_alrm_sighandler);
  }
}

void
vsf_sysutil_default_sig(const enum EVSFSysUtilSignal sig)
{
  int realsig = vsf_sysutil_translate_sig(sig);
  vsf_sysutil_set_sighandler(realsig, SIG_DFL);
  s_sig_details[realsig].p_private = NULL;
  s_sig_details[realsig].sync_sig_handler = NULL;
}

void
vsf_sysutil_install_null_sighandler(const enum EVSFSysUtilSignal sig)
{
  int realsig = vsf_sysutil_translate_sig(sig);
  s_sig_details[realsig].p_private = NULL;
  s_sig_details[realsig].sync_sig_handler = NULL;
  vsf_sysutil_set_sighandler(realsig, vsf_sysutil_common_sighandler);
}

void
vsf_sysutil_install_async_sighandler(const enum EVSFSysUtilSignal sig,
                                     vsf_async_sighandle_t handler)
{
  int realsig = vsf_sysutil_translate_sig(sig);
  s_sig_details[realsig].p_private = NULL;
  s_sig_details[realsig].sync_sig_handler = NULL;
  vsf_sysutil_block_sig(sig);
  vsf_sysutil_set_sighandler(realsig, handler);
}

static void
vsf_sysutil_set_sighandler(int sig, void (*p_handlefunc)(int))
{
  int retval;
  struct sigaction sigact;
  vsf_sysutil_memclr(&sigact, sizeof(sigact));
  sigact.sa_handler = p_handlefunc;
  retval = sigfillset(&sigact.sa_mask);
  if (retval != 0)
  {
    die("sigfillset");
  }
  retval = sigaction(sig, &sigact, NULL);
  if (retval != 0)
  {
    die("sigaction");
  }
}

void
vsf_sysutil_block_sig(const enum EVSFSysUtilSignal sig)
{
  sigset_t sset;
  int retval;
  int realsig = vsf_sysutil_translate_sig(sig);
  retval = sigemptyset(&sset);
  if (retval != 0)
  {
    die("sigemptyset");
  }
  retval = sigaddset(&sset, realsig);
  if (retval != 0)
  {
    die("sigaddset");
  }
  retval = sigprocmask(SIG_BLOCK, &sset, NULL);
  if (retval != 0)
  {
    die("sigprocmask");
  }
}

void
vsf_sysutil_unblock_sig(const enum EVSFSysUtilSignal sig)
{
  sigset_t sset;
  int retval;
  int realsig = vsf_sysutil_translate_sig(sig);
  retval = sigemptyset(&sset);
  if (retval != 0)
  {
    die("sigemptyset");
  }
  retval = sigaddset(&sset, realsig);
  if (retval != 0)
  {
    die("sigaddset");
  }
  retval = sigprocmask(SIG_UNBLOCK, &sset, NULL);
  if (retval != 0)
  {
    die("sigprocmask");
  }
}
void
vsf_sysutil_install_io_handler(vsf_context_io_t handler, void* p_private)
{
  if (s_io_handler != NULL)
  {
    bug("double register of i/o handler");
  }
  s_io_handler = handler;
  s_p_io_handler_private = p_private;
}

void
vsf_sysutil_uninstall_io_handler(void)
{
  if (s_io_handler == NULL)
  {
    bug("no i/o handler to unregister!");
  }
  s_io_handler = NULL;
  s_p_io_handler_private = NULL;
}

void
vsf_sysutil_set_alarm(const unsigned int trigger_seconds)
{
  (void) alarm(trigger_seconds);
}

void
vsf_sysutil_clear_alarm(void)
{
  vsf_sysutil_set_alarm(0);
}

int
vsf_sysutil_read(const int fd, void* p_buf, const unsigned int size)
{
  while (1)
  {
    int retval = read(fd, p_buf, size);
    int saved_errno = errno;
    vsf_sysutil_check_pending_actions(kVSFSysUtilIO, retval, fd);
    if (retval < 0 && saved_errno == EINTR)
    {
      continue;
    }
    return retval;
  }
}

int
vsf_sysutil_write(const int fd, const void* p_buf, const unsigned int size)
{
  while (1)
  {
    int retval = write(fd, p_buf, size);
    int saved_errno = errno;
    vsf_sysutil_check_pending_actions(kVSFSysUtilIO, retval, fd);
    if (retval < 0 && saved_errno == EINTR)
    {
      continue;
    }
    return retval;
  }
}

int
vsf_sysutil_read_loop(const int fd, void* p_buf, unsigned int size)
{
  int retval;
  int num_read = 0;
  if (size > INT_MAX)
  {
    die("size too big in vsf_sysutil_read_loop");
  }
  while (1)
  {
    retval = vsf_sysutil_read(fd, (char*)p_buf + num_read, size);
    if (retval < 0)
    {
      return retval;
    }
    else if (retval == 0)
    {
      /* Read all we're going to read.. */
      return num_read; 
    }
    if ((unsigned int) retval > size)
    {
      die("retval too big in vsf_sysutil_read_loop");
    }
    num_read += retval;
    size -= (unsigned int) retval;
    if (size == 0)
    {
      /* Hit the read target, cool. */
      return num_read;
    }
  }
}

int
vsf_sysutil_write_loop(const int fd, const void* p_buf, unsigned int size)
{
  int retval;
  int num_written = 0;
  if (size > INT_MAX)
  {
    die("size too big in vsf_sysutil_write_loop");
  }
  while (1)
  {
    retval = vsf_sysutil_write(fd, (const char*)p_buf + num_written, size);
    if (retval < 0)
    {
      /* Error */
      return retval;
    }
    else if (retval == 0)
    {
      /* Written all we're going to write.. */
      return num_written;
    }
    if ((unsigned int) retval > size)
    {
      die("retval too big in vsf_sysutil_write_loop");
    }
    num_written += retval;
    size -= (unsigned int) retval;
    if (size == 0)
    {
      /* Hit the write target, cool. */
      return num_written;
    }
  }
}

filesize_t
vsf_sysutil_get_file_offset(const int file_fd)
{
  filesize_t retval = lseek(file_fd, 0, SEEK_CUR);
  if (retval < 0)
  {
    die("lseek");
  }
  return retval;
}

void
vsf_sysutil_lseek_to(const int fd, filesize_t seek_pos)
{
  filesize_t retval;
  if (seek_pos < 0)
  {
    die("negative seek_pos in vsf_sysutil_lseek_to");
  }
  retval = lseek(fd, seek_pos, SEEK_SET);
  if (retval < 0)
  {
    die("lseek");
  }
}

void
vsf_sysutil_lseek_end(const int fd)
{
  filesize_t retval;
  retval = lseek(fd, 0, SEEK_END);
  if (retval < 0)
  {
    die("lseek");
  }
}

void
vsf_sysutil_fillbuff(void* buff, unsigned int size, char chr)
{
  if (size == 0 || size > INT_MAX || buff == NULL)
  {
    return;
  }
  while (size != 0)
  {
    *(char*)buff = chr;
    buff++;
    size--;
  }
  return;
}

void*
vsf_sysutil_malloc(unsigned int size)
{
  void* p_ret;
  /* Paranoia - what if we got an integer overflow/underflow? */
  if (size == 0 || size > INT_MAX)
  {
    bug("zero or big size in vsf_sysutil_malloc");
  }  
  p_ret = malloc(size);
  if (p_ret == NULL)
  {
    die("malloc");
  }
  return p_ret;
}

void*
vsf_sysutil_malloc_zero(unsigned int size)
{
  void* p_ret;
  p_ret = vsf_sysutil_malloc(size);
  vsf_sysutil_fillbuff(p_ret, size, 0);
  return p_ret;
}

void*
vsf_sysutil_realloc(void* p_ptr, unsigned int size)
{
  void* p_ret;
  if (size == 0 || size > INT_MAX)
  {
    bug("zero or big size in vsf_sysutil_realloc");
  }
  p_ret = realloc(p_ptr, size);
  if (p_ret == NULL)
  {
    die("realloc");
  }
  return p_ret;
}

void
vsf_sysutil_free(void* p_ptr)
{
  if (p_ptr == NULL)
  {
    bug("vsf_sysutil_free got a null pointer");
  }
  free(p_ptr);
}

unsigned int
vsf_sysutil_getpid(void)
{
  if (s_current_pid == -1)
  {
    s_current_pid = vsf_sysutil_getpid_nocache();
  }
  return (unsigned int) s_current_pid;
}

unsigned int
vsf_sysutil_getppid(void)
{
  return (unsigned int)getppid();
}

int
vsf_sysutil_fork(void)
{
  /* Child does NOT inherit exit function */
  exitfunc_t curr_func = s_exit_func;
  int retval;
  s_exit_func = 0;
  retval = vsf_sysutil_fork_failok();
  if (retval != 0)
  {
    s_exit_func = curr_func;
  }
  if (retval < 0)
  {
    die("fork");
  }
  return retval;
}

int
vsf_sysutil_fork_failok(void)
{
  int retval;
  retval = fork();
  if (retval == 0)
  {
    vsf_sysutil_post_fork();
  }
  return retval;
}

void
vsf_sysutil_set_exit_func(exitfunc_t exitfunc)
{
  s_exit_func = exitfunc;
}

void
vsf_sysutil_exit(int exit_code)
{
  if (s_exit_func)
  {
    exitfunc_t curr_func = s_exit_func;
    /* Prevent recursion */
    s_exit_func = 0;
    (*curr_func)();
  }
  _exit(exit_code);
}

struct vsf_sysutil_wait_retval
vsf_sysutil_wait(void)
{
  struct vsf_sysutil_wait_retval retval;
  vsf_sysutil_memclr(&retval, sizeof(retval));
  while (1)
  {
    int sys_ret = wait(&retval.exit_status);
    if (sys_ret < 0 && errno == EINTR)
    {
      vsf_sysutil_check_pending_actions(kVSFSysUtilUnknown, 0, 0);
      continue;
    }
    retval.syscall_retval = sys_ret;
    return retval;
  }
}

int
vsf_sysutil_wait_reap_one(void)
{
  int retval = waitpid(-1, NULL, WNOHANG);
  if (retval == 0 || (retval < 0 && errno == ECHILD))
  {
    /* No more children */
    return 0;
  }
  if (retval < 0)
  {
    die("waitpid");
  }
  /* Got one */
  return retval;
}

int
vsf_sysutil_wait_get_retval(const struct vsf_sysutil_wait_retval* p_waitret)
{
  return p_waitret->syscall_retval;
}

int
vsf_sysutil_wait_exited_normally(
  const struct vsf_sysutil_wait_retval* p_waitret)
{
  int status = ((struct vsf_sysutil_wait_retval*) p_waitret)->exit_status;
  return WIFEXITED(status);
}

int
vsf_sysutil_wait_get_exitcode(const struct vsf_sysutil_wait_retval* p_waitret)
{
  int status;
  if (!vsf_sysutil_wait_exited_normally(p_waitret))
  {
    bug("not a normal exit in vsf_sysutil_wait_get_exitcode");
  }
  status = ((struct vsf_sysutil_wait_retval*) p_waitret)->exit_status;
  return WEXITSTATUS(status);
}

void
vsf_sysutil_activate_keepalive(int fd)
{
  int keepalive = 1;
  int retval = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive,
                          sizeof(keepalive));
  if (retval != 0)
  {
    die("setsockopt: keepalive");
  }
}

void
vsf_sysutil_activate_reuseaddr(int fd)
{
  int reuseaddr = 1;
  int retval = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr,
                          sizeof(reuseaddr));
  if (retval != 0)
  {
    die("setsockopt: reuseaddr");
  }
}

void
vsf_sysutil_set_nodelay(int fd)
{
  int nodelay = 1;
  int retval = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &nodelay,
                          sizeof(nodelay));
  if (retval != 0)
  {
    die("setsockopt: nodelay");
  }
}

void
vsf_sysutil_activate_sigurg(int fd)
{
  int retval = fcntl(fd, F_SETOWN, vsf_sysutil_getpid());
  if (retval != 0)
  {
    die("fcntl");
  }
}

void
vsf_sysutil_activate_oobinline(int fd)
{
  int oob_inline = 1;
  int retval = setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob_inline,
                          sizeof(oob_inline));
  if (retval != 0)
  {
    die("setsockopt: oobinline");
  }
}

void
vsf_sysutil_set_iptos_throughput(int fd)
{
  int tos = IPTOS_THROUGHPUT;
  /* Ignore failure to set (maybe this IP stack demands privilege for this) */
  (void) setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
}

void
vsf_sysutil_activate_linger(int fd)
{
  int retval;
  struct linger the_linger;
  vsf_sysutil_memclr(&the_linger, sizeof(the_linger));
  the_linger.l_onoff = 1;
  the_linger.l_linger = 60 * 10;
  retval = setsockopt(fd, SOL_SOCKET, SO_LINGER, &the_linger,
                      sizeof(the_linger));
  if (retval != 0)
  {
    die("setsockopt: linger");
  }
}

void
vsf_sysutil_deactivate_linger_failok(int fd)
{
  struct linger the_linger;
  the_linger.l_onoff = 0;
  the_linger.l_linger = 0;
  (void) setsockopt(fd, SOL_SOCKET, SO_LINGER, &the_linger, sizeof(the_linger));
}

void
vsf_sysutil_activate_noblock(int fd)
{
  int retval;
  int curr_flags = fcntl(fd, F_GETFL);
  if (vsf_sysutil_retval_is_error(curr_flags))
  {
    die("fcntl");
  }
  curr_flags |= O_NONBLOCK;
  retval = fcntl(fd, F_SETFL, curr_flags);
  if (retval != 0)
  {
    die("fcntl");
  }
}

void
vsf_sysutil_deactivate_noblock(int fd)
{
  int retval;
  int curr_flags = fcntl(fd, F_GETFL);
  if (vsf_sysutil_retval_is_error(curr_flags))
  {
    die("fcntl");
  }
  curr_flags &= ~O_NONBLOCK;
  retval = fcntl(fd, F_SETFL, curr_flags);
  if (retval != 0)
  {
    die("fcntl");
  }
}

int
vsf_sysutil_recv_peek(const int fd, void* p_buf, unsigned int len)
{
  while (1)
  {
    int retval = recv(fd, p_buf, len, MSG_PEEK);
    int saved_errno = errno;
    vsf_sysutil_check_pending_actions(kVSFSysUtilIO, retval, fd);
    if (retval < 0 && saved_errno == EINTR)
    {
      continue;
    }
    return retval;
  }
}

int
vsf_sysutil_atoi(const char* p_str)
{
  return atoi(p_str);
}

filesize_t
vsf_sysutil_a_to_filesize_t(const char* p_str)
{
  /* atoll() is C99 standard - but even modern FreeBSD, OpenBSD don't have
   * it, so we'll supply our own
   */
  filesize_t result = 0;
  filesize_t mult = 1;
  unsigned int len = vsf_sysutil_strlen(p_str);
  unsigned int i;
  /* Bail if the number is excessively big (petabytes!) */
  if (len > 15)
  {
    return 0;
  }
  for (i=0; i<len; ++i)
  {
    char the_char = p_str[len-(i+1)];
    filesize_t val;
    if (the_char < '0' || the_char > '9')
    {
      return 0;
    }
    val = the_char - '0';
    val *= mult;
    result += val;
    mult *= 10;
  }
  return result;
}

const char*
vsf_sysutil_ulong_to_str(unsigned long the_ulong)
{
  static char ulong_buf[32];
  (void) snprintf(ulong_buf, sizeof(ulong_buf), "%lu", the_ulong);
  return ulong_buf;
}

const char*
vsf_sysutil_ulong_to_hex(unsigned long the_ulong)
{
  static char ulong_buf[32];
  (void) snprintf(ulong_buf, sizeof(ulong_buf), "%.8lx", the_ulong);
  return ulong_buf;
}

const char*
vsf_sysutil_filesize_t_to_str(filesize_t the_filesize)
{
  static char filesize_buf[32];
  if (sizeof(long) == 8)
  {
    /* Avoid using non-standard %ll if we can */
    (void) snprintf(filesize_buf, sizeof(filesize_buf), "%ld",
                    (long) the_filesize);
  }
  else
  {
    (void) snprintf(filesize_buf, sizeof(filesize_buf), "%lld", the_filesize);
  }
  return filesize_buf;
}

const char*
vsf_sysutil_double_to_str(double the_double)
{
  static char double_buf[32];
  (void) snprintf(double_buf, sizeof(double_buf), "%.2f", the_double);
  return double_buf;
}

const char*
vsf_sysutil_uint_to_octal(unsigned int the_uint)
{
  static char octal_buf[32];
  if (the_uint == 0)
  {
    octal_buf[0] = '0';
    octal_buf[1] = '\0';
  }
  else
  {
    (void) snprintf(octal_buf, sizeof(octal_buf), "0%o", the_uint);
  }
  return octal_buf;
}

unsigned int
vsf_sysutil_octal_to_uint(const char* p_str)
{
  /* NOTE - avoiding using sscanf() parser */
  unsigned int result = 0;
  int seen_non_zero_digit = 0;
  while (*p_str != '\0')
  {
    int digit = *p_str;
    if (!isdigit(digit) || digit > '7')
    {
      break;
    }
    if (digit != '0')
    {
      seen_non_zero_digit = 1;
    }
    if (seen_non_zero_digit)
    {
      result <<= 3;
      result += (digit - '0');
    }
    p_str++;
  }
  return result;
}

int
vsf_sysutil_toupper(int the_char)
{
  return toupper((unsigned char) the_char);
}

int
vsf_sysutil_isspace(int the_char)
{
  return isspace((unsigned char) the_char);
}

int
vsf_sysutil_isprint(int the_char)
{
  /* From Solar - we know better than some libc's! Don't let any potential
   * control chars through
   */
  unsigned char uc = (unsigned char) the_char;
  if (uc <= 31)
  {
    return 0;
  }
  if (uc == 177)
  {
    return 0;
  }
  if (uc >= 128 && uc <= 159)
  {
    return 0;
  }
  return isprint(the_char);
}

int
vsf_sysutil_isalnum(int the_char)
{
  return isalnum((unsigned char) the_char);
}

int
vsf_sysutil_isdigit(int the_char)
{
  return isdigit((unsigned char) the_char);
}

char*
vsf_sysutil_getcwd(char* p_dest, const unsigned int buf_size)
{
  char* p_retval;
  if (buf_size == 0) {
    return p_dest;
  }
  p_retval = getcwd(p_dest, buf_size);
  p_dest[buf_size - 1] = '\0';
  return p_retval;
}

int
vsf_sysutil_mkdir(const char* p_dirname, const unsigned int mode)
{
  return mkdir(p_dirname, mode);
}

int
vsf_sysutil_rmdir(const char* p_dirname)
{
  return rmdir(p_dirname);
}

int
vsf_sysutil_chdir(const char* p_dirname)
{
  return chdir(p_dirname);
}

int
vsf_sysutil_rename(const char* p_from, const char* p_to)
{
  return rename(p_from, p_to);
}

struct vsf_sysutil_dir*
vsf_sysutil_opendir(const char* p_dirname)
{
  return (struct vsf_sysutil_dir*) opendir(p_dirname);
}

void
vsf_sysutil_closedir(struct vsf_sysutil_dir* p_dir)
{
  DIR* p_real_dir = (DIR*) p_dir;
  int retval = closedir(p_real_dir);
  if (retval != 0)
  {
    die("closedir");
  }
}

const char*
vsf_sysutil_next_dirent(struct vsf_sysutil_dir* p_dir)
{
  DIR* p_real_dir = (DIR*) p_dir;
  struct dirent* p_dirent = readdir(p_real_dir);
  if (p_dirent == NULL)
  {
    return NULL;
  }
  return p_dirent->d_name;
}

unsigned int
vsf_sysutil_strlen(const char* p_text)
{
  size_t ret = strlen(p_text);
  /* A defense in depth measure. */
  if (ret > INT_MAX / 8)
  {
    die("string suspiciously long");
  }
  return (unsigned int) ret;
}

char*
vsf_sysutil_strdup(const char* p_str)
{
  return strdup(p_str);
}

char*
vsf_sysutil_strndup(const char* p_str, unsigned int p_len)
{
  char *new = (char *)malloc(p_len+1);
  
  if (new == NULL)
    return NULL;
    
  new[p_len]='\0';
  return (char *)memcpy(new, p_str, p_len);
}

void
vsf_sysutil_memclr(void* p_dest, unsigned int size)
{
  /* Safety */
  if (size == 0)
  {
    return;
  }
  memset(p_dest, '\0', size);
}

void
vsf_sysutil_memcpy(void* p_dest, const void* p_src, const unsigned int size)
{
  /* Safety */
  if (size == 0)
  {
    return;
  }
  /* Defense in depth */
  if (size > INT_MAX)
  {
    die("possible negative value to memcpy?");
  }
  memcpy(p_dest, p_src, size);
}

void
vsf_sysutil_strcpy(char* p_dest, const char* p_src, unsigned int maxsize)
{
  if (maxsize == 0)
  {
    return;
  }
  strncpy(p_dest, p_src, maxsize);
  p_dest[maxsize - 1] = '\0';
}

int
vsf_sysutil_memcmp(const void* p_src1, const void* p_src2, unsigned int size)
{
  /* Safety */
  if (size == 0)
  {
    return 0;
  }
  return memcmp(p_src1, p_src2, size);
}

int
vsf_sysutil_strcmp(const char* p_src1, const char* p_src2)
{
  return strcmp(p_src1, p_src2);
}

unsigned int
vsf_sysutil_getpagesize(void)
{
  static unsigned int s_page_size;
  if (s_page_size == 0)
  {
    s_page_size = getpagesize();
    if (s_page_size == 0)
    {
      die("getpagesize");
    }
  }
  return s_page_size;
}

static int
vsf_sysutil_translate_memprot(const enum EVSFSysUtilMapPermission perm)
{
  int retval = 0;
  switch (perm)
  {
    case kVSFSysUtilMapProtReadOnly:
      retval = PROT_READ;
      break;
    case kVSFSysUtilMapProtNone:
      retval = PROT_NONE;
      break;
    default:
      bug("bad value in vsf_sysutil_translate_memprot");
      break;
  }
  return retval;
}

void
vsf_sysutil_memprotect(void* p_addr, unsigned int len,
                       const enum EVSFSysUtilMapPermission perm)
{
  int prot = vsf_sysutil_translate_memprot(perm);
  int retval = mprotect(p_addr, len, prot);
  if (retval != 0)
  {
    die("mprotect");
  }
}

void
vsf_sysutil_memunmap(void* p_start, unsigned int length)
{
  int retval = munmap(p_start, length);
  if (retval != 0)
  {
    die("munmap");
  }
}

static int
vsf_sysutil_translate_openmode(const enum EVSFSysUtilOpenMode mode)
{
  int retval = 0;
  switch (mode)
  {
    case kVSFSysUtilOpenReadOnly:
      retval = O_RDONLY;
      break;
    case kVSFSysUtilOpenWriteOnly:
      retval = O_WRONLY;
      break;
    case kVSFSysUtilOpenReadWrite:
      retval = O_RDWR;
      break;
    default:
      bug("bad mode in vsf_sysutil_translate_openmode");
      break;
  }
  return retval;
}

int
vsf_sysutil_open_file(const char* p_filename,
                      const enum EVSFSysUtilOpenMode mode)
{
  return open(p_filename, vsf_sysutil_translate_openmode(mode) | O_NONBLOCK);
}

int
vsf_sysutil_create_file_exclusive(const char* p_filename)
{
  /* umask() also contributes to end mode */
  return open(p_filename, O_CREAT | O_EXCL | O_WRONLY | O_APPEND,
              tunable_file_open_mode);
}

int
vsf_sysutil_create_or_open_file(const char* p_filename, unsigned int mode)
{
  return open(p_filename, O_CREAT | O_WRONLY | O_NONBLOCK, mode);
}

int
vsf_sysutil_create_or_open_file_append(const char* p_filename,
                                       unsigned int mode)
{
  return open(p_filename, O_CREAT | O_WRONLY | O_NONBLOCK | O_APPEND, mode);
}

void
vsf_sysutil_dupfd2(int old_fd, int new_fd)
{
  int retval;
  if (old_fd == new_fd)
  {
    return;
  }
  retval = dup2(old_fd, new_fd);
  if (retval != new_fd)
  {
    die("dup2");
  }
}

void
vsf_sysutil_close(int fd)
{
  while (1)
  {
    int retval = close(fd);
    if (retval != 0)
    {
      if (errno == EINTR)
      {
        vsf_sysutil_check_pending_actions(kVSFSysUtilUnknown, 0, 0);
        continue;
      }
      die("close");
    }
    return;
  }
}

int
vsf_sysutil_close_failok(int fd)
{
  return close(fd);
}

int
vsf_sysutil_unlink(const char* p_dead)
{
  return unlink(p_dead);
}

int
vsf_sysutil_write_access(const char* p_filename)
{
  int retval = access(p_filename, W_OK);
  return (retval == 0);
}

static void
vsf_sysutil_alloc_statbuf(struct vsf_sysutil_statbuf** p_ptr)
{
  if (*p_ptr == NULL)
  {
    *p_ptr = vsf_sysutil_malloc(sizeof(struct stat));
  }
}

void
vsf_sysutil_fstat(int fd, struct vsf_sysutil_statbuf** p_ptr)
{
  int retval;
  vsf_sysutil_alloc_statbuf(p_ptr);
  retval = fstat(fd, (struct stat*) (*p_ptr));
  if (retval != 0)
  {
    die("fstat");
  }
}

int
vsf_sysutil_stat(const char* p_name, struct vsf_sysutil_statbuf** p_ptr)
{
  vsf_sysutil_alloc_statbuf(p_ptr);
  return stat(p_name, (struct stat*) (*p_ptr));
}

int
vsf_sysutil_lstat(const char* p_name, struct vsf_sysutil_statbuf** p_ptr)
{
  vsf_sysutil_alloc_statbuf(p_ptr);
  return lstat(p_name, (struct stat*) (*p_ptr));
}

void
vsf_sysutil_dir_stat(const struct vsf_sysutil_dir* p_dir,
                     struct vsf_sysutil_statbuf** p_ptr)
{
  int fd = dirfd((DIR*) p_dir);
  vsf_sysutil_fstat(fd, p_ptr);
}

int
vsf_sysutil_statbuf_is_regfile(const struct vsf_sysutil_statbuf* p_stat)
{
  const struct stat* p_realstat = (const struct stat*) p_stat;
  return S_ISREG(p_realstat->st_mode);
}

int
vsf_sysutil_statbuf_is_symlink(const struct vsf_sysutil_statbuf* p_stat)
{
  const struct stat* p_realstat = (const struct stat*) p_stat;
  return S_ISLNK(p_realstat->st_mode);
}

int
vsf_sysutil_statbuf_is_socket(const struct vsf_sysutil_statbuf* p_stat)
{
  const struct stat* p_realstat = (const struct stat*) p_stat;
  return S_ISSOCK(p_realstat->st_mode);
}

int
vsf_sysutil_statbuf_is_dir(const struct vsf_sysutil_statbuf* p_stat)
{
  const struct stat* p_realstat = (const struct stat*) p_stat;
  return S_ISDIR(p_realstat->st_mode);
}

const char*
vsf_sysutil_statbuf_get_perms(const struct vsf_sysutil_statbuf* p_statbuf)
{
  static char perms[11];
  int i;
  const struct stat* p_stat = (const struct stat*) p_statbuf;
  for (i=0; i<10; i++)
  {
    perms[i] = '-';
  }
  perms[0] = '?';
  switch (p_stat->st_mode & S_IFMT)
  {
    case S_IFREG: perms[0] = '-'; break;
    case S_IFDIR: perms[0] = 'd'; break;
    case S_IFLNK: perms[0] = 'l'; break;
    case S_IFIFO: perms[0] = 'p'; break;
    case S_IFSOCK: perms[0] = 's'; break;
    case S_IFCHR: perms[0] = 'c'; break;
    case S_IFBLK: perms[0] = 'b'; break;
    default: break;
  }
  if (p_stat->st_mode & S_IRUSR) perms[1] = 'r';
  if (p_stat->st_mode & S_IWUSR) perms[2] = 'w';
  if (p_stat->st_mode & S_IXUSR) perms[3] = 'x';
  if (p_stat->st_mode & S_IRGRP) perms[4] = 'r';
  if (p_stat->st_mode & S_IWGRP) perms[5] = 'w';
  if (p_stat->st_mode & S_IXGRP) perms[6] = 'x';
  if (p_stat->st_mode & S_IROTH) perms[7] = 'r';
  if (p_stat->st_mode & S_IWOTH) perms[8] = 'w';
  if (p_stat->st_mode & S_IXOTH) perms[9] = 'x';
  if (p_stat->st_mode & S_ISUID) perms[3] = (perms[3] == 'x') ? 's' : 'S';
  if (p_stat->st_mode & S_ISGID) perms[6] = (perms[6] == 'x') ? 's' : 'S';
  if (p_stat->st_mode & S_ISVTX) perms[9] = (perms[9] == 'x') ? 't' : 'T';
  perms[10] = '\0';
  return perms;
}

long
vsf_sysutil_statbuf_get_filedate(const struct vsf_sysutil_statbuf* p_statbuf)
{
  const struct stat* p_stat = (const struct stat*) p_statbuf;
  return p_stat->st_mtime;
}

const char*
vsf_sysutil_statbuf_get_date(const struct vsf_sysutil_statbuf* p_statbuf,
                             int use_localtime, long curr_time)
{
  static char datebuf[64];
  int retval;
  struct tm* p_tm;
  const struct stat* p_stat = (const struct stat*) p_statbuf;
  const char* p_date_format = "%b %d %H:%M";
  if (!use_localtime)
  {
    p_tm = gmtime(&p_stat->st_mtime);
  }
  else
  {
    p_tm = localtime(&p_stat->st_mtime);
  }
  /* Is this a future or 6 months old date? If so, we drop to year format */
  if (p_stat->st_mtime > curr_time ||
      (curr_time - p_stat->st_mtime) > 60*60*24*182)
  {
    p_date_format = "%b %d  %Y";
  }
  retval = strftime(datebuf, sizeof(datebuf), p_date_format, p_tm);
  datebuf[sizeof(datebuf)-1] = '\0';
  if (retval == 0)
  {
    die("strftime");
  }
  return datebuf;
}

const char*
vsf_sysutil_statbuf_get_numeric_date(
  const struct vsf_sysutil_statbuf* p_statbuf,
  int use_localtime)
{
  static char datebuf[15];
  const struct stat* p_stat = (const struct stat*) p_statbuf;
  struct tm* p_tm;
  int retval;
  if (!use_localtime)
  {
    p_tm = gmtime(&p_stat->st_mtime);
  }
  else
  {
    p_tm = localtime(&p_stat->st_mtime);
  }
  retval = strftime(datebuf, sizeof(datebuf), "%Y%m%d%H%M%S", p_tm);
  if (retval == 0)
  {
    die("strftime");
  }
  return datebuf;
}

filesize_t
vsf_sysutil_statbuf_get_size(const struct vsf_sysutil_statbuf* p_statbuf)
{
  const struct stat* p_stat = (const struct stat*) p_statbuf;
  if (p_stat->st_size < 0)
  {
    die("invalid inode size in vsf_sysutil_statbuf_get_size");
  }
  return p_stat->st_size;
}

int
vsf_sysutil_statbuf_get_uid(const struct vsf_sysutil_statbuf* p_statbuf)
{
  const struct stat* p_stat = (const struct stat*) p_statbuf;
  return p_stat->st_uid;
}

int
vsf_sysutil_statbuf_get_gid(const struct vsf_sysutil_statbuf* p_statbuf)
{
  const struct stat* p_stat = (const struct stat*) p_statbuf;
  return p_stat->st_gid;
}

unsigned int
vsf_sysutil_statbuf_get_links(const struct vsf_sysutil_statbuf* p_statbuf)
{
  const struct stat* p_stat = (const struct stat*) p_statbuf;
  return p_stat->st_nlink;
}

int
vsf_sysutil_statbuf_is_readable_other(
  const struct vsf_sysutil_statbuf* p_statbuf)
{
  const struct stat* p_stat = (const struct stat*) p_statbuf;
  if (p_stat->st_mode & S_IROTH)
  {
    return 1;
  }
  return 0;
}

const char*
vsf_sysutil_statbuf_get_sortkey_mtime(
  const struct vsf_sysutil_statbuf* p_statbuf)
{
  static char intbuf[32];
  const struct stat* p_stat = (const struct stat*) p_statbuf;
  /* This slight hack function must return a character date format such that
   * more recent dates appear later in the alphabet! Most notably, we must
   * make sure we pad to the same length with 0's 
   */
  snprintf(intbuf, sizeof(intbuf), "%030ld", (long) p_stat->st_mtime);
  return intbuf;
}

void
vsf_sysutil_fchown(const int fd, const int uid, const 