home *** CD-ROM | disk | FTP | other *** search
/ Dream 52 / Amiga_Dream_52.iso / Linux / Magazine / wwwoffle-2.1.tar.gz / wwwoffle-2.1 / wwwoffled.c < prev    next >
C/C++ Source or Header  |  1998-03-02  |  13KB  |  513 lines

  1. /***************************************
  2.   $Header: /home/amb/wwwoffle/RCS/wwwoffled.c 2.8 1998/03/02 15:06:00 amb Exp $
  3.  
  4.   WWWOFFLE - World Wide Web Offline Explorer - Version 2.1.
  5.   A demon program to maintain the database and spawn the servers.
  6.   ******************/ /******************
  7.   Written by Andrew M. Bishop
  8.  
  9.   This file Copyright 1996,97,98 Andrew M. Bishop
  10.   It may be distributed under the GNU Public License, version 2, or
  11.   any higher version.  See section COPYING of the GNU Public license
  12.   for conditions under which this file may be redistributed.
  13.   ***************************************/
  14.  
  15.  
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <ctype.h>
  19.  
  20. #include <sys/wait.h>
  21. #include <sys/time.h>
  22. #include <sys/types.h>
  23. #include <sys/stat.h>
  24. #include <fcntl.h>
  25. #include <unistd.h>
  26. #include <errno.h>
  27. #include <signal.h>
  28.  
  29. #include "version.h"
  30. #include "wwwoffle.h"
  31. #include "misc.h"
  32. #include "config.h"
  33. #include "sockets.h"
  34. #include "errors.h"
  35.  
  36.  
  37. static void usage(int verbose);
  38. static void demoninit(void);
  39. static void install_sighandlers(void);
  40. static void sigchild(int signum);
  41. static void sigexit(int signum);
  42. static void sighup(int signum);
  43.  
  44.  
  45. /*+ The server sockets that we listen on +*/
  46. int http_fd=-1,                 /*+ for the HTTP connections. +*/
  47.     wwwoffle_fd=-1;             /*+ for the WWWOFFLE connections. +*/
  48.  
  49. /*+ The online / offline /autodial status. +*/
  50. int online=0;
  51.  
  52. /*+ The current number active servers +*/
  53. int n_servers=0,                /*+ in total. +*/
  54.     n_fetch_servers=0;          /*+ fetching a page. +*/
  55.  
  56. /*+ The wwwoffle client file descriptor when fetching. +*/
  57. int fetch_fd=-1;
  58.  
  59. /*+ The pids of the servers that are fetching. +*/
  60. int fetch_pids[MAX_FETCH_SERVERS];
  61.  
  62. /*+ The current status, fetching or not. +*/
  63. int fetching=0;
  64.  
  65. /*+ Set to 1 when the demon is to shutdown. +*/
  66. static int closedown=0;
  67.  
  68. /*+ Set to 1 when the demon is to re-read config file due to a sighup. +*/
  69. static int readconfig=0;
  70.  
  71. /*+ Remember that we got a SIGCHLD +*/
  72. static sig_atomic_t got_sigchld=0;
  73.  
  74. /*+ True if run as a demon +*/
  75. static int detached=1;
  76.  
  77.  
  78. /*++++++++++++++++++++++++++++++++++++++
  79.   The main program.
  80.   ++++++++++++++++++++++++++++++++++++++*/
  81.  
  82. int main(int argc, char** argv)
  83. {
  84.  int i;
  85.  int err;
  86.  struct stat buf;
  87.  
  88.  /* Parse the command line options */
  89.  
  90.  for(i=1;i<argc;i++)
  91.    {
  92.     if(!strcmp(argv[i],"-h"))
  93.        usage(1);
  94.  
  95.     if(!strcmp(argv[i],"-d"))
  96.       {
  97.        detached=0;
  98.        if(i<(argc-1) && isdigit(argv[i+1][0]) && !argv[i+1][1])
  99.          {
  100.           DebugLevel=Fatal+1-atoi(argv[++i]);
  101.           if(DebugLevel<0)
  102.              DebugLevel=0;
  103.          }
  104.        continue;
  105.       }
  106.  
  107.     if(!strcmp(argv[i],"-c"))
  108.       {
  109.        if(++i>=argc)
  110.          {fprintf(stderr,"wwwoffled: The '-c' option requires a filename.\n"); exit(1);}
  111.  
  112.        ConfigFile=argv[i];
  113.        continue;
  114.       }
  115.  
  116.     fprintf(stderr,"wwwoffled: Unknown option '%s'.\n",argv[i]); exit(1);
  117.    }
  118.  
  119.  /* Initialise things. */
  120.  
  121.  for(i=0;i<MAX_FETCH_SERVERS;i++)
  122.     fetch_pids[i]=0;
  123.  
  124.  InitErrorHandler("wwwoffled",1,!detached);
  125.  
  126.  if(ReadConfigFile(2))
  127.     PrintMessage(Fatal,"Error in configuration file '%s'.",ConfigFile);
  128.  
  129.  PrintMessage(Important,"WWWOFFLE Demon Version %s started",WWWOFFLE_VERSION);
  130.  PrintMessage(Inform,"WWWOFFLE Read Configuration File.");
  131.  
  132.  if(WWWOFFLE_Gid != -1)
  133.    {
  134.     if(setgid(WWWOFFLE_Gid)<0)
  135.        PrintMessage(Fatal,"Cannot set group id to %d [%!s].",WWWOFFLE_Gid);
  136.     if(setegid(WWWOFFLE_Gid)<0)
  137.        PrintMessage(Fatal,"Cannot set effective group id to %d [%!s].",WWWOFFLE_Gid);
  138.    }
  139.  
  140.  if(WWWOFFLE_Uid != -1)
  141.    {
  142.     if(setuid(WWWOFFLE_Uid)<0)
  143.        PrintMessage(Fatal,"Cannot set user id to %d [%!s].",WWWOFFLE_Uid);
  144.     if(seteuid(WWWOFFLE_Uid)<0)
  145.        PrintMessage(Fatal,"Cannot set effective user id to %d [%!s].",WWWOFFLE_Uid);
  146.    }
  147.  
  148.  if(WWWOFFLE_Gid != -1 || WWWOFFLE_Uid != -1)
  149.     PrintMessage(Inform,"Running with uid=%d, gid=%d.",getuid(),getgid());
  150.  
  151.  http_fd=OpenServerSocket(HTTP_Port);
  152.  if(http_fd==-1)
  153.     PrintMessage(Fatal,"Cannot create HTTP server socket.");
  154.  
  155.  wwwoffle_fd=OpenServerSocket(WWWOFFLE_Port);
  156.  if(wwwoffle_fd==-1)
  157.     PrintMessage(Fatal,"Cannot create WWWOFFLE server socket.");
  158.  
  159.  if(stat(SpoolDir,&buf))
  160.    {
  161.     err=mkdir(SpoolDir,0755);
  162.     if(err==-1 && errno!=EEXIST)
  163.        PrintMessage(Fatal,"Cannot create spool directory %s [%!s].",SpoolDir);
  164.     stat(SpoolDir,&buf);
  165.    }
  166.  
  167.  if(!S_ISDIR(buf.st_mode))
  168.     PrintMessage(Fatal,"The spool directory %s is not a directory.",SpoolDir);
  169.  
  170.  err=chdir(SpoolDir);
  171.  if(err==-1)
  172.     PrintMessage(Fatal,"Cannot change to spool directory %s [%!s].",SpoolDir);
  173.  
  174.  if(detached)
  175.    {
  176.     demoninit();
  177.     PrintMessage(Important,"Detached from terminal and changed pid to %d.",getpid());
  178.     InitErrorHandler("wwwoffled",1,!detached); /* pid changes after detaching. */
  179.    }
  180.  
  181.  install_sighandlers();
  182.  
  183.  /* Loop around waiting for connections. */
  184.  
  185.  do
  186.    {
  187.     struct timeval tv;
  188.     fd_set readfd;
  189.     int nfds;
  190.     int retval;
  191.  
  192.     if(http_fd>wwwoffle_fd)
  193.        nfds=http_fd+1;
  194.     else
  195.        nfds=wwwoffle_fd+1;
  196.  
  197.     FD_ZERO(&readfd);
  198.  
  199.     FD_SET(wwwoffle_fd,&readfd);
  200.  
  201.     if(n_servers<MaxServers)
  202.        FD_SET(http_fd,&readfd);
  203.  
  204.     tv.tv_sec=10;
  205.     tv.tv_usec=0;
  206.  
  207.     retval=select(nfds,&readfd,NULL,NULL,&tv);
  208.  
  209.     if(retval!=-1)
  210.       {
  211.        if(FD_ISSET(wwwoffle_fd,&readfd))
  212.          {
  213.           char *host;
  214.           int port,client;
  215.  
  216.           client=AcceptConnect(wwwoffle_fd);
  217.           init_buffer(client);
  218.  
  219.           if(client>=0 && !SocketRemoteName(client,&host,NULL,&port))
  220.             {
  221.              if(IsAllowedConnect(host))
  222.                {
  223.                 PrintMessage(Important,"WWWOFFLE Connection from %s.",host);
  224.  
  225.                 CommandConnect(client);
  226.  
  227.                 if(fetch_fd!=client)
  228.                    CloseSocket(client);
  229.                }
  230.              else
  231.                {
  232.                 PrintMessage(Warning,"WWWOFFLE connection from %s rejected.",host);
  233.                 CloseSocket(client);
  234.                }
  235.             }
  236.          }
  237.  
  238.        if(FD_ISSET(http_fd,&readfd))
  239.          {
  240.           char *host;
  241.           int port,client;
  242.  
  243.           client=AcceptConnect(http_fd);
  244.           init_buffer(client);
  245.  
  246.           if(client>=0 && !SocketRemoteName(client,&host,NULL,&port))
  247.             {
  248.              if(IsAllowedConnect(host))
  249.                {
  250.                 PrintMessage(Inform,"HTTP Proxy connection from %s.",host);
  251.                 ForkServer(client,1);
  252.                }
  253.              else
  254.                 PrintMessage(Warning,"HTTP Proxy connection from %s rejected.",host);
  255.  
  256.              CloseSocket(client);
  257.             }
  258.          }
  259.       }
  260.  
  261.     if(readconfig)
  262.       {
  263.        readconfig=0;
  264.  
  265.        PrintMessage(Important,"SIGHUP signalled.");
  266.  
  267.        PrintMessage(Important,"WWWOFFLE Re-reading Configuration File.");
  268.  
  269.        if(ReadConfigFile(-1))
  270.           PrintMessage(Warning,"Error in configuration file; keeping old values.");
  271.  
  272.        PrintMessage(Important,"WWWOFFLE Finished Re-reading Configuration File.");
  273.       }
  274.  
  275.     if(got_sigchld)
  276.       {
  277.        int pid, status;
  278.  
  279.        /* To avoid race conditions, reset the flag before fetching the status */
  280.        got_sigchld=0;
  281.  
  282.        while((pid=waitpid(-1,&status,WNOHANG))>0)
  283.         {
  284.          int i;
  285.          int exitval=0;
  286.  
  287.          if(WIFEXITED(status))
  288.             exitval=WEXITSTATUS(status);
  289.          else if(WIFSIGNALED(status))
  290.             exitval=-WTERMSIG(status);
  291.  
  292.          if(exitval>=0)
  293.             PrintMessage(Inform,"Child wwwoffles exited with status %d (pid=%d).",exitval,pid);
  294.          else
  295.             PrintMessage(Important,"Child wwwoffles terminated by signal %d (pid=%d).",-exitval,pid);
  296.  
  297.          n_servers--;
  298.  
  299.          /* Check if the child that terminated is one of the fetching wwwoffles */
  300.          for(i=0;i<MaxFetchServers;i++)
  301.             if(fetch_pids[i]==pid)
  302.               {
  303.                n_fetch_servers--;
  304.                fetch_pids[i]=0;
  305.                break;
  306.               }
  307.  
  308.          if(exitval==3)
  309.             fetching=0;
  310.  
  311.          if(exitval==4 && online==1)
  312.             fetching=1;
  313.  
  314.          if(online!=1)
  315.             fetching=0;
  316.         }
  317.  
  318.         PrintMessage(Debug,"Currently running: %d servers total, %d fetchers.",n_servers,n_fetch_servers);
  319.       }
  320.  
  321.     /* The select timed out or we got a signal. If we are currently fetching,
  322.        start fetch servers to look for jobs in the spool directory. */
  323.  
  324.     while(fetching && n_fetch_servers<MaxFetchServers && n_servers<MaxServers)
  325.        ForkServer(fetch_fd,0);
  326.  
  327.     if(fetch_fd!=-1 && !fetching && n_fetch_servers==0)
  328.       {
  329.        write_string(fetch_fd,"WWWOFFLE No more to fetch.\n");
  330.        CloseSocket(fetch_fd);
  331.        fetch_fd=-1;
  332.  
  333.        PrintMessage(Important,"WWWOFFLE Fetch finished.");
  334.       }
  335.    }
  336.  while(!closedown);
  337.  
  338.  /* Close down and exit. */
  339.  
  340.  CloseSocket(http_fd);
  341.  CloseSocket(wwwoffle_fd);
  342.  
  343.  if(n_servers)
  344.     PrintMessage(Important,"Exit signalled - waiting for children.");
  345.  else
  346.     PrintMessage(Important,"Exit signalled.");
  347.  
  348.  while(n_servers)
  349.    {
  350.     int pid,status,exitval=0;
  351.  
  352.     while((pid=waitpid(-1,&status,0))>0)
  353.       {
  354.        if(WIFEXITED(status))
  355.           exitval=WEXITSTATUS(status);
  356.        else if(WIFSIGNALED(status))
  357.           exitval=-WTERMSIG(status);
  358.  
  359.        if(exitval>=0)
  360.           PrintMessage(Inform,"Child wwwoffles exited with status %d (pid=%d).",exitval,pid);
  361.        else
  362.           PrintMessage(Important,"Child wwwoffles terminated by signal %d (pid=%d).",-exitval,pid);
  363.  
  364.        n_servers--;
  365.       }
  366.    }
  367.  
  368.  PrintMessage(Important,"Exiting.");
  369.  
  370.  return(0);
  371. }
  372.  
  373.  
  374. /*++++++++++++++++++++++++++++++++++++++
  375.   Print the program usage in long or short format.
  376.  
  377.   int verbose True for long format.
  378.   ++++++++++++++++++++++++++++++++++++++*/
  379.  
  380. static void usage(int verbose)
  381. {
  382.  fprintf(stderr,
  383.          "\n"
  384.          "WWWOFFLED - World Wide Web Offline Explorer (Demon) - Version %s\n"
  385.          "\n",WWWOFFLE_VERSION);
  386.  
  387.  if(verbose)
  388.     fprintf(stderr,
  389.             "(c) Andrew M. Bishop 1996,97,98 [       amb@gedanken.demon.co.uk ]\n"
  390.             "                                [http://www.gedanken.demon.co.uk/]\n"
  391.             "\n");
  392.  
  393.  fprintf(stderr,
  394.          "Usage: wwwoffled [-h] [-c <config-file>] [-d [<log-level>]]\n"
  395.          "\n");
  396.  
  397.  if(verbose)
  398.     fprintf(stderr,
  399.             "   -h                  : Display this help.\n"
  400.             "\n"
  401.             "   -c <config-file>    : The name of the configuration file to use.\n"
  402.             "                         (Default %s).\n"
  403.             "\n"
  404.             "   -d [<log-level>]    : Do not detach from the terminal and use stderr.\n"
  405.             "                         0 <= log-level <= %d (default in config file).\n"
  406.             "\n",ConfigFile,Fatal+1);
  407.  
  408.  exit(0);
  409. }
  410.  
  411.  
  412. /*++++++++++++++++++++++++++++++++++++++
  413.   Detach ourself from the controlling terminal.
  414.   ++++++++++++++++++++++++++++++++++++++*/
  415.  
  416. static void demoninit(void)
  417. {
  418.  pid_t pid=0;
  419.  
  420.  pid=fork();
  421.  if(pid==-1)
  422.     PrintMessage(Fatal,"Cannot fork() to detach(1) [%!s].");
  423.  else if(pid)
  424.     exit(0);
  425.  
  426.  setsid();
  427.  
  428.  pid=fork();
  429.  if(pid==-1)
  430.     PrintMessage(Fatal,"Cannot fork() to detach(2) [%!s].");
  431.  else if(pid)
  432.     exit(0);
  433.  
  434.  /* Close fds */
  435.  close(STDIN_FILENO);
  436.  close(STDOUT_FILENO);
  437.  close(STDERR_FILENO);
  438. }
  439.  
  440.  
  441. /*++++++++++++++++++++++++++++++++++++++
  442.   Install the signal handlers.
  443.   ++++++++++++++++++++++++++++++++++++++*/
  444.  
  445. static void install_sighandlers(void)
  446. {
  447.  struct sigaction action;
  448.  
  449.  /* SIGCHLD */
  450.  action.sa_handler = sigchild;
  451.  sigemptyset (&action.sa_mask);
  452.  action.sa_flags = 0;
  453.  if(sigaction(SIGCHLD, &action, NULL) != 0)
  454.     PrintMessage(Warning, "Cannot install SIGCHLD handler.");
  455.  
  456.  /* SIGINT, SIGQUIT, SIGTERM */
  457.  action.sa_handler = sigexit;
  458.  sigemptyset(&action.sa_mask);
  459.  sigaddset(&action.sa_mask, SIGINT);           /* Block all of them */
  460.  sigaddset(&action.sa_mask, SIGQUIT);
  461.  sigaddset(&action.sa_mask, SIGTERM);
  462.  action.sa_flags = 0;
  463.  if(sigaction(SIGINT, &action, NULL) != 0)
  464.     PrintMessage(Warning, "Cannot install SIGINT handler.");
  465.  if(sigaction(SIGQUIT, &action, NULL) != 0)
  466.     PrintMessage(Warning, "Cannot install SIGQUIT handler.");
  467.  if(sigaction(SIGTERM, &action, NULL) != 0)
  468.     PrintMessage(Warning, "Cannot install SIGTERM handler.");
  469.  
  470.  /* SIGHUP */
  471.  action.sa_handler = sighup;
  472.  sigemptyset(&action.sa_mask);
  473.  action.sa_flags = 0;
  474.  if(sigaction(SIGHUP, &action, NULL) != 0)
  475.     PrintMessage(Warning, "Cannot install SIGHUP handler.");
  476. }
  477.  
  478.  
  479. /*++++++++++++++++++++++++++++++++++++++
  480.   The signal handler for the child exiting.
  481.  
  482.   int signum The signal number.
  483.   ++++++++++++++++++++++++++++++++++++++*/
  484.  
  485. static void sigchild(int signum)
  486. {
  487.  got_sigchld=1;
  488. }
  489.  
  490.  
  491. /*++++++++++++++++++++++++++++++++++++++
  492.   The signal handler for the signals to tell us to exit.
  493.  
  494.   int signum The signal number.
  495.   ++++++++++++++++++++++++++++++++++++++*/
  496.  
  497. static void sigexit(int signum)
  498. {
  499.  closedown=1;
  500. }
  501.  
  502.  
  503. /*++++++++++++++++++++++++++++++++++++++
  504.   The signal handler for the signals to tell us to re-read the config file.
  505.  
  506.   int signum The signal number.
  507.   ++++++++++++++++++++++++++++++++++++++*/
  508.  
  509. static void sighup(int signum)
  510. {
  511.  readconfig=1;
  512. }
  513.