/* server.c */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/signal.h>
#include <netdb.h>
#include <fcntl.h>
#include <unistd.h>
#include <syslog.h>
#include <netinet/in.h>
#include <arpa/inet.h>

char  cmd[]="/usr/local/etc/httpd/bin/faxconvert 2>/dev/null";
int   cli_socket;

void interrupted() {
    syslog(LOG_NOTICE,"aborted");
    exit(1);
}

int go_background(void)
{
   int fd;
   int fs;
   
   if(getppid() != 1)
   {
      signal(SIGTTOU, SIG_IGN);
      signal(SIGTTIN, SIG_IGN);
      signal(SIGTSTP, SIG_IGN);
      signal(SIGINT,(void (*)())interrupted);
      fs=fork();
      if(fs < 0)
      {
         perror("fork");
         exit(1);
      }
      if(fs > 0) exit(0);
      setpgrp();
      fd=open("/dev/tty", O_RDWR);
      if(fd >= 0)
      {
         ioctl(fd, TIOCNOTTY, (char *)NULL);
         close(fd);
      }
   }
   for(fd=0;fd < 1024;fd++) close(fd);
   errno=0;
   chdir("/");
   umask(0);
}

int main (int argc, char *argv[])
{
  /* definition of variables */
  struct sockaddr_in	sock_in;
  	 int		i, end=0, h_socket;
	 int		portnum;     /* portnumber to use */

  go_background();
  openlog("faxconvert", 0, LOG_DAEMON);

  /* initialization starts here */
  syslog(LOG_NOTICE,"faxconvert-server started");

  /* get portnumber for bind function */
  sscanf (argv[1], "%d", &portnum);
  if (portnum==0) {
      syslog(LOG_NOTICE,"argument 'portnumber' missing");
      exit(1);
  }

  if ((h_socket = socket (AF_INET, SOCK_STREAM, 0)) == -1)
  {
    syslog(LOG_NOTICE,"%s: function 'socket' failed", strerror(errno));
    exit(1);
  }

  /* bind a name to the socket */
  sock_in.sin_family = AF_INET;
  sock_in.sin_port = htons (portnum);
  sock_in.sin_addr.s_addr = htonl (INADDR_ANY);
  for (i=0; (i<sizeof (sock_in.sin_zero)); i++)
    sock_in.sin_zero[i] = 0;  

  if ((bind (h_socket, (struct sockaddr*) &sock_in, sizeof(sock_in))) == -1)
  {
    syslog(LOG_NOTICE,"%s: function 'bind' failed", strerror(errno));
    exit(1);   
  }

  /* accept requests */
  if ((listen (h_socket, 1)) == -1)
  {
    syslog(LOG_NOTICE,"%s: function 'listen' failed", strerror(errno));
    exit(1);
  }
  /* initialization part ends here */

  /* server main loop starts here*/
  while (1)
  {
    if ((cli_socket = accept (h_socket, NULL, NULL)) == -1) {
      syslog(LOG_NOTICE,"%s: function 'accept' failed", strerror(errno));
      exit(1);
    } else {
      close(cli_socket);
      switch (fork()) {
        case 0:     /* child */
          system(cmd);
          exit(0);
          break;
        default:    /* parent */
          break;
      }
    }
  }  /*end of while */
  return 0;
}

