xref: /lighttpd1.4/src/mod_evhost.c (revision 66698469)
1 #include "first.h"
2 
3 #include "base.h"
4 #include "plugin.h"
5 #include "log.h"
6 #include "stat_cache.h"
7 
8 #include <stdlib.h>
9 #include <string.h>
10 
11 /**
12  *
13  * #
14  * # define a pattern for the host url finding
15  * # %% => % sign
16  * # %0 => domain name + tld
17  * # %1 => tld
18  * # %2 => domain name without tld
19  * # %3 => subdomain 1 name
20  * # %4 => subdomain 2 name
21  * # %_ => fqdn (without port info)
22  * #
23  * evhost.path-pattern = "/home/ckruse/dev/www/%3/htdocs/"
24  *
25  */
26 
27 typedef struct {
28     /* pieces for path creation */
29     const buffer *path_pieces;
30 } plugin_config;
31 
32 typedef struct {
33     PLUGIN_DATA;
34     plugin_config defaults;
35     plugin_config conf;
36 
37     array split_vals;
38 } plugin_data;
39 
40 INIT_FUNC(mod_evhost_init) {
41     return calloc(1, sizeof(plugin_data));
42 }
43 
44 static void mod_evhost_free_path_pieces(const buffer *path_pieces) {
45     buffer *b;
46     *(const buffer **)&b = path_pieces;
47     for (; path_pieces->ptr; ++path_pieces) free(path_pieces->ptr);
48     free(b);
49 }
50 
51 FREE_FUNC(mod_evhost_free) {
52     plugin_data * const p = p_d;
53     array_free_data(&p->split_vals);
54     if (NULL == p->cvlist) return;
55     /* (init i to 0 if global context; to 1 to skip empty global context) */
56     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
57         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
58         for (; -1 != cpv->k_id; ++cpv) {
59             if (cpv->vtype != T_CONFIG_LOCAL || NULL == cpv->v.v) continue;
60             switch (cpv->k_id) {
61               case 0: /* evhost.path-pattern */
62                 mod_evhost_free_path_pieces(cpv->v.v);
63                 break;
64               default:
65                 break;
66             }
67         }
68     }
69 }
70 
71 __attribute_cold__
72 static buffer * mod_evhost_parse_pattern_err(buffer *bptr) {
73     for (; bptr->ptr; ++bptr) free(bptr->ptr);
74     return NULL;
75 }
76 
77 static buffer * mod_evhost_parse_pattern(const char *ptr) {
78 	uint32_t used = 0;
79 	const uint32_t sz = 127;/* (sz+1 must match bptr[] num elts below) */
80 	const char *pos;
81 	buffer bptr[128]; /* (128 elements takes 2k on stack in 64-bit) */
82 	memset(bptr, 0, sizeof(bptr));
83 
84 	for(pos=ptr;*ptr;ptr++) {
85 		if(*ptr == '%') {
86 			size_t len;
87 			if (used >= sz-1) /* (should not happen) */
88 				return mod_evhost_parse_pattern_err(bptr);
89 
90 			/* "%%" "%_" "%x" "%{x.y}" where x and y are *single digit* 0 - 9 */
91 			if (ptr[1] == '%' || ptr[1] == '_' || light_isdigit(ptr[1])) {
92 				len = 2;
93 			} else if (ptr[1] == '{') {
94 				if (!light_isdigit(ptr[2]))
95 					return mod_evhost_parse_pattern_err(bptr);
96 				if (ptr[3] == '.') {
97 					if (!light_isdigit(ptr[4]))
98 						return mod_evhost_parse_pattern_err(bptr);
99 					if (ptr[5] != '}')
100 						return mod_evhost_parse_pattern_err(bptr);
101 					len = 6;
102 				} else if (ptr[3] == '}') {
103 					len = 4;
104 				} else {
105 					return mod_evhost_parse_pattern_err(bptr);
106 				}
107 			} else {
108 				return mod_evhost_parse_pattern_err(bptr);
109 			}
110 
111 			buffer_copy_string_len(bptr+used, pos, ptr-pos);
112 			pos = ptr + len;
113 
114 			buffer_copy_string_len(bptr+used+1, ptr, len);
115 			ptr += len - 1; /*(ptr++ in for() loop)*/
116 
117 			used += 2;
118 		}
119 	}
120 
121 	if(*pos != '\0') {
122 		if (used >= sz) /* (should not happen) */
123 			return mod_evhost_parse_pattern_err(bptr);
124 		buffer_copy_string_len(bptr+used, pos, ptr-pos);
125 		++used;
126 	}
127 
128 	buffer * const path_pieces =
129 	  malloc(sizeof(bptr) + ((used+1) * sizeof(buffer)));
130 	force_assert(path_pieces);
131 	return memcpy(path_pieces, bptr, (used+1) * sizeof(buffer));
132 }
133 
134 static void mod_evhost_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv) {
135     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
136       case 0: /* evhost.path-pattern */
137         if (cpv->vtype == T_CONFIG_LOCAL)
138             pconf->path_pieces = cpv->v.v;
139         break;
140       default:/* should not happen */
141         return;
142     }
143 }
144 
145 static void mod_evhost_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) {
146     do {
147         mod_evhost_merge_config_cpv(pconf, cpv);
148     } while ((++cpv)->k_id != -1);
149 }
150 
151 static void mod_evhost_patch_config(request_st * const r, plugin_data * const p) {
152     p->conf = p->defaults; /* copy small struct instead of memcpy() */
153     /*memcpy(&p->conf, &p->defaults, sizeof(plugin_config));*/
154     for (int i = 1, used = p->nconfig; i < used; ++i) {
155         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
156             mod_evhost_merge_config(&p->conf, p->cvlist + p->cvlist[i].v.u2[0]);
157     }
158 }
159 
160 SETDEFAULTS_FUNC(mod_evhost_set_defaults) {
161     static const config_plugin_keys_t cpk[] = {
162       { CONST_STR_LEN("evhost.path-pattern"),
163         T_CONFIG_STRING,
164         T_CONFIG_SCOPE_CONNECTION }
165      ,{ NULL, 0,
166         T_CONFIG_UNSET,
167         T_CONFIG_SCOPE_UNSET }
168     };
169 
170     plugin_data * const p = p_d;
171     if (!config_plugin_values_init(srv, p, cpk, "mod_evhost"))
172         return HANDLER_ERROR;
173 
174     /* process and validate config directives
175      * (init i to 0 if global context; to 1 to skip empty global context) */
176     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
177         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
178         for (; -1 != cpv->k_id; ++cpv) {
179             switch (cpv->k_id) {
180               case 0: /* evhost.path-pattern */
181                 if (!buffer_is_blank(cpv->v.b)) {
182                     const char * const ptr = cpv->v.b->ptr;
183                     cpv->v.v = mod_evhost_parse_pattern(ptr);
184                     if (NULL == cpv->v.v) {
185                         log_error(srv->errh, __FILE__, __LINE__,
186                           "invalid evhost.path-pattern: %s", ptr);
187                         return HANDLER_ERROR;
188                     }
189                     cpv->vtype = T_CONFIG_LOCAL;
190                 }
191                 break;
192               default:/* should not happen */
193                 break;
194             }
195         }
196     }
197 
198     /* initialize p->defaults from global config context */
199     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
200         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
201         if (-1 != cpv->k_id)
202             mod_evhost_merge_config(&p->defaults, cpv);
203     }
204 
205     return HANDLER_GO_ON;
206 }
207 
208 /**
209  * assign the different parts of the domain to array-indezes (sub2.sub1.domain.tld)
210  * - %0 - domain.tld
211  * - %1 - tld
212  * - %2 - domain
213  * - %3 - sub1
214  * - ...
215  */
216 
217 static void mod_evhost_parse_host(buffer *key, array *host, buffer *authority) {
218 	char *ptr = authority->ptr + buffer_clen(authority);
219 	char *colon = ptr; /* needed to filter out the colon (if exists) */
220 	int first = 1;
221 	int i;
222 
223 	/*if (ptr == authority->ptr) return;*//*(no authority checked earlier)*/
224 
225 	if (*authority->ptr == '[') { /* authority is IPv6 literal address */
226                 colon = ptr;
227                 if (ptr[-1] != ']') {
228 			do { --ptr; } while (ptr > authority->ptr && ptr[-1] != ']');
229 			if (*ptr != ':') return; /*(should not happen for valid authority)*/
230 			colon = ptr;
231 		}
232 		ptr = authority->ptr;
233 		array_set_key_value(host,CONST_STR_LEN("%0"),ptr,colon-ptr);
234 		return;
235 	}
236 
237 	/* first, find the domain + tld */
238 	for(; ptr > authority->ptr; --ptr) {
239 		if(*ptr == '.') {
240 			if(first) first = 0;
241 			else      break;
242 		} else if(*ptr == ':') {
243 			colon = ptr;
244 			first = 1;
245 		}
246 	}
247 
248 	/* if we stopped at a dot, skip the dot */
249 	if (*ptr == '.') ptr++;
250 	array_set_key_value(host, CONST_STR_LEN("%0"), ptr, colon-ptr);
251 
252 	/* if the : is not the start of the authority, go on parsing the hostname */
253 
254 	if (colon != authority->ptr) {
255 		for(ptr = colon - 1, i = 1; ptr > authority->ptr; --ptr) {
256 			if(*ptr == '.') {
257 				if (ptr != colon - 1) {
258 					/* is something between the dots */
259 					buffer_clear(key);
260 					buffer_append_char(key, '%');
261 					buffer_append_int(key, i++);
262 					array_set_key_value(host, BUF_PTR_LEN(key), ptr+1, colon-ptr-1);
263 				}
264 				colon = ptr;
265 			}
266 		}
267 
268 		/* if the . is not the first character of the hostname */
269 		if (colon != ptr) {
270 			buffer_clear(key);
271 			buffer_append_char(key, '%');
272 			buffer_append_int(key, i /* ++ */);
273 			array_set_key_value(host, BUF_PTR_LEN(key), ptr, colon-ptr);
274 		}
275 	}
276 }
277 
278 static void mod_evhost_build_doc_root_path(buffer *b, array *parsed_host, buffer *authority, const buffer *path_pieces) {
279 	array_reset_data_strings(parsed_host);
280 	mod_evhost_parse_host(b, parsed_host, authority);
281 	buffer_clear(b);
282 
283 	for (const char *ptr; (ptr = path_pieces->ptr); ++path_pieces) {
284 		if (*ptr == '%') {
285 			const data_string *ds;
286 
287 			if (*(ptr+1) == '%') {
288 				/* %% */
289 				buffer_append_char(b, '%');
290 			} else if (*(ptr+1) == '_' ) {
291 				/* %_ == full hostname */
292 				char *colon = strchr(authority->ptr, ':');
293 
294 				if(colon == NULL) {
295 					buffer_append_string_buffer(b, authority); /* adds fqdn */
296 				} else {
297 					/* strip the port out of the authority-part of the URI scheme */
298 					buffer_append_string_len(b, authority->ptr, colon - authority->ptr); /* adds fqdn */
299 				}
300 			} else if (ptr[1] == '{' ) {
301 				char s[3] = "% ";
302 				s[1] = ptr[2]; /*(assumes single digit before '.', and, optionally, '.' and single digit after '.')*/
303 				if (NULL != (ds = (data_string *)array_get_element_klen(parsed_host, s, 2))) {
304 					if (ptr[3] != '.' || ptr[4] == '0') {
305 						buffer_append_string_buffer(b, &ds->value);
306 					} else {
307 						if ((size_t)(ptr[4]-'0') <= buffer_clen(&ds->value)) {
308 							buffer_append_char(b, ds->value.ptr[(ptr[4]-'0')-1]);
309 						}
310 					}
311 				} else {
312 					/* unhandled %-sequence */
313 				}
314 			} else if (NULL != (ds = (data_string *)array_get_element_klen(parsed_host, BUF_PTR_LEN(path_pieces)))) {
315 				buffer_append_string_buffer(b, &ds->value);
316 			} else {
317 				/* unhandled %-sequence */
318 			}
319 		} else {
320 			buffer_append_string_buffer(b, path_pieces);
321 		}
322 	}
323 
324 	buffer_append_slash(b);
325 }
326 
327 static handler_t mod_evhost_uri_handler(request_st * const r, void *p_d) {
328 	plugin_data *p = p_d;
329 
330 	/* not authority set */
331 	if (buffer_is_blank(&r->uri.authority)) return HANDLER_GO_ON;
332 
333 	mod_evhost_patch_config(r, p);
334 
335 	/* missing even default(global) conf */
336 	if (NULL == p->conf.path_pieces) return HANDLER_GO_ON;
337 
338 	buffer * const b = r->tmp_buf;/*(tmp_buf cleared before use in call below)*/
339 	mod_evhost_build_doc_root_path(b, &p->split_vals, &r->uri.authority, p->conf.path_pieces);
340 
341 	if (!stat_cache_path_isdir(b)) {
342 		log_perror(r->conf.errh, __FILE__, __LINE__, "%s", b->ptr);
343 	} else {
344 		buffer_copy_buffer(&r->physical.doc_root, b);
345 	}
346 
347 	return HANDLER_GO_ON;
348 }
349 
350 int mod_evhost_plugin_init(plugin *p);
351 int mod_evhost_plugin_init(plugin *p) {
352 	p->version     = LIGHTTPD_VERSION_ID;
353 	p->name        = "evhost";
354 	p->init                    = mod_evhost_init;
355 	p->set_defaults            = mod_evhost_set_defaults;
356 	p->handle_docroot          = mod_evhost_uri_handler;
357 	p->cleanup                 = mod_evhost_free;
358 
359 	return 0;
360 }
361