xref: /lighttpd1.4/src/mod_expire.c (revision 03b4c993)
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(connection * const con, plugin_data * const p) {
188     memcpy(&p->conf, &p->defaults, sizeof(plugin_config));
189     for (int i = 1, used = p->nconfig; i < used; ++i) {
190         if (config_check_cond(con, (uint32_t)p->cvlist[i].k_id))
191             mod_expire_merge_config(&p->conf, p->cvlist + p->cvlist[i].v.u2[0]);
192     }
193 }
194 
195 SETDEFAULTS_FUNC(mod_expire_set_defaults) {
196     static const config_plugin_keys_t cpk[] = {
197       { CONST_STR_LEN("expire.url"),
198         T_CONFIG_ARRAY_KVSTRING,
199         T_CONFIG_SCOPE_CONNECTION }
200      ,{ CONST_STR_LEN("expire.mimetypes"),
201         T_CONFIG_ARRAY_KVSTRING,
202         T_CONFIG_SCOPE_CONNECTION }
203      ,{ NULL, 0,
204         T_CONFIG_UNSET,
205         T_CONFIG_SCOPE_UNSET }
206     };
207 
208     plugin_data * const p = p_d;
209     if (!config_plugin_values_init(srv, p, cpk, "mod_expire"))
210         return HANDLER_ERROR;
211 
212     /* process and validate config directives
213      * (init i to 0 if global context; to 1 to skip empty global context) */
214     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
215         const config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
216         for (; -1 != cpv->k_id; ++cpv) {
217             const array *a = NULL;
218             switch (cpv->k_id) {
219               case 0: /* expire.url */
220                 a = cpv->v.a;
221                 break;
222               case 1: /* expire.mimetypes */
223                 for (uint32_t k = 0; k < cpv->v.a->used; ++k) {
224                     data_string *ds = (data_string *)cpv->v.a->data[k];
225                     /*(omit trailing '*', if present, from prefix match)*/
226                     /*(not usually a good idea to modify array keys
227                      * since doing so might break array_get_element_klen()
228                      * search; config should be consistent in using * or not)*/
229                     size_t klen = buffer_string_length(&ds->key);
230                     if (klen && ds->key.ptr[klen-1] == '*')
231                         buffer_string_set_length(&ds->key, klen-1);
232                 }
233                 a = cpv->v.a;
234                 break;
235               default:/* should not happen */
236                 break;
237             }
238 
239             /* parse array values into structured data */
240             if (NULL != a && a->used) {
241                 p->toffsets =
242                   realloc(p->toffsets, sizeof(time_t) * (p->tused + a->used*2));
243                 time_t *toff = p->toffsets + p->tused;
244                 for (uint32_t k = 0; k < a->used; ++k, toff+=2, p->tused+=2) {
245                     buffer *v = &((data_string *)a->data[k])->value;
246                     *toff = mod_expire_get_offset(srv->errh, v, toff+1);
247                     if (-1 == *toff) {
248                         log_error(srv->errh, __FILE__, __LINE__,
249                           "parsing %s failed: %s", cpk[cpv->k_id].k, v->ptr);
250                         return HANDLER_ERROR;
251                     }
252                     /* overwrite v->used with offset int p->toffsets
253                      * as v->ptr is not used by this module after config */
254                     v->used = (uint32_t)p->tused;
255                 }
256             }
257         }
258     }
259 
260     /* initialize p->defaults from global config context */
261     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
262         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
263         if (-1 != cpv->k_id)
264             mod_expire_merge_config(&p->defaults, cpv);
265     }
266 
267     return HANDLER_GO_ON;
268 }
269 
270 CONNECTION_FUNC(mod_expire_handler) {
271 	plugin_data *p = p_d;
272 	const buffer *vb;
273 	const data_string *ds;
274 
275 	/* Add caching headers only to http_status 200 OK or 206 Partial Content */
276 	if (con->http_status != 200 && con->http_status != 206) return HANDLER_GO_ON;
277 	/* Add caching headers only to GET or HEAD requests */
278 	if (   con->request.http_method != HTTP_METHOD_GET
279 	    && con->request.http_method != HTTP_METHOD_HEAD) return HANDLER_GO_ON;
280 	/* Add caching headers only if not already present */
281 	vb = http_header_response_get(con, HTTP_HEADER_CACHE_CONTROL, CONST_STR_LEN("Cache-Control"));
282 	if (NULL != vb) return HANDLER_GO_ON;
283 
284 	if (buffer_is_empty(con->uri.path)) return HANDLER_GO_ON;
285 
286 	mod_expire_patch_config(con, p);
287 
288 	/* check expire.url */
289 	ds = p->conf.expire_url
290 	  ? (const data_string *)array_match_key_prefix(p->conf.expire_url, con->uri.path)
291 	  : NULL;
292 	/* check expire.mimetypes (if no match with expire.url) */
293 	if (NULL == ds) {
294 		if (NULL == p->conf.expire_mimetypes) return HANDLER_GO_ON;
295 		vb = http_header_response_get(con, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type"));
296 		ds = (NULL != vb)
297 		   ? (const data_string *)array_match_key_prefix(p->conf.expire_mimetypes, vb)
298 		   : (const data_string *)array_get_element_klen(p->conf.expire_mimetypes, CONST_STR_LEN(""));
299 		if (NULL == ds) return HANDLER_GO_ON;
300 	}
301 
302 	const time_t * const off = p->toffsets + ds->value.used;
303 	const time_t cur_ts = log_epoch_secs;
304 	time_t expires = off[1];
305 	if (0 == off[0]) { /* access */
306 		expires += cur_ts;
307 	}
308 	else {             /* modification */
309 		stat_cache_entry *sce = stat_cache_get_entry(con->physical.path);
310 		/* can't set modification-based expire if mtime is not available */
311 		if (NULL == sce) return HANDLER_GO_ON;
312 		expires += sce->st.st_mtime;
313 	}
314 
315 			/* expires should be at least cur_ts */
316 			if (expires < cur_ts) expires = cur_ts;
317 
318 			buffer * const tb = con->srv->tmp_buf;
319 
320 			/* HTTP/1.0 */
321 			buffer_clear(tb);
322 			buffer_append_strftime(tb, "%a, %d %b %Y %H:%M:%S GMT", gmtime(&(expires)));
323 			http_header_response_set(con, HTTP_HEADER_OTHER, CONST_STR_LEN("Expires"), CONST_BUF_LEN(tb));
324 
325 			/* HTTP/1.1 */
326 			buffer_copy_string_len(tb, CONST_STR_LEN("max-age="));
327 			buffer_append_int(tb, expires - cur_ts); /* as expires >= cur_ts the difference is >= 0 */
328 			http_header_response_set(con, HTTP_HEADER_CACHE_CONTROL, CONST_STR_LEN("Cache-Control"), CONST_BUF_LEN(tb));
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