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