]> granicus.if.org Git - apache/blob - modules/metadata/mod_expires.c
adjust remaining modules to use the new handler hook method (Alan Edwards)
[apache] / modules / metadata / mod_expires.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 /*
60  * mod_expires.c
61  * version 0.0.11
62  * status beta
63  * 
64  * Andrew Wilson <Andrew.Wilson@cm.cf.ac.uk> 26.Jan.96
65  *
66  * This module allows you to control the form of the Expires: header
67  * that Apache issues for each access.  Directives can appear in
68  * configuration files or in .htaccess files so expiry semantics can
69  * be defined on a per-directory basis.  
70  *
71  * DIRECTIVE SYNTAX
72  *
73  * Valid directives are:
74  *
75  *     ExpiresActive on | off
76  *     ExpiresDefault <code><seconds>
77  *     ExpiresByType type/encoding <code><seconds>
78  *
79  * Valid values for <code> are:
80  *
81  *     'M'      expires header shows file modification date + <seconds>
82  *     'A'      expires header shows access time + <seconds>
83  *
84  *              [I'm not sure which of these is best under different
85  *              circumstances, I guess it's for other people to explore.
86  *              The effects may be indistinguishable for a number of cases]
87  *
88  * <seconds> should be an integer value [acceptable to atoi()]
89  *
90  * There is NO space between the <code> and <seconds>.
91  *
92  * For example, a directory which contains information which changes
93  * frequently might contain:
94  *
95  *     # reports generated by cron every hour.  don't let caches
96  *     # hold onto stale information
97  *     ExpiresDefault M3600
98  *
99  * Another example, our html pages can change all the time, the gifs
100  * tend not to change often:
101  * 
102  *     # pages are hot (1 week), images are cold (1 month)
103  *     ExpiresByType text/html A604800
104  *     ExpiresByType image/gif A2592000
105  *
106  * Expires can be turned on for all URLs on the server by placing the
107  * following directive in a conf file:
108  *
109  *     ExpiresActive on
110  *
111  * ExpiresActive can also appear in .htaccess files, enabling the
112  * behaviour to be turned on or off for each chosen directory.
113  *
114  *     # turn off Expires behaviour in this directory
115  *     # and subdirectories
116  *     ExpiresActive off
117  *
118  * Directives defined for a directory are valid in subdirectories
119  * unless explicitly overridden by new directives in the subdirectory
120  * .htaccess files.
121  *
122  * ALTERNATIVE DIRECTIVE SYNTAX
123  *
124  * Directives can also be defined in a more readable syntax of the form:
125  *
126  *     ExpiresDefault "<base> [plus] {<num> <type>}*"
127  *     ExpiresByType type/encoding "<base> [plus] {<num> <type>}*"
128  *
129  * where <base> is one of:
130  *      access  
131  *      now             equivalent to 'access'
132  *      modification
133  *
134  * where the 'plus' keyword is optional
135  *
136  * where <num> should be an integer value [acceptable to atoi()]
137  *
138  * where <type> is one of:
139  *      years
140  *      months
141  *      weeks
142  *      days
143  *      hours
144  *      minutes
145  *      seconds
146  *
147  * For example, any of the following directives can be used to make
148  * documents expire 1 month after being accessed, by default:
149  *
150  *      ExpiresDefault "access plus 1 month"
151  *      ExpiresDefault "access plus 4 weeks"
152  *      ExpiresDefault "access plus 30 days"
153  *
154  * The expiry time can be fine-tuned by adding several '<num> <type>'
155  * clauses:
156  *
157  *      ExpiresByType text/html "access plus 1 month 15 days 2 hours"
158  *      ExpiresByType image/gif "modification plus 5 hours 3 minutes"
159  *
160  * ---
161  *
162  * Change-log:
163  * 29.Jan.96    Hardened the add_* functions.  Server will now bail out
164  *              if bad directives are given in the conf files.
165  * 02.Feb.96    Returns DECLINED if not 'ExpiresActive on', giving other
166  *              expires-aware modules a chance to play with the same
167  *              directives. [Michael Rutman]
168  * 03.Feb.96    Call tzset() before localtime().  Trying to get the module
169  *              to work properly in non GMT timezones.
170  * 12.Feb.96    Modified directive syntax to allow more readable commands:
171  *                ExpiresDefault "now plus 10 days 20 seconds"
172  *                ExpiresDefault "access plus 30 days"
173  *                ExpiresDefault "modification plus 1 year 10 months 30 days"
174  * 13.Feb.96    Fix call to table_get() with NULL 2nd parameter [Rob Hartill]
175  * 19.Feb.96    Call gm_timestr_822() to get time formatted correctly, can't
176  *              rely on presence of HTTP_TIME_FORMAT in Apache 1.1+.
177  * 21.Feb.96    This version (0.0.9) reverses assumptions made in 0.0.8
178  *              about star/star handlers.  Reverting to 0.0.7 behaviour.
179  * 08.Jun.96    allows ExpiresDefault to be used with responses that use 
180  *              the DefaultType by not DECLINING, but instead skipping 
181  *              the table_get check and then looking for an ExpiresDefault.
182  *              [Rob Hartill]
183  * 04.Nov.96    'const' definitions added.
184  *
185  * TODO
186  * add support for Cache-Control: max-age=20 from the HTTP/1.1
187  * proposal (in this case, a ttl of 20 seconds) [ask roy]
188  * add per-file expiry and explicit expiry times - duplicates some
189  * of the mod_cern_meta.c functionality.  eg:
190  *              ExpiresExplicit index.html "modification plus 30 days"
191  *
192  * BUGS
193  * Hi, welcome to the internet.
194  */
195
196 #include "ap_config.h"
197 #ifdef HAVE_CTYPE_H
198 #include <ctype.h>
199 #endif
200 #ifdef HAVE_STRINGS_H
201 #include <strings.h>
202 #endif
203 #include "httpd.h"
204 #include "http_config.h"
205 #include "http_log.h"
206 #include "http_request.h"
207 #include "apr_strings.h"
208
209 typedef struct {
210     int active;
211     char *expiresdefault;
212     apr_table_t *expiresbytype;
213 } expires_dir_config;
214
215 /* from mod_dir, why is this alias used?
216  */
217 #define DIR_CMD_PERMS OR_INDEXES
218
219 #define ACTIVE_ON       1
220 #define ACTIVE_OFF      0
221 #define ACTIVE_DONTCARE 2
222
223 module AP_MODULE_DECLARE_DATA expires_module;
224
225 static void *create_dir_expires_config(apr_pool_t *p, char *dummy)
226 {
227     expires_dir_config *new =
228     (expires_dir_config *) apr_pcalloc(p, sizeof(expires_dir_config));
229     new->active = ACTIVE_DONTCARE;
230     new->expiresdefault = "";
231     new->expiresbytype = apr_make_table(p, 4);
232     return (void *) new;
233 }
234
235 static const char *set_expiresactive(cmd_parms *cmd, void *in_dir_config, int arg)
236 {
237     expires_dir_config *dir_config = in_dir_config;
238
239     /* if we're here at all it's because someone explicitly
240      * set the active flag
241      */
242     dir_config->active = ACTIVE_ON;
243     if (arg == 0) {
244         dir_config->active = ACTIVE_OFF;
245     };
246     return NULL;
247 }
248
249 /* check_code() parse 'code' and return NULL or an error response
250  * string.  If we return NULL then real_code contains code converted
251  * to the cnnnn format.
252  */
253 static char *check_code(apr_pool_t *p, const char *code, char **real_code)
254 {
255     char *word;
256     char base = 'X';
257     int modifier = 0;
258     int num = 0;
259     int factor = 0;
260
261     /* 0.0.4 compatibility?
262      */
263     if ((code[0] == 'A') || (code[0] == 'M')) {
264         *real_code = (char *)code;
265         return NULL;
266     };
267
268     /* <base> [plus] {<num> <type>}*
269      */
270
271     /* <base>
272      */
273     word = ap_getword_conf(p, &code);
274     if (!strncasecmp(word, "now", 1) ||
275         !strncasecmp(word, "access", 1)) {
276         base = 'A';
277     }
278     else if (!strncasecmp(word, "modification", 1)) {
279         base = 'M';
280     }
281     else {
282         return apr_pstrcat(p, "bad expires code, unrecognised <base> '",
283                        word, "'", NULL);
284     };
285
286     /* [plus]
287      */
288     word = ap_getword_conf(p, &code);
289     if (!strncasecmp(word, "plus", 1)) {
290         word = ap_getword_conf(p, &code);
291     };
292
293     /* {<num> <type>}*
294      */
295     while (word[0]) {
296         /* <num>
297          */
298         if (apr_isdigit(word[0])) {
299             num = atoi(word);
300         }
301         else {
302             return apr_pstrcat(p, "bad expires code, numeric value expected <num> '",
303                            word, "'", NULL);
304         };
305
306         /* <type>
307          */
308         word = ap_getword_conf(p, &code);
309         if (word[0]) {
310             /* do nothing */
311         }
312         else {
313             return apr_pstrcat(p, "bad expires code, missing <type>", NULL);
314         };
315
316         factor = 0;
317         if (!strncasecmp(word, "years", 1)) {
318             factor = 60 * 60 * 24 * 365;
319         }
320         else if (!strncasecmp(word, "months", 2)) {
321             factor = 60 * 60 * 24 * 30;
322         }
323         else if (!strncasecmp(word, "weeks", 1)) {
324             factor = 60 * 60 * 24 * 7;
325         }
326         else if (!strncasecmp(word, "days", 1)) {
327             factor = 60 * 60 * 24;
328         }
329         else if (!strncasecmp(word, "hours", 1)) {
330             factor = 60 * 60;
331         }
332         else if (!strncasecmp(word, "minutes", 2)) {
333             factor = 60;
334         }
335         else if (!strncasecmp(word, "seconds", 1)) {
336             factor = 1;
337         }
338         else {
339             return apr_pstrcat(p, "bad expires code, unrecognised <type>",
340                            "'", word, "'", NULL);
341         };
342
343         modifier = modifier + factor * num;
344
345         /* next <num>
346          */
347         word = ap_getword_conf(p, &code);
348     };
349
350     *real_code = apr_psprintf(p, "%c%d", base, modifier);
351
352     return NULL;
353 }
354
355 static const char *set_expiresbytype(cmd_parms *cmd, void *in_dir_config,
356                                      const char *mime, const char *code)
357 {
358     expires_dir_config *dir_config = in_dir_config;
359     char *response, *real_code;
360
361     if ((response = check_code(cmd->pool, code, &real_code)) == NULL) {
362         apr_table_setn(dir_config->expiresbytype, mime, real_code);
363         return NULL;
364     };
365     return apr_pstrcat(cmd->pool,
366                  "'ExpiresByType ", mime, " ", code, "': ", response, NULL);
367 }
368
369 static const char *set_expiresdefault(cmd_parms *cmd, void *in_dir_config,
370                                       const char *code)
371 {
372     expires_dir_config * dir_config = in_dir_config;
373     char *response, *real_code;
374
375     if ((response = check_code(cmd->pool, code, &real_code)) == NULL) {
376         dir_config->expiresdefault = real_code;
377         return NULL;
378     };
379     return apr_pstrcat(cmd->pool,
380                    "'ExpiresDefault ", code, "': ", response, NULL);
381 }
382
383 static const command_rec expires_cmds[] =
384 {
385     AP_INIT_FLAG("ExpiresActive", set_expiresactive, NULL, DIR_CMD_PERMS,
386                  "Limited to 'on' or 'off'"),
387     AP_INIT_TAKE2("ExpiresBytype", set_expiresbytype, NULL, DIR_CMD_PERMS,
388                   "a MIME type followed by an expiry date code"),
389     AP_INIT_TAKE1("ExpiresDefault", set_expiresdefault, NULL, DIR_CMD_PERMS,
390                   "an expiry date code"),
391     {NULL}
392 };
393
394 static void *merge_expires_dir_configs(apr_pool_t *p, void *basev, void *addv)
395 {
396     expires_dir_config *new = (expires_dir_config *) apr_pcalloc(p, sizeof(expires_dir_config));
397     expires_dir_config *base = (expires_dir_config *) basev;
398     expires_dir_config *add = (expires_dir_config *) addv;
399
400     if (add->active == ACTIVE_DONTCARE) {
401         new->active = base->active;
402     }
403     else {
404         new->active = add->active;
405     };
406
407     if (add->expiresdefault != '\0') {
408         new->expiresdefault = add->expiresdefault;
409     };
410
411     new->expiresbytype = apr_overlay_tables(p, add->expiresbytype,
412                                         base->expiresbytype);
413     return new;
414 }
415
416 static int add_expires(request_rec *r)
417 {
418     expires_dir_config *conf;
419     char *code;
420     apr_time_t base;
421     apr_time_t additional;
422     apr_time_t expires;
423     char *timestr;
424
425     if (ap_is_HTTP_ERROR(r->status))       /* Don't add Expires headers to errors */
426         return DECLINED;
427
428     if (r->main != NULL)        /* Say no to subrequests */
429         return DECLINED;
430
431     conf = (expires_dir_config *) ap_get_module_config(r->per_dir_config, &expires_module);
432     if (conf == NULL) {
433         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
434                     "internal error: %s", r->filename);
435         return HTTP_INTERNAL_SERVER_ERROR;
436     };
437
438     if (conf->active != ACTIVE_ON)
439         return DECLINED;
440
441     /* we perhaps could use the default_type(r) in its place but that
442      * may be 2nd guesing the desired configuration...  calling table_get
443      * with a NULL key will SEGV us
444      *
445      * I still don't know *why* r->content_type would ever be NULL, this
446      * is possibly a result of fixups being called in many different
447      * places.  Fixups is probably the wrong place to be doing all this
448      * work...  Bah.
449      *
450      * Changed as of 08.Jun.96 don't DECLINE, look for an ExpiresDefault.
451      */
452     if (r->content_type == NULL)
453         code = NULL;
454     else
455         code = (char *) apr_table_get(conf->expiresbytype, 
456                 ap_field_noparam(r->pool, r->content_type));
457
458     if (code == NULL) {
459         /* no expires defined for that type, is there a default? */
460         code = conf->expiresdefault;
461
462         if (code[0] == '\0')
463             return OK;
464     };
465
466     /* we have our code */
467
468     switch (code[0]) {
469     case 'M':
470         if (r->finfo.protection == 0) { 
471             /* file doesn't exist on disk, so we can't do anything based on
472              * modification time.  Note that this does _not_ log an error.
473              */
474             return DECLINED;
475         }
476         base = r->finfo.mtime;
477         additional = atoi(&code[1]);
478         break;
479     case 'A':
480         /* there's been some discussion and it's possible that 
481          * 'access time' will be stored in request structure
482          */
483         base = r->request_time;
484         additional = atoi(&code[1]);
485         break;
486     default:
487         /* expecting the add_* routines to be case-hardened this 
488          * is just a reminder that module is beta
489          */
490         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
491                     "internal error: bad expires code: %s", r->filename);
492         return HTTP_INTERNAL_SERVER_ERROR;
493     };
494
495     expires = base + additional;
496     apr_table_mergen(r->headers_out, "Cache-Control",
497                     apr_psprintf(r->pool, "max-age=%qd",
498                                 (expires - r->request_time)
499                                     / APR_USEC_PER_SEC));
500     timestr = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
501     apr_rfc822_date(timestr, expires);
502     apr_table_setn(r->headers_out, "Expires", timestr);
503     return OK;
504 }
505
506 static void register_hooks(void)
507 {
508     ap_hook_fixups(add_expires,NULL,NULL,AP_HOOK_MIDDLE);
509 }
510
511 module AP_MODULE_DECLARE_DATA expires_module =
512 {
513     STANDARD20_MODULE_STUFF,
514     create_dir_expires_config,  /* dir config creater */
515     merge_expires_dir_configs,  /* dir merger --- default is to override */
516     NULL,                       /* server config */
517     NULL,                       /* merge server configs */
518     expires_cmds,               /* command apr_table_t */
519     register_hooks              /* register hooks */
520 };