Exemplo n.º 1
0
int
main(void)
{
  uint8_t data[64];
  char string[(sizeof(data) * 2) + 1];

  memset(data, 0xab, sizeof(data));

  if (det_data_to_hex(string, sizeof(string), data, sizeof(data)) !=
      (sizeof(string) - 1))
  {
    det_derr_msg("Failed det_data_to_hex");
    return (EXIT_FAILURE);
  }

  uint8_t buf[sizeof(data)];

  memclr(buf, sizeof(buf));

  if (det_hex_to_data(buf, sizeof(buf), string) != sizeof(data))
  {
    det_derr_msg("Failed det_hex_to_data");
    return (EXIT_FAILURE);
  }

  if (memcmp(data, buf, sizeof(data)))
  {
    det_derr_msg("Failed memcmp");
    return (EXIT_FAILURE);
  }

  return (EXIT_SUCCESS);
} // main()
Exemplo n.º 2
0
int
det_daemonize(
    const char *cmd
    )
{
  int result = -1;

  if (unlikely(!cmd))
  {
    errno = EINVAL;
    det_derr_ret("NULL parameter");
    goto errout;
  }

  umask(0); // clear file creation mask

  struct rlimit rl;

  // get max number of file descriptors
  if ((result = getrlimit(RLIMIT_NOFILE, &rl)) < 0)
  {
    det_derr_ret("%s: Failed to get file limit", cmd);
    goto errout;
  }

  pid_t pid;

  // become a session leader to lose controlling TTY
  if ((pid = fork()) < 0)
  {
    det_derr_ret("%s: Failed to fork", cmd);
    goto errout;
  }
  else if (pid != 0) // parent
  {
    det_derr_msg("Parent exiting");
    exit (0);
  }

  if ((pid = setsid()) < 0)
  {
    det_derr_ret("%s: Failed to create new session", cmd);
    goto errout;
  }

  // ensure future opens won't allocate controlling TTYs
  struct sigaction sa;
  sa.sa_handler = SIG_IGN;

  if ((result = sigemptyset(&sa.sa_mask)) < 0)
  {
    det_derr_ret("%s: Failed to clear signal set", cmd);
    goto errout;
  }

  sa.sa_flags = 0;

  if ((result = sigaction(SIGHUP, &sa, NULL)) < 0)
  {
    det_derr_ret("%s: cannot ignore SIGHUP", cmd);
    goto errout;
  }

  if ((pid = fork()) < 0)
  {
    det_derr_ret("%s: Failed to fork", cmd);
    goto errout;
  }
  else if (pid != 0) // parent
  {
    det_derr_msg("Parent exiting");
    exit (0);
  }

  /* change directory to the root so we don't prevent filesystems from
   * being unmounted
  */ 
  if ((result = chdir("/")) < 0)
  {
    det_derr_ret("%s: Failed to change directory to root", cmd);
    goto errout;
  }

  // close all open file descriptors
  if (rl.rlim_max == RLIM_INFINITY)
    rl.rlim_max = 1024;

  for (int fd = 0; fd < (int) rl.rlim_max; fd++)
    close(fd);

  // attach file descriptors 0, 1, and 2 to /dev/null
  int fd0 = open("/dev/null", O_RDWR);
  int fd1 = dup(0);
  int fd2 = dup(0);

  openlog(cmd, LOG_CONS, LOG_DAEMON);

  if (fd0 != 0 || fd1 != 1 || fd2 != 2)
  {
    syslog(LOG_ERR, "unexpected file descriptors %d %d %d",
        fd0, fd1, fd2);
    result = -1;
    goto errout;
  }

  result = 0;

errout:

  return (result);
} // det_daemonize