xref: /lighttpd1.4/src/mod_expire.c (revision 70b1af06)
1 #include "first.h"
2 
3 #include "base.h"
4 #include "array.h"
5 #include "buffer.h"
6 #include "log.h"
7 #include "http_header.h"
8 
9 #include "plugin.h"
10 #include "stat_cache.h"
11 
12 #include <stdlib.h>
13 #include <string.h>
14 #include <time.h>
15 
16 /**
17  * set HTTP headers Cache-Control and Expires
18  */
19 
20 typedef struct {
21     const array *expire_url;
22     const array *expire_mimetypes;
23 } plugin_config;
24 
25 typedef struct {
26     PLUGIN_DATA;
27     plugin_config defaults;
28     plugin_config conf;
29     time_t *toffsets;
30     uint32_t tused;
31 } plugin_data;
32 
33 INIT_FUNC(mod_expire_init) {
34     return calloc(1, sizeof(plugin_data));
35 }
36 
37 FREE_FUNC(mod_expire_free) {
38     plugin_data * const p = p_d;
39     free(p->toffsets);
40 }
41 
42 static time_t mod_expire_get_offset(log_error_st *errh, const buffer *expire, time_t *offset) {
43 	char *ts;
44 	time_t type = -1;
45 	time_t retts = 0;
46 
47 	/*
48 	 * parse
49 	 *
50 	 * '(access|now|modification) [plus] {<num> <type>}*'
51 	 *
52 	 * e.g. 'access 1 years'
53 	 */
54 
55 	if (buffer_string_is_empty(expire)) {
56 		log_error(errh, __FILE__, __LINE__, "mod_expire empty string");
57 		return -1;
58 	}
59 
60 	ts = expire->ptr;
61 
62 	if (0 == strncmp(ts, "access ", 7)) {
63 		type  = 0;
64 		ts   += 7;
65 	} else if (0 == strncmp(ts, "now ", 4)) {
66 		type  = 0;
67 		ts   += 4;
68 	} else if (0 == strncmp(ts, "modification ", 13)) {
69 		type  = 1;
70 		ts   += 13;
71 	} else {
72 		/* invalid type-prefix */
73 		log_error(errh, __FILE__, __LINE__, "invalid <base>: %s", ts);
74 		return -1;
75 	}
76 
77 	if (0 == strncmp(ts, "plus ", 5)) {
78 		/* skip the optional plus */
79 		ts   += 5;
80 	}
81 
82 	/* the rest is just <number> (years|months|weeks|days|hours|minutes|seconds) */
83 	while (1) {
84 		char *space, *err;
85 		int num;
86 
87 		if (NULL == (space = strchr(ts, ' '))) {
88 			log_error(errh, __FILE__, __LINE__,
89 			  "missing space after <num>: %s", ts);
90 			return -1;
91 		}
92 
93 		num = strtol(ts, &err, 10);
94 		if (*err != ' ') {
95 			log_error(errh, __FILE__, __LINE__,
96 			  "missing <type> after <num>: %s", ts);
97 			return -1;
98 		}
99 
100 		ts = space + 1;
101 
102 		if (NULL != (space = strchr(ts, ' '))) {
103 			int slen;
104 			/* */
105 
106 			slen = space - ts;
107 
108 			if (slen == 5 &&
109 			    0 == strncmp(ts, "years", slen)) {
110 				num *= 60 * 60 * 24 * 30 * 12;
111 			} else if (slen == 6 &&
112 				   0 == strncmp(ts, "months", slen)) {
113 				num *= 60 * 60 * 24 * 30;
114 			} else if (slen == 5 &&
115 				   0 == strncmp(ts, "weeks", slen)) {
116 				num *= 60 * 60 * 24 * 7;
117 			} else if (slen == 4 &&
118 				   0 == strncmp(ts, "days", slen)) {
119 				num *= 60 * 60 * 24;
120 			} else if (slen == 5 &&
121 				   0 == strncmp(ts, "hours", slen)) {
122 				num *= 60 * 60;
123 			} else if (slen == 7 &&
124 				   0 == strncmp(ts, "minutes", slen)) {
125 				num *= 60;
126 			} else if (slen == 7 &&
127 				   0 == strncmp(ts, "seconds", slen)) {
128 				num *= 1;
129 			} else {
130 				log_error(errh, __FILE__, __LINE__, "unknown type: %s", ts);
131 				return -1;
132 			}
133 
134 			retts += num;
135 
136 			ts = space + 1;
137 		} else {
138 			if (0 == strcmp(ts, "years")) {
139 				num *= 60 * 60 * 24 * 30 * 12;
140 			} else if (0 == strcmp(ts, "months")) {
141 				num *= 60 * 60 * 24 * 30;
142 			} else if (0 == strcmp(ts, "weeks")) {
143 				num *= 60 * 60 * 24 * 7;
144 			} else if (0 == strcmp(ts, "days")) {
145 				num *= 60 * 60 * 24;
146 			} else if (0 == strcmp(ts, "hours")) {
147 				num *= 60 * 60;
148 			} else if (0 == strcmp(ts, "minutes")) {
149 				num *= 60;
150 			} else if (0 == strcmp(ts, "seconds")) {
151 				num *= 1;
152 			} else {
153 				log_error(errh, __FILE__, __LINE__, "unknown type: %s", ts);
154 				return -1;
155 			}
156 
157 			retts += num;
158 
159 			break;
160 		}
161 	}
162 
163 	*offset = retts;
164 
165 	return type;
166 }
167 
168 static void mod_expire_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv) {
169     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
170       case 0: /* expire.url */
171         pconf->expire_url = cpv->v.a;
172         break;
173       case 1: /* expire.mimetypes */
174         pconf->expire_mimetypes = cpv->v.a;
175         break;
176       default:/* should not happen */
177         return;
178     }
179 }
180 
181 static void mod_expire_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) {
182     do {
183         mod_expire_merge_config_cpv(pconf, cpv);
184     } while ((++cpv)->k_id != -1);
185 }
186 
187 static void mod_expire_patch_config(request_st * const r, plugin_data * const p) {
188     p->conf = p->defaults; /* copy small struct instead of memcpy() */
189     /*memcpy(&p->conf, &p->defaults, sizeof(plugin_config));*/
190     for (int i = 1, used = p->nconfig; i < used; ++i) {
191         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
192             mod_expire_merge_config(&p->conf, p->cvlist + p->cvlist[i].v.u2[0]);
193     }
194 }
195 
196 SETDEFAULTS_FUNC(mod_expire_set_defaults) {
197     static const config_plugin_keys_t cpk[] = {
198       { CONST_STR_LEN("expire.url"),
199         T_CONFIG_ARRAY_KVSTRING,
200         T_CONFIG_SCOPE_CONNECTION }
201      ,{ CONST_STR_LEN("expire.mimetypes"),
202         T_CONFIG_ARRAY_KVSTRING,
203         T_CONFIG_SCOPE_CONNECTION }
204      ,{ NULL, 0,
205         T_CONFIG_UNSET,
206         T_CONFIG_SCOPE_UNSET }
207     };
208 
209     plugin_data * const p = p_d;
210     if (!config_plugin_values_init(srv, p, cpk, "mod_expire"))
211         return HANDLER_ERROR;
212 
213     /* process and validate config directives
214      * (init i to 0 if global context; to 1 to skip empty global context) */
215     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
216         const config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
217         for (; -1 != cpv->k_id; ++cpv) {
218             const array *a = NULL;
219             switch (cpv->k_id) {
220               case 0: /* expire.url */
221                 a = cpv->v.a;
222                 break;
223               case 1: /* expire.mimetypes */
224                 for (uint32_t k = 0; k < cpv->v.a->used; ++k) {
225                     data_string *ds = (data_string *)cpv->v.a->data[k];
226                     /*(omit trailing '*', if present, from prefix match)*/
227                     /*(not usually a good idea to modify array keys
228                      * since doing so might break array_get_element_klen()
229                      * search; config should be consistent in using * or not)*/
230                     size_t klen = buffer_string_length(&ds->key);
231                     if (klen && ds->key.ptr[klen-1] == '*')
232                         buffer_string_set_length(&ds->key, klen-1);
233                 }
234                 a = cpv->v.a;
235                 break;
236               default:/* should not happen */
237                 break;
238             }
239 
240             /* parse array values into structured data */
241             if (NULL != a && a->used) {
242                 p->toffsets =
243                   realloc(p->toffsets, sizeof(time_t) * (p->tused + a->used*2));
244                 time_t *toff = p->toffsets + p->tused;
245                 for (uint32_t k = 0; k < a->used; ++k, toff+=2, p->tused+=2) {
246                     buffer *v = &((data_string *)a->data[k])->value;
247                     *toff = mod_expire_get_offset(srv->errh, v, toff+1);
248                     if (-1 == *toff) {
249                         log_error(srv->errh, __FILE__, __LINE__,
250                           "parsing %s failed: %s", cpk[cpv->k_id].k, v->ptr);
251                         return HANDLER_ERROR;
252                     }
253                     /* overwrite v->used with offset int p->toffsets
254                      * as v->ptr is not used by this module after config */
255                     v->used = (uint32_t)p->tused;
256                 }
257             }
258         }
259     }
260 
261     /* initialize p->defaults from global config context */
262     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
263         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
264         if (-1 != cpv->k_id)
265             mod_expire_merge_config(&p->defaults, cpv);
266     }
267 
268     return HANDLER_GO_ON;
269 }
270 
271 REQUEST_FUNC(mod_expire_handler) {
272 	plugin_data *p = p_d;
273 	const buffer *vb;
274 	const data_string *ds;
275 
276 	/* Add caching headers only to http_status 200 OK or 206 Partial Content */
277 	if (r->http_status != 200 && r->http_status != 206) return HANDLER_GO_ON;
278 	/* Add caching headers only to GET or HEAD requests */
279 	if (!http_method_get_or_head(r->http_method)) return HANDLER_GO_ON;
280 	/* Add caching headers only if not already present */
281 	vb = http_header_response_get(r, HTTP_HEADER_CACHE_CONTROL, CONST_STR_LEN("Cache-Control"));
282 	if (NULL != vb) return HANDLER_GO_ON;
283 
284 	mod_expire_patch_config(r, p);
285 
286 	/* check expire.url */
287 	ds = p->conf.expire_url
288 	  ? (const data_string *)array_match_key_prefix(p->conf.expire_url, &r->uri.path)
289 	  : NULL;
290 	/* check expire.mimetypes (if no match with expire.url) */
291 	if (NULL == ds) {
292 		if (NULL == p->conf.expire_mimetypes) return HANDLER_GO_ON;
293 		vb = http_header_response_get(r, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type"));
294 		ds = (NULL != vb)
295 		   ? (const data_string *)array_match_key_prefix(p->conf.expire_mimetypes, vb)
296 		   : (const data_string *)array_get_element_klen(p->conf.expire_mimetypes, CONST_STR_LEN(""));
297 		if (NULL == ds) return HANDLER_GO_ON;
298 	}
299 
300 	const time_t * const off = p->toffsets + ds->value.used;
301 	const time_t cur_ts = log_epoch_secs;
302 	time_t expires = off[1];
303 	if (0 == off[0]) { /* access */
304 		expires += cur_ts;
305 	}
306 	else {             /* modification */
307 		stat_cache_entry *sce = stat_cache_get_entry(&r->physical.path);
308 		/* can't set modification-based expire if mtime is not available */
309 		if (NULL == sce) return HANDLER_GO_ON;
310 		expires += sce->st.st_mtime;
311 	}
312 
313 			/* expires should be at least cur_ts */
314 			if (expires < cur_ts) expires = cur_ts;
315 
316 			buffer * const tb = r->tmp_buf;
317 
318 			/* HTTP/1.0 */
319 			buffer_clear(tb);
320 			buffer_append_strftime(tb, "%a, %d %b %Y %H:%M:%S GMT", gmtime(&(expires)));
321 			http_header_response_set(r, HTTP_HEADER_OTHER, CONST_STR_LEN("Expires"), CONST_BUF_LEN(tb));
322 
323 			/* HTTP/1.1 */
324 			buffer_copy_string_len(tb, CONST_STR_LEN("max-age="));
325 			buffer_append_int(tb, expires - cur_ts); /* as expires >= cur_ts the difference is >= 0 */
326 			http_header_response_set(r, HTTP_HEADER_CACHE_CONTROL, CONST_STR_LEN("Cache-Control"), CONST_BUF_LEN(tb));
327 
328 	return HANDLER_GO_ON;
329 }
330 
331 
332 int mod_expire_plugin_init(plugin *p);
333 int mod_expire_plugin_init(plugin *p) {
334 	p->version     = LIGHTTPD_VERSION_ID;
335 	p->name        = "expire";
336 
337 	p->init        = mod_expire_init;
338 	p->cleanup     = mod_expire_free;
339 	p->set_defaults= mod_expire_set_defaults;
340 	p->handle_response_start = mod_expire_handler;
341 
342 	return 0;
343 }
344