]> granicus.if.org Git - apache/blob - support/htcacheclean.c
just style
[apache] / support / htcacheclean.c
1 /* Copyright 2001-2004 The Apache Software Foundation
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 /*
17  * htcacheclean.c: simple program for cleaning of
18  * the disk cache of the Apache HTTP server
19  *
20  * Contributed by Andreas Steinmetz <ast@domdv.de>
21  * 8 Oct 2004
22  */
23
24 #include "apr.h"
25 #include "apr_lib.h"
26 #include "apr_strings.h"
27 #include "apr_file_io.h"
28 #include "apr_file_info.h"
29 #include "apr_pools.h"
30 #include "apr_hash.h"
31 #include "apr_thread_proc.h"
32 #include "apr_signal.h"
33 #include "apr_getopt.h"
34 #include "apr_ring.h"
35 #include "apr_date.h"
36
37 #if APR_HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40 #if APR_HAVE_STDLIB_H
41 #include <stdlib.h>
42 #endif
43
44 /* mod_disk_cache.c extract start */
45
46 #define DISK_FORMAT_VERSION 0
47 typedef struct {
48     /* Indicates the format of the header struct stored on-disk. */
49     int format;
50     /* The HTTP status code returned for this response.  */
51     int status;
52     /* The size of the entity name that follows. */
53     apr_size_t name_len;
54     /* The number of times we've cached this entity. */
55     apr_size_t entity_version;
56     /* Miscellaneous time values. */
57     apr_time_t date;
58     apr_time_t expire;
59     apr_time_t request_time;
60     apr_time_t response_time;
61 } disk_cache_info_t;
62
63 #define CACHE_HEADER_SUFFIX ".header"
64 #define CACHE_DATA_SUFFIX   ".data"
65 /* mod_disk_cache.c extract end */
66
67 /* mod_disk_cache.c related definitions start */
68
69 /*
70  * this is based on #define AP_TEMPFILE "/aptmpXXXXXX"
71  *
72  * the above definition could be reworked into the following:
73  *
74  * #define AP_TEMPFILE_PREFIX "/"
75  * #define AP_TEMPFILE_BASE   "aptmp"
76  * #define AP_TEMPFILE_SUFFIX "XXXXXX"
77  * #define AP_TEMPFILE_BASELEN strlen(AP_TEMPFILE_BASE)
78  * #define AP_TEMPFILE_NAMELEN strlen(AP_TEMPFILE_BASE AP_TEMPFILE_SUFFIX)
79  * #define AP_TEMPFILE AP_TEMPFILE_PREFIX AP_TEMPFILE_BASE AP_TEMPFILE_SUFFIX
80  *
81  * these definitions would then match the definitions below:
82  */
83
84 #define AP_TEMPFILE_BASE    "aptmp"
85 #define AP_TEMPFILE_SUFFIX  "XXXXXX"
86 #define AP_TEMPFILE_BASELEN strlen(AP_TEMPFILE_BASE)
87 #define AP_TEMPFILE_NAMELEN strlen(AP_TEMPFILE_BASE AP_TEMPFILE_SUFFIX)
88
89 /* mod_disk_cache.c related definitions end */
90
91 /* define the following for debugging */
92 #undef DEBUG
93
94 /*
95  * Note: on Linux delays <= 2ms are busy waits without
96  *       scheduling, so never use a delay <= 2ms below
97  */
98
99 #define NICE_DELAY    10000     /* usecs */
100 #define DELETE_NICE   10        /* be nice after this amount of delete ops */
101 #define STAT_ATTEMPTS 10        /* maximum stat attempts for a file */
102 #define STAT_DELAY    5000      /* usecs */
103 #define HEADER        1         /* headers file */
104 #define DATA          2         /* body file */
105 #define TEMP          4         /* temporary file */
106 #define HEADERDATA    (HEADER|DATA)
107 #define MAXDEVIATION  3600      /* secs */
108 #define SECS_PER_MIN  60
109 #define KBYTE         1024
110 #define MBYTE         1048576
111
112 #define DIRINFO (APR_FINFO_MTIME|APR_FINFO_SIZE|APR_FINFO_TYPE|APR_FINFO_LINK)
113
114 typedef struct _direntry {
115     APR_RING_ENTRY(_direntry) link;
116     int type;         /* type of file/fileset: TEMP, HEADER, DATA, HEADERDATA */
117     apr_time_t htime; /* headers file modification time */
118     apr_time_t dtime; /* body file modification time */
119     apr_off_t hsize;  /* headers file size */
120     apr_off_t dsize;  /* body or temporary file size */
121     char *basename;   /* file/fileset base name */
122 } DIRENTRY;
123
124 typedef struct _entry {
125     APR_RING_ENTRY(_entry) link;
126     apr_time_t expire;        /* cache entry exiration time */
127     apr_time_t response_time; /* cache entry time of last response to client */
128     apr_time_t htime;         /* headers file modification time */
129     apr_time_t dtime;         /* body file modification time */
130     apr_off_t hsize;          /* headers file size */
131     apr_off_t dsize;          /* body or temporary file size */
132     char *basename;           /* fileset base name */
133 } ENTRY;
134
135
136 static int delcount;    /* file deletion count for nice mode */
137 static int interrupted; /* flag: true if SIGINT or SIGTERM occurred */
138 static int realclean;   /* flag: true means user said apache is not running */
139 static int verbose;     /* flag: true means print statistics */
140 static int benice;      /* flag: true means nice mode is activated */
141 static int dryrun;      /* flag: true means dry run, don't actually delete
142                                  anything */
143 static int baselen;     /* string length of the path to the proxy directory */
144 static apr_time_t now;  /* start time of this processing run */
145
146 static apr_file_t *errfile;   /* stderr file handle */
147 static apr_off_t unsolicited; /* file size summary for deleted unsolicited
148                                  files */
149 static APR_RING_ENTRY(_entry) root; /* ENTRY ring anchor */
150
151
152 #ifdef DEBUG
153 /*
154  * fake delete for debug purposes
155  */
156 #define apr_file_remove fake_file_remove
157 static void fake_file_remove(char *pathname, apr_pool_t *p)
158 {
159     apr_finfo_t info;
160
161     /* stat and printing to simulate some deletion system load and to
162        display what would actually have happened */
163     apr_stat(&info, pathname, DIRINFO, p);
164     apr_file_printf(errfile, "would delete %s\n", pathname);
165 }
166 #endif
167
168 /*
169  * called on SIGINT or SIGTERM
170  */
171 static void setterm(int unused)
172 {
173 #ifdef DEBUG
174     apr_file_printf(errfile, "interrupt\n");
175 #endif
176     interrupted = 1;
177 }
178
179 /*
180  * called in out of memory condition
181  */
182 static int oom(int unused)
183 {
184     static int called = 0;
185
186     /* be careful to call exit() only once */
187     if (!called) {
188         called = 1;
189         exit(1);
190     }
191     return APR_ENOMEM;
192 }
193
194 /*
195  * print purge statistics
196  */
197 static void printstats(apr_off_t total, apr_off_t sum, apr_off_t max,
198                        apr_off_t etotal, apr_off_t entries)
199 {
200     char ttype, stype, mtype, utype;
201     apr_off_t tfrag, sfrag, ufrag;
202
203     if (!verbose) {
204         return;
205     }
206
207     ttype = 'K';
208     tfrag = ((total * 10) / KBYTE) % 10;
209     total /= KBYTE;
210     if (total >= KBYTE) {
211         ttype = 'M';
212         tfrag = ((total * 10) / KBYTE) % 10;
213         total /= KBYTE;
214     }
215
216     stype = 'K';
217     sfrag = ((sum * 10) / KBYTE) % 10;
218     sum /= KBYTE;
219     if (sum >= KBYTE) {
220         stype = 'M';
221         sfrag = ((sum * 10) / KBYTE) % 10;
222         sum /= KBYTE;
223     }
224
225     mtype = 'K';
226     max /= KBYTE;
227     if (max >= KBYTE) {
228         mtype = 'M';
229         max /= KBYTE;
230     }
231
232     apr_file_printf(errfile, "Statistics:\n");
233     if (unsolicited) {
234         utype = 'K';
235         ufrag = ((unsolicited * 10) / KBYTE) % 10;
236         unsolicited /= KBYTE;
237         if (unsolicited >= KBYTE) {
238             utype = 'M';
239             ufrag = ((unsolicited * 10) / KBYTE) % 10;
240             unsolicited /= KBYTE;
241         }
242         if (!unsolicited && !ufrag) {
243             ufrag = 1;
244         }
245         apr_file_printf(errfile, "unsolicited size %d.%d%c\n",
246                         (int)(unsolicited), (int)(ufrag), utype);
247      }
248      apr_file_printf(errfile, "size limit %d.0%c\n", (int)(max), mtype);
249      apr_file_printf(errfile, "total size was %d.%d%c, total size now "
250                               "%d.%d%c\n",
251                      (int)(total), (int)(tfrag), ttype, (int)(sum),
252                      (int)(sfrag), stype);
253      apr_file_printf(errfile, "total entries was %d, total entries now %d\n",
254                      (int)(etotal), (int)(entries));
255 }
256
257 /*
258  * delete a single file
259  */
260 static void delete_file(char *path, char *basename, apr_pool_t *pool)
261 {
262     char *nextpath;
263     apr_pool_t *p;
264
265     if (dryrun) {
266         return;
267     }
268
269     /* temp pool, otherwise lots of memory could be allocated */
270     apr_pool_create(&p, pool);
271     nextpath = apr_pstrcat(p, path, "/", basename, NULL);
272     apr_file_remove(nextpath, p);
273     apr_pool_destroy(p);
274
275     if (benice) {
276         if (++delcount >= DELETE_NICE) {
277             apr_sleep(NICE_DELAY);
278             delcount = 0;
279         }
280     }
281 }
282
283 /*
284  * delete cache file set
285  */
286 static void delete_entry(char *path, char *basename, apr_pool_t *pool)
287 {
288     char *nextpath;
289     apr_pool_t *p;
290
291     if (dryrun) {
292         return;
293     }
294
295     /* temp pool, otherwise lots of memory could be allocated */
296     apr_pool_create(&p, pool);
297
298     nextpath = apr_pstrcat(p, path, "/", basename, CACHE_HEADER_SUFFIX, NULL);
299     apr_file_remove(nextpath, p);
300
301     nextpath = apr_pstrcat(p, path, "/", basename, CACHE_DATA_SUFFIX, NULL);
302     apr_file_remove(nextpath, p);
303
304     apr_pool_destroy(p);
305
306     if (benice) {
307         delcount += 2;
308         if (delcount >= DELETE_NICE) {
309             apr_sleep(NICE_DELAY);
310             delcount = 0;
311         }
312     }
313 }
314
315 /*
316  * walk the cache directory tree
317  */
318 static int process_dir(char *path, apr_pool_t *pool)
319 {
320     apr_dir_t *dir;
321     apr_pool_t *p;
322     apr_hash_t *h;
323     apr_hash_index_t *i;
324     apr_file_t *fd;
325     apr_status_t status;
326     apr_finfo_t info;
327     apr_size_t len;
328     apr_time_t current, deviation;
329     char *nextpath, *base, *ext;
330     APR_RING_ENTRY(_direntry) anchor;
331     DIRENTRY *d, *t, *n;
332     ENTRY *e;
333     int skip, retries;
334     disk_cache_info_t disk_info;
335
336     APR_RING_INIT(&anchor, _direntry, link);
337     apr_pool_create(&p, pool);
338     h = apr_hash_make(p);
339     fd = NULL;
340     skip = 0;
341     deviation = MAXDEVIATION * APR_USEC_PER_SEC;
342
343     if (apr_dir_open(&dir, path, p) != APR_SUCCESS) {
344         return 1;
345     }
346
347     while (apr_dir_read(&info, 0, dir) == APR_SUCCESS && !interrupted) {
348         /* skip first two entries which will always be '.' and '..' */
349         if (skip < 2) {
350             skip++;
351             continue;
352         }
353         d = apr_pcalloc(p, sizeof(DIRENTRY));
354         d->basename = apr_pstrcat(p, path, "/", info.name, NULL);
355         APR_RING_INSERT_TAIL(&anchor, d, _direntry, link);
356     }
357
358     apr_dir_close(dir);
359
360     if (interrupted) {
361         return 1;
362     }
363
364     skip = baselen + 1;
365
366     for (d = APR_RING_FIRST(&anchor);
367          !interrupted && d != APR_RING_SENTINEL(&anchor, _direntry, link);
368          d=n) {
369         n = APR_RING_NEXT(d, link);
370         base = strrchr(d->basename, '/');
371         if (!base++) {
372             base = d->basename;
373         }
374         ext = strchr(base, '.');
375
376         /* there may be temporary files which may be gone before
377          * processing, always skip these if not in realclean mode
378          */
379         if (!ext && !realclean) {
380             if (!strncasecmp(base, AP_TEMPFILE_BASE, AP_TEMPFILE_BASELEN)
381                 && strlen(base) == AP_TEMPFILE_NAMELEN) {
382                 continue;
383             }
384         }
385
386         /* this may look strange but apr_stat() may return errno which
387          * is system dependent and there may be transient failures,
388          * so just blindly retry for a short while
389          */
390         retries = STAT_ATTEMPTS;
391         status = APR_SUCCESS;
392         do {
393             if (status != APR_SUCCESS) {
394                 apr_sleep(STAT_DELAY);
395             }
396             status = apr_stat(&info, d->basename, DIRINFO, p);
397         } while (status != APR_SUCCESS && !interrupted && --retries);
398
399         /* what may happen here is that apache did create a file which
400          * we did detect but then does delete the file before we can
401          * get file information, so if we don't get any file information
402          * we will ignore the file in this case
403          */
404         if (status != APR_SUCCESS) {
405             if (!realclean && !interrupted) {
406                 continue;
407             }
408             return 1;
409         }
410
411         if (info.filetype == APR_DIR) {
412             if (process_dir(d->basename, pool)) {
413                 return 1;
414             }
415             continue;
416         }
417
418         if (info.filetype != APR_REG) {
419             continue;
420         }
421
422         if (!ext) {
423             if (!strncasecmp(base, AP_TEMPFILE_BASE, AP_TEMPFILE_BASELEN)
424                 && strlen(base) == AP_TEMPFILE_NAMELEN) {
425                 d->basename += skip;
426                 d->type = TEMP;
427                 d->dsize = info.size;
428                 apr_hash_set(h, d->basename, APR_HASH_KEY_STRING, d);
429             }
430             continue;
431         }
432
433         if (!strcasecmp(ext, CACHE_HEADER_SUFFIX)) {
434             *ext = '\0';
435             d->basename += skip;
436             /* if a user manually creates a '.header' file */
437             if (d->basename[0] == '\0') {
438                 continue;
439             }
440             t = apr_hash_get(h, d->basename, APR_HASH_KEY_STRING);
441             if (t) {
442                 d = t;
443             }
444             d->type |= HEADER;
445             d->htime = info.mtime;
446             d->hsize = info.size;
447             apr_hash_set(h, d->basename, APR_HASH_KEY_STRING, d);
448             continue;
449         }
450
451         if (!strcasecmp(ext, CACHE_DATA_SUFFIX)) {
452             *ext = '\0';
453             d->basename += skip;
454             /* if a user manually creates a '.data' file */
455             if (d->basename[0] == '\0') {
456                 continue;
457             }
458             t = apr_hash_get(h, d->basename, APR_HASH_KEY_STRING);
459             if (t) {
460                 d = t;
461             }
462             d->type |= DATA;
463             d->dtime = info.mtime;
464             d->dsize = info.size;
465             apr_hash_set(h, d->basename, APR_HASH_KEY_STRING, d);
466         }
467     }
468
469     if (interrupted) {
470         return 1;
471     }
472
473     path[baselen] = '\0';
474
475     for (i = apr_hash_first(p, h); i && !interrupted; i = apr_hash_next(i)) {
476          apr_hash_this(i, NULL, NULL, (void **)(&d));
477         switch(d->type) {
478         case HEADERDATA:
479             nextpath = apr_pstrcat(p, path, "/", d->basename,
480                                    CACHE_HEADER_SUFFIX, NULL);
481             if (apr_file_open(&fd, nextpath, APR_READ, APR_OS_DEFAULT,
482                               p) == APR_SUCCESS) {
483                 len = sizeof(disk_cache_info_t);
484                 if (apr_file_read_full(fd, &disk_info, len,
485                                        &len) == APR_SUCCESS) {
486                     apr_file_close(fd);
487                     if (disk_info.format == DISK_FORMAT_VERSION) {
488                         e = apr_palloc(pool, sizeof(ENTRY));
489                         APR_RING_INSERT_TAIL(&root, e, _entry, link);
490                         e->expire = disk_info.expire;
491                         e->response_time = disk_info.response_time;
492                         e->htime = d->htime;
493                         e->dtime = d->dtime;
494                         e->hsize = d->hsize;
495                         e->dsize = d->dsize;
496                         e->basename = apr_palloc(pool,
497                                                  strlen(d->basename) + 1);
498                         strcpy(e->basename, d->basename);
499                         break;
500                     }
501                 }
502                 else {
503                     apr_file_close(fd);
504                 }
505             }
506             /* we have a somehow unreadable headers file which is associated
507              * with a data file. this may be caused by apache currently
508              * rewriting the headers file. thus we may delete the file set
509              * either in realclean mode or if the headers file modification
510              * timestamp is not within a specified positive or negative offset
511              * to the current time.
512              */
513             current = apr_time_now();
514             if (realclean || d->htime < current - deviation
515                 || d->htime > current + deviation) {
516                 delete_entry(path, d->basename, p);
517                 unsolicited += d->hsize;
518                 unsolicited += d->dsize;
519             }
520             break;
521
522         /* single data and header files may be deleted either in realclean
523          * mode or if their modification timestamp is not within a
524          * specified positive or negative offset to the current time.
525          * this handling is necessary due to possible race conditions
526          * between apache and this process
527          */
528         case HEADER:
529             current = apr_time_now();
530             if (realclean || d->htime < current - deviation
531                 || d->htime > current + deviation) {
532                 delete_entry(path, d->basename, p);
533                 unsolicited += d->hsize;
534             }
535             break;
536
537         case DATA:
538             current = apr_time_now();
539             if (realclean || d->dtime < current - deviation
540                 || d->dtime > current + deviation) {
541                 delete_entry(path, d->basename, p);
542                 unsolicited += d->dsize;
543             }
544             break;
545
546         /* temp files may only be deleted in realclean mode which
547          * is asserted above if a tempfile is in the hash array
548          */
549         case TEMP:
550             delete_file(path, d->basename, p);
551             unsolicited += d->dsize;
552             break;
553         }
554     }
555
556     if (interrupted) {
557         return 1;
558     }
559
560     apr_pool_destroy(p);
561
562     if (benice) {
563         apr_sleep(NICE_DELAY);
564     }
565
566     if (interrupted) {
567         return 1;
568     }
569
570     return 0;
571 }
572
573 /*
574  * purge cache entries
575  */
576 static void purge(char *path, apr_pool_t *pool, apr_off_t max)
577 {
578     apr_off_t sum, total, entries, etotal;
579     ENTRY *e, *n, *oldest;
580
581     sum = 0;
582     entries = 0;
583
584     for (e = APR_RING_FIRST(&root);
585          e != APR_RING_SENTINEL(&root, _entry, link);
586          e = APR_RING_NEXT(e, link)) {
587         sum += e->hsize;
588         sum += e->dsize;
589         entries++;
590     }
591
592     total = sum;
593     etotal = entries;
594
595     if (sum <= max) {
596         printstats(total, sum, max, etotal, entries);
597         return;
598     }
599
600     /* process all entries with a timestamp in the future, this may
601      * happen if a wrong system time is corrected
602      */
603
604     for (e = APR_RING_FIRST(&root);
605          e != APR_RING_SENTINEL(&root, _entry, link) && !interrupted;) {
606         n = APR_RING_NEXT(e, link);
607         if (e->response_time > now || e->htime > now || e->dtime > now) {
608             delete_entry(path, e->basename, pool);
609             sum -= e->hsize;
610             sum -= e->dsize;
611             entries--;
612             APR_RING_REMOVE(e, link);
613             if (sum <= max) {
614                 if (!interrupted) {
615                     printstats(total, sum, max, etotal, entries);
616                 }
617                 return;
618             }
619         }
620         e = n;
621     }
622
623     if (interrupted) {
624         return;
625     }
626
627     /* process all entries with are expired */
628     for (e = APR_RING_FIRST(&root);
629          e != APR_RING_SENTINEL(&root, _entry, link) && !interrupted;) {
630         n = APR_RING_NEXT(e, link);
631         if (e->expire != APR_DATE_BAD && e->expire < now) {
632             delete_entry(path, e->basename, pool);
633             sum -= e->hsize;
634             sum -= e->dsize;
635             entries--;
636             APR_RING_REMOVE(e, link);
637             if (sum <= max) {
638                 if (!interrupted) {
639                     printstats(total, sum, max, etotal, entries);
640                 }
641                 return;
642             }
643         }
644         e = n;
645     }
646
647     if (interrupted) {
648          return;
649     }
650
651     /* process remaining entries oldest to newest, the check for an emtpy
652      * ring actually isn't necessary except when the compiler does
653      * corrupt 64bit arithmetics which happend to me once, so better safe
654      * than sorry
655      */
656     while (sum > max && !interrupted && !APR_RING_EMPTY(&root, _entry, link)) {
657         oldest = APR_RING_FIRST(&root);
658
659         for (e = APR_RING_NEXT(oldest, link);
660              e != APR_RING_SENTINEL(&root, _entry, link);
661              e = APR_RING_NEXT(e, link)) {
662             if (e->dtime < oldest->dtime) {
663                 oldest = e;
664             }
665         }
666
667         delete_entry(path, oldest->basename, pool);
668         sum -= oldest->hsize;
669         sum -= oldest->dsize;
670         entries--;
671         APR_RING_REMOVE(oldest, link);
672     }
673
674     if (!interrupted) {
675         printstats(total, sum, max, etotal, entries);
676     }
677 }
678
679 /*
680  * usage info
681  */
682 static void usage(void)
683 {
684     apr_file_printf(errfile, "htcacheclean -- program for cleaning the "
685                              "disk cache.\n");
686     apr_file_printf(errfile, "Usage: htcacheclean [-Dvrn] -pPATH -lLIMIT\n");
687     apr_file_printf(errfile, "       htcacheclean [-Dvrn] -pPATH -LLIMIT\n");
688     apr_file_printf(errfile, "       htcacheclean [-ni] -dINTERVAL -pPATH "
689                              "-lLIMIT\n");
690     apr_file_printf(errfile, "       htcacheclean [-ni] -dINTERVAL -pPATH "
691                              "-LLIMIT\n");
692     apr_file_printf(errfile, "Options:\n");
693     apr_file_printf(errfile, "   -d   Daemonize and repeat cache cleaning "
694                              "every INTERVAL minutes. This\n"
695                              "        option is mutually exclusive with "
696                              "the -D, -v and -r options.\n");
697     apr_file_printf(errfile, "   -D   Do a dry run and don't delete anything. "
698                              "This option is mutually\n"
699                              "        exclusive with the -d option.\n");
700     apr_file_printf(errfile, "   -v   Be verbose and print statistics. "
701                              "This option is mutually exclusive\n"
702                              "        with the -d option.\n");
703     apr_file_printf(errfile, "   -r   Clean thoroughly. This assumes that "
704                              "the Apache web server\n"
705                              "        is not running. This option is "
706                              "mutually exclusive with the -d option.\n");
707     apr_file_printf(errfile, "   -n   Be nice. This causes slower processing "
708                              "in favour of other processes.\n");
709     apr_file_printf(errfile, "   -p   Specify PATH as the root directory of "
710                              "the disk cache.\n");
711     apr_file_printf(errfile, "   -l   Specify LIMIT as the total disk cache "
712                              "size limit in KBytes.\n");
713     apr_file_printf(errfile, "   -L   Specify LIMIT as the total disk cache "
714                              "size limit in MBytes.\n");
715     apr_file_printf(errfile, "   -i   Be intelligent and run only when there "
716                              "was a modification\n"
717                              "        of the disk cache. This option is only "
718                              "possible together with\n"
719                              "        the -d option.\n");
720     exit(1);
721 }
722
723 /*
724  * main
725  */
726 int main(int argc, const char * const argv[])
727 {
728     apr_off_t max;
729     apr_time_t current, repeat, delay, previous;
730     apr_status_t status;
731     apr_pool_t *pool, *instance;
732     apr_getopt_t *o;
733     apr_finfo_t info;
734     int retries, isdaemon, limit_found, intelligent, dowork;
735     char opt;
736     const char *arg;
737     char *proxypath, *path;
738
739     interrupted = 0;
740     repeat = 0;
741     isdaemon = 0;
742     dryrun = 0;
743     limit_found = 0;
744     max = 0;
745     verbose = 0;
746     realclean = 0;
747     benice = 0;
748     intelligent = 0;
749     proxypath = NULL;
750
751     if (apr_app_initialize(&argc, &argv, NULL) != APR_SUCCESS) {
752         return 1;
753     }
754     atexit(apr_terminate);
755
756     if (apr_pool_create(&pool, NULL) != APR_SUCCESS) {
757         return 1;
758     }
759     apr_pool_abort_set(oom, pool);
760     apr_file_open_stderr(&errfile, pool);
761     apr_signal(SIGINT, setterm);
762     apr_signal(SIGTERM, setterm);
763
764     apr_getopt_init(&o, pool, argc, argv);
765
766     while (1) {
767         status = apr_getopt(o, "iDnvrd:l:L:p:", &opt, &arg);
768         if (status == APR_EOF) {
769             break;
770         }
771         else if (status != APR_SUCCESS) {
772             usage();
773         }
774         else {
775             switch (opt) {
776             case 'i':
777                 if (intelligent) {
778                     usage();
779                 }
780                 intelligent = 1;
781                 break;
782
783             case 'D':
784                 if (dryrun) {
785                     usage();
786                 }
787                 dryrun = 1;
788                 break;
789
790             case 'n':
791                 if (benice) {
792                     usage();
793                 }
794                 benice = 1;
795                 break;
796
797             case 'v':
798                 if (verbose) {
799                     usage();
800                 }
801                 verbose = 1;
802                 break;
803
804             case 'r':
805                 if (realclean) {
806                     usage();
807                 }
808                 realclean = 1;
809                 break;
810
811             case 'd':
812                 if (isdaemon) {
813                     usage();
814                 }
815                 isdaemon = 1;
816                 repeat = apr_atoi64(arg);
817                 repeat *= SECS_PER_MIN;
818                 repeat *= APR_USEC_PER_SEC;
819                 break;
820
821             case 'l':
822                 if (limit_found) {
823                     usage();
824                 }
825                 limit_found = 1;
826                 max = apr_atoi64(arg);
827                 max *= KBYTE;
828                 break;
829
830             case 'L':
831                 if (limit_found) {
832                     usage();
833                 }
834                 limit_found = 1;
835                 max = apr_atoi64(arg);
836                 max *= MBYTE;
837                 break;
838
839             case 'p':
840                 if (proxypath) {
841                     usage();
842                 }
843                 proxypath = apr_pstrdup(pool, arg);
844                 if (apr_filepath_set(proxypath, pool) != APR_SUCCESS) {
845                     usage();
846                 }
847                 break;
848             } /* switch */
849         } /* else */
850     } /* while */
851
852     if (o->ind != argc) {
853          usage();
854     }
855
856     if (isdaemon && (repeat <= 0 || verbose || realclean || dryrun)) {
857          usage();
858     }
859
860     if (!isdaemon && intelligent) {
861          usage();
862     }
863
864     if (!proxypath || max <= 0) {
865          usage();
866     }
867
868     if (apr_filepath_get(&path, 0, pool) != APR_SUCCESS) {
869         usage();
870     }
871     baselen = strlen(path);
872
873 #ifndef DEBUG
874     if (isdaemon) {
875         apr_file_close(errfile);
876         apr_proc_detach(APR_PROC_DETACH_DAEMONIZE);
877     }
878 #endif
879
880     do {
881         apr_pool_create(&instance, pool);
882
883         now = apr_time_now();
884         APR_RING_INIT(&root, _entry, link);
885         delcount = 0;
886         unsolicited = 0;
887         dowork = 0;
888
889         switch (intelligent) {
890         case 0:
891             dowork = 1;
892             break;
893
894         case 1:
895             retries = STAT_ATTEMPTS;
896             status = APR_SUCCESS;
897
898             do {
899                 if (status != APR_SUCCESS) {
900                     apr_sleep(STAT_DELAY);
901                 }
902                 status = apr_stat(&info, path, APR_FINFO_MTIME, instance);
903             } while (status != APR_SUCCESS && !interrupted && --retries);
904
905             if (status == APR_SUCCESS) {
906                 previous = info.mtime;
907                 intelligent = 2;
908             }
909             dowork = 1;
910             break;
911
912         case 2:
913             retries = STAT_ATTEMPTS;
914             status = APR_SUCCESS;
915
916             do {
917                 if (status != APR_SUCCESS) {
918                     apr_sleep(STAT_DELAY);
919                 }
920                 status = apr_stat(&info, path, APR_FINFO_MTIME, instance);
921             } while (status != APR_SUCCESS && !interrupted && --retries);
922
923             if (status == APR_SUCCESS) {
924                 if (previous != info.mtime) {
925                     dowork = 1;
926                 }
927                 previous = info.mtime;
928                 break;
929             }
930             intelligent = 1;
931             dowork = 1;
932             break;
933         }
934
935         if (dowork && !interrupted) {
936             if (!process_dir(path, instance) && !interrupted) {
937                 purge(path, instance, max);
938             }
939             else if (!isdaemon && !interrupted) {
940                 apr_file_printf(errfile,
941                      "An error occurred, cache cleaning aborted.\n");
942                 return 1;
943             }
944
945             if (intelligent && !interrupted) {
946                 retries = STAT_ATTEMPTS;
947                 status = APR_SUCCESS;
948                 do {
949                     if (status != APR_SUCCESS) {
950                         apr_sleep(STAT_DELAY);
951                     }
952                     status = apr_stat(&info, path, APR_FINFO_MTIME, instance);
953                 } while (status != APR_SUCCESS && !interrupted && --retries);
954
955                 if (status == APR_SUCCESS) {
956                     previous = info.mtime;
957                     intelligent = 2;
958                 }
959                 else {
960                     intelligent = 1;
961                 }
962             }
963         }
964
965         apr_pool_destroy(instance);
966
967         current = apr_time_now();
968         if (current < now) {
969             delay = repeat;
970         }
971         else if (current - now >= repeat) {
972             delay = repeat;
973         }
974         else {
975             delay = now + repeat - current;
976         }
977
978         /* we can't sleep the whole delay time here apiece as this is racy
979          * with respect to interrupt delivery - think about what happens
980          * if we have tested for an interrupt, then get scheduled
981          * before the apr_sleep() call and while waiting for the cpu
982          * we do get an interrupt
983          */
984         if (isdaemon) {
985             while (delay && !interrupted) {
986                 if (delay > APR_USEC_PER_SEC) {
987                     apr_sleep(APR_USEC_PER_SEC);
988                     delay -= APR_USEC_PER_SEC;
989                 }
990                 else {
991                     apr_sleep(delay);
992                     delay = 0;
993                 }
994             }
995         }
996     } while (isdaemon && !interrupted);
997
998     if (!isdaemon && interrupted) {
999         apr_file_printf(errfile,
1000                         "Cache cleaning aborted due to user request.\n");
1001         return 1;
1002     }
1003
1004     return 0;
1005 }