File: wwwoffled.c

package info (click to toggle)
wwwoffle 2.3a-4
  • links: PTS
  • area: main
  • in suites: slink
  • size: 1,452 kB
  • ctags: 1,064
  • sloc: ansic: 10,102; lex: 1,395; sh: 510; makefile: 263; perl: 78
file content (525 lines) | stat: -rw-r--r-- 13,630 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/***************************************
  $Header: /home/amb/wwwoffle/RCS/wwwoffled.c 2.11 1998/07/10 18:49:32 amb Exp $

  WWWOFFLE - World Wide Web Offline Explorer - Version 2.3.
  A demon program to maintain the database and spawn the servers.
  ******************/ /******************
  Written by Andrew M. Bishop

  This file Copyright 1996,97,98 Andrew M. Bishop
  It may be distributed under the GNU Public License, version 2, or
  any higher version.  See section COPYING of the GNU Public license
  for conditions under which this file may be redistributed.
  ***************************************/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include <sys/wait.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>

#include "version.h"
#include "wwwoffle.h"
#include "misc.h"
#include "config.h"
#include "sockets.h"
#include "errors.h"

#if defined (hpux)
/* HP/UX has no `seteuid'. Instead it uses `setresuid' to set `uid', `euid', and `suid' simultaneously. */
#define setegid(egid)   setresgid (-1, (egid), -1)
#define seteuid(euid)   setresuid (-1, (euid), -1)
#endif

static void usage(int verbose);
static void demoninit(void);
static void install_sighandlers(void);
static void sigchild(int signum);
static void sigexit(int signum);
static void sighup(int signum);


/*+ The server sockets that we listen on +*/
int http_fd=-1,                 /*+ for the HTTP connections. +*/
    wwwoffle_fd=-1;             /*+ for the WWWOFFLE connections. +*/

/*+ The online / offline /autodial status. +*/
int online=0;

/*+ The current number active servers +*/
int n_servers=0,                /*+ in total. +*/
    n_fetch_servers=0;          /*+ fetching a page. +*/

/*+ The wwwoffle client file descriptor when fetching. +*/
int fetch_fd=-1;

/*+ The pids of the servers that are fetching. +*/
int fetch_pids[MAX_FETCH_SERVERS];

/*+ The current status, fetching or not. +*/
int fetching=0;

/*+ Set to 1 when the demon is to shutdown. +*/
static int closedown=0;

/*+ Set to 1 when the demon is to re-read config file due to a sighup. +*/
static int readconfig=0;

/*+ Remember that we got a SIGCHLD +*/
static sig_atomic_t got_sigchld=0;

/*+ True if run as a demon +*/
static int detached=1;


/*++++++++++++++++++++++++++++++++++++++
  The main program.
  ++++++++++++++++++++++++++++++++++++++*/

int main(int argc, char** argv)
{
 int i;
 int err;
 struct stat buf;

 /* Parse the command line options */

 for(i=1;i<argc;i++)
   {
    if(!strcmp(argv[i],"-h"))
       usage(1);

    if(!strcmp(argv[i],"-d"))
      {
       detached=0;
       if(i<(argc-1) && isdigit(argv[i+1][0]) && !argv[i+1][1])
         {
          DebugLevel=Fatal+1-atoi(argv[++i]);
          if(DebugLevel<0)
             DebugLevel=0;
         }
       continue;
      }

    if(!strcmp(argv[i],"-c"))
      {
       if(++i>=argc)
         {fprintf(stderr,"wwwoffled: The '-c' option requires a filename.\n"); exit(1);}

       ConfigFile=argv[i];
       continue;
      }

    fprintf(stderr,"wwwoffled: Unknown option '%s'.\n",argv[i]); exit(1);
   }

 /* Initialise things. */

 for(i=0;i<MAX_FETCH_SERVERS;i++)
    fetch_pids[i]=0;

 InitErrorHandler("wwwoffled",1,!detached);

 if(ReadConfigFile(2))
    PrintMessage(Fatal,"Error in configuration file '%s'.",ConfigFile);

 PrintMessage(Important,"WWWOFFLE Demon Version %s started",WWWOFFLE_VERSION);
 PrintMessage(Inform,"WWWOFFLE Read Configuration File.");

 if(WWWOFFLE_Gid != -1)
   {
    if(setgid(WWWOFFLE_Gid)<0)
       PrintMessage(Fatal,"Cannot set group id to %d [%!s].",WWWOFFLE_Gid);
    if(setegid(WWWOFFLE_Gid)<0)
       PrintMessage(Fatal,"Cannot set effective group id to %d [%!s].",WWWOFFLE_Gid);
   }

 if(WWWOFFLE_Uid != -1)
   {
    if(setuid(WWWOFFLE_Uid)<0)
       PrintMessage(Fatal,"Cannot set user id to %d [%!s].",WWWOFFLE_Uid);
    if(seteuid(WWWOFFLE_Uid)<0)
       PrintMessage(Fatal,"Cannot set effective user id to %d [%!s].",WWWOFFLE_Uid);
   }

 if(WWWOFFLE_Gid != -1 || WWWOFFLE_Uid != -1)
    PrintMessage(Inform,"Running with uid=%d, gid=%d.",getuid(),getgid());

 http_fd=OpenServerSocket(HTTP_Port);
 if(http_fd==-1)
    PrintMessage(Fatal,"Cannot create HTTP server socket.");

 wwwoffle_fd=OpenServerSocket(WWWOFFLE_Port);
 if(wwwoffle_fd==-1)
    PrintMessage(Fatal,"Cannot create WWWOFFLE server socket.");

 if(stat(SpoolDir,&buf))
   {
    err=mkdir(SpoolDir,0755);
    if(err==-1 && errno!=EEXIST)
       PrintMessage(Fatal,"Cannot create spool directory %s [%!s].",SpoolDir);
    stat(SpoolDir,&buf);
   }

 if(!S_ISDIR(buf.st_mode))
    PrintMessage(Fatal,"The spool directory %s is not a directory.",SpoolDir);

 err=chdir(SpoolDir);
 if(err==-1)
    PrintMessage(Fatal,"Cannot change to spool directory %s [%!s].",SpoolDir);

 if(detached)
   {
    demoninit();
    PrintMessage(Important,"Detached from terminal and changed pid to %d.",getpid());
    InitErrorHandler("wwwoffled",1,!detached); /* pid changes after detaching. */
   }

 install_sighandlers();

 /* Loop around waiting for connections. */

 do
   {
    struct timeval tv;
    fd_set readfd;
    int nfds;
    int retval;

    if(http_fd>wwwoffle_fd)
       nfds=http_fd+1;
    else
       nfds=wwwoffle_fd+1;

    FD_ZERO(&readfd);

    FD_SET(wwwoffle_fd,&readfd);

    if(n_servers<MaxServers)
       FD_SET(http_fd,&readfd);

    tv.tv_sec=10;
    tv.tv_usec=0;

    retval=select(nfds,&readfd,NULL,NULL,&tv);

    if(retval!=-1)
      {
       if(FD_ISSET(wwwoffle_fd,&readfd))
         {
          char *host,*ip;
          int port,client;

          client=AcceptConnect(wwwoffle_fd);
          init_buffer(client);

          if(client>=0 && !SocketRemoteName(client,&host,&ip,&port))
            {
             if(IsAllowedConnect(host) || IsAllowedConnect(ip))
               {
                PrintMessage(Important,"WWWOFFLE Connection from %s (%s).",host,ip);

                CommandConnect(client);

                if(fetch_fd!=client)
                   CloseSocket(client);
               }
             else
               {
                PrintMessage(Warning,"WWWOFFLE connection from %s rejected.",host);
                CloseSocket(client);
               }
            }
         }

       if(FD_ISSET(http_fd,&readfd))
         {
          char *host,*ip;
          int port,client;

          client=AcceptConnect(http_fd);
          init_buffer(client);

          if(client>=0 && !SocketRemoteName(client,&host,&ip,&port))
            {
             if(IsAllowedConnect(host) || IsAllowedConnect(ip))
               {
                PrintMessage(Inform,"HTTP Proxy connection from %s (%s).",host,ip);
                ForkServer(client,1);
               }
             else
                PrintMessage(Warning,"HTTP Proxy connection from %s rejected.",host);

             CloseSocket(client);
            }
         }
      }

    if(readconfig)
      {
       readconfig=0;

       PrintMessage(Important,"SIGHUP signalled.");

       PrintMessage(Important,"WWWOFFLE Re-reading Configuration File.");

       if(ReadConfigFile(-1))
          PrintMessage(Warning,"Error in configuration file; keeping old values.");

       PrintMessage(Important,"WWWOFFLE Finished Re-reading Configuration File.");
      }

    if(got_sigchld)
      {
       int pid, status;

       /* To avoid race conditions, reset the flag before fetching the status */
       got_sigchld=0;

       while((pid=waitpid(-1,&status,WNOHANG))>0)
        {
         int i;
         int exitval=0;

         if(WIFEXITED(status))
            exitval=WEXITSTATUS(status);
         else if(WIFSIGNALED(status))
            exitval=-WTERMSIG(status);

         if(exitval>=0)
            PrintMessage(Inform,"Child wwwoffles exited with status %d (pid=%d).",exitval,pid);
         else
            PrintMessage(Important,"Child wwwoffles terminated by signal %d (pid=%d).",-exitval,pid);

         n_servers--;

         /* Check if the child that terminated is one of the fetching wwwoffles */
         for(i=0;i<MaxFetchServers;i++)
            if(fetch_pids[i]==pid)
              {
               n_fetch_servers--;
               fetch_pids[i]=0;
               break;
              }

         if(exitval==3)
            fetching=0;

         if(exitval==4 && online==1)
            fetching=1;

         if(online!=1)
            fetching=0;
        }

        PrintMessage(Debug,"Currently running: %d servers total, %d fetchers.",n_servers,n_fetch_servers);
      }

    /* The select timed out or we got a signal. If we are currently fetching,
       start fetch servers to look for jobs in the spool directory. */

    while(fetching && n_fetch_servers<MaxFetchServers && n_servers<MaxServers)
       ForkServer(fetch_fd,0);

    if(fetch_fd!=-1 && !fetching && n_fetch_servers==0)
      {
       write_string(fetch_fd,"WWWOFFLE No more to fetch.\n");
       CloseSocket(fetch_fd);
       fetch_fd=-1;

       PrintMessage(Important,"WWWOFFLE Fetch finished.");
      }
   }
 while(!closedown);

 /* Close down and exit. */

 CloseSocket(http_fd);
 CloseSocket(wwwoffle_fd);

 if(n_servers)
    PrintMessage(Important,"Exit signalled - waiting for children.");
 else
    PrintMessage(Important,"Exit signalled.");

 while(n_servers)
   {
    int pid,status,exitval=0;

    while((pid=waitpid(-1,&status,0))>0)
      {
       if(WIFEXITED(status))
          exitval=WEXITSTATUS(status);
       else if(WIFSIGNALED(status))
          exitval=-WTERMSIG(status);

       if(exitval>=0)
          PrintMessage(Inform,"Child wwwoffles exited with status %d (pid=%d).",exitval,pid);
       else
          PrintMessage(Important,"Child wwwoffles terminated by signal %d (pid=%d).",-exitval,pid);

       n_servers--;
      }
   }

 PrintMessage(Important,"Exiting.");

 return(0);
}


/*++++++++++++++++++++++++++++++++++++++
  Print the program usage in long or short format.

  int verbose True for long format.
  ++++++++++++++++++++++++++++++++++++++*/

static void usage(int verbose)
{
 fprintf(stderr,
         "\n"
         "WWWOFFLED - World Wide Web Offline Explorer (Demon) - Version %s\n"
         "\n",WWWOFFLE_VERSION);

 if(verbose)
    fprintf(stderr,
            "(c) Andrew M. Bishop 1996,97,98 [       amb@gedanken.demon.co.uk ]\n"
            "                                [http://www.gedanken.demon.co.uk/]\n"
            "\n");

 fprintf(stderr,
         "Usage: wwwoffled [-h] [-c <config-file>] [-d [<log-level>]]\n"
         "\n");

 if(verbose)
    fprintf(stderr,
            "   -h                  : Display this help.\n"
            "\n"
            "   -c <config-file>    : The name of the configuration file to use.\n"
            "                         (Default %s).\n"
            "\n"
            "   -d [<log-level>]    : Do not detach from the terminal and use stderr.\n"
            "                         0 <= log-level <= %d (default in config file).\n"
            "\n",ConfigFile,Fatal+1);

 exit(0);
}


/*++++++++++++++++++++++++++++++++++++++
  Detach ourself from the controlling terminal.
  ++++++++++++++++++++++++++++++++++++++*/

static void demoninit(void)
{
 pid_t pid=0;

 pid=fork();
 if(pid==-1)
    PrintMessage(Fatal,"Cannot fork() to detach(1) [%!s].");
 else if(pid)
    exit(0);

 setsid();

 pid=fork();
 if(pid==-1)
    PrintMessage(Fatal,"Cannot fork() to detach(2) [%!s].");
 else if(pid)
    exit(0);

 /* Close fds */
 close(STDIN_FILENO);
 close(STDOUT_FILENO);
 close(STDERR_FILENO);
}


/*++++++++++++++++++++++++++++++++++++++
  Install the signal handlers.
  ++++++++++++++++++++++++++++++++++++++*/

static void install_sighandlers(void)
{
 struct sigaction action;

 /* SIGCHLD */
 action.sa_handler = sigchild;
 sigemptyset (&action.sa_mask);
 action.sa_flags = 0;
 if(sigaction(SIGCHLD, &action, NULL) != 0)
    PrintMessage(Warning, "Cannot install SIGCHLD handler.");

 /* SIGINT, SIGQUIT, SIGTERM */
 action.sa_handler = sigexit;
 sigemptyset(&action.sa_mask);
 sigaddset(&action.sa_mask, SIGINT);           /* Block all of them */
 sigaddset(&action.sa_mask, SIGQUIT);
 sigaddset(&action.sa_mask, SIGTERM);
 action.sa_flags = 0;
 if(sigaction(SIGINT, &action, NULL) != 0)
    PrintMessage(Warning, "Cannot install SIGINT handler.");
 if(sigaction(SIGQUIT, &action, NULL) != 0)
    PrintMessage(Warning, "Cannot install SIGQUIT handler.");
 if(sigaction(SIGTERM, &action, NULL) != 0)
    PrintMessage(Warning, "Cannot install SIGTERM handler.");

 /* SIGHUP */
 action.sa_handler = sighup;
 sigemptyset(&action.sa_mask);
 action.sa_flags = 0;
 if(sigaction(SIGHUP, &action, NULL) != 0)
    PrintMessage(Warning, "Cannot install SIGHUP handler.");

 /* SIGPIPE */
 action.sa_handler = SIG_IGN;
 sigemptyset (&action.sa_mask);
 action.sa_flags = 0;
 if(sigaction(SIGPIPE, &action, NULL) != 0)
    PrintMessage(Warning, "Cannot ignore SIGPIPE.");
}


/*++++++++++++++++++++++++++++++++++++++
  The signal handler for the child exiting.

  int signum The signal number.
  ++++++++++++++++++++++++++++++++++++++*/

static void sigchild(int signum)
{
 got_sigchld=1;
}


/*++++++++++++++++++++++++++++++++++++++
  The signal handler for the signals to tell us to exit.

  int signum The signal number.
  ++++++++++++++++++++++++++++++++++++++*/

static void sigexit(int signum)
{
 closedown=1;
}


/*++++++++++++++++++++++++++++++++++++++
  The signal handler for the signals to tell us to re-read the config file.

  int signum The signal number.
  ++++++++++++++++++++++++++++++++++++++*/

static void sighup(int signum)
{
 readconfig=1;
}