xref: /lighttpd1.4/src/configfile.c (revision e11f72b1)
1 #include "first.h"
2 
3 #include "base.h"
4 #include "burl.h"
5 #include "etag.h"
6 #include "fdevent.h"
7 #include "keyvalue.h"
8 #include "log.h"
9 #include "stream.h"
10 
11 #include "configparser.h"
12 #include "configfile.h"
13 #include "plugin.h"
14 #include "stat_cache.h"
15 #include "sys-crypto.h"
16 
17 #include <sys/stat.h>
18 #include <sys/wait.h>
19 
20 #include <stdlib.h>
21 #include <fcntl.h>
22 #include <unistd.h>
23 #include <errno.h>
24 #include <string.h>
25 #include <ctype.h>
26 #include <limits.h>
27 #include <glob.h>
28 
29 #ifdef HAVE_SYSLOG_H
30 # include <syslog.h>
31 #endif
32 
33 #ifndef PATH_MAX
34 #define PATH_MAX 4096
35 #endif
36 
37 typedef struct {
38     PLUGIN_DATA;
39     request_config defaults;
40 } config_data_base;
41 
42 static void config_free_config(void * const p_d) {
43     plugin_data_base * const p = p_d;
44     if (NULL == p) return;
45     if (NULL == p->cvlist) { free(p); return; }
46     /* (init i to 0 if global context; to 1 to skip empty global context) */
47     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
48         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
49         for (; -1 != cpv->k_id; ++cpv) {
50             switch (cpv->k_id) {
51               case 18:/* server.kbytes-per-second */
52                 if (cpv->vtype == T_CONFIG_LOCAL) free(cpv->v.v);
53                 break;
54               default:
55                 break;
56             }
57         }
58     }
59     free(p->cvlist);
60     free(p);
61 }
62 
63 void config_reset_config_bytes_sec(void * const p_d) {
64     plugin_data_base * const p = p_d;
65     if (NULL == p->cvlist) return;
66     /* (init i to 0 if global context; to 1 to skip empty global context) */
67     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
68         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
69         for (; -1 != cpv->k_id; ++cpv) {
70             switch (cpv->k_id) {
71               case 18:/* server.kbytes-per-second */
72                 if (cpv->vtype == T_CONFIG_LOCAL) ((off_t *)cpv->v.v)[0] = 0;
73                 break;
74               default:
75                 break;
76             }
77         }
78     }
79 }
80 
81 static void config_merge_config_cpv(request_config * const pconf, const config_plugin_value_t * const cpv) {
82     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
83       case 0: /* server.document-root */
84         pconf->document_root = cpv->v.b;
85         break;
86       case 1: /* server.name */
87         pconf->server_name = cpv->v.b;
88         break;
89       case 2: /* server.tag */
90         pconf->server_tag = cpv->v.b;
91         break;
92       case 3: /* server.max-request-size */
93         pconf->max_request_size = cpv->v.u;
94         break;
95       case 4: /* server.max-keep-alive-requests */
96         pconf->max_keep_alive_requests = cpv->v.shrt;
97         break;
98       case 5: /* server.max-keep-alive-idle */
99         pconf->max_keep_alive_idle = cpv->v.shrt;
100         break;
101       case 6: /* server.max-read-idle */
102         pconf->max_read_idle = cpv->v.shrt;
103         break;
104       case 7: /* server.max-write-idle */
105         pconf->max_write_idle = cpv->v.shrt;
106         break;
107       case 8: /* server.errorfile-prefix */
108         pconf->errorfile_prefix = cpv->v.b;
109         break;
110       case 9: /* server.error-handler */
111         pconf->error_handler = cpv->v.b;
112         break;
113       case 10:/* server.error-handler-404 */
114         pconf->error_handler_404 = cpv->v.b;
115         break;
116       case 11:/* server.error-intercept */
117         pconf->error_intercept = (0 != cpv->v.u);
118         break;
119       case 12:/* server.force-lowercase-filenames */
120         pconf->force_lowercase_filenames = (0 != cpv->v.u);
121         break;
122       case 13:/* server.follow-symlink */
123         pconf->follow_symlink = (0 != cpv->v.u);
124         break;
125       case 14:/* server.protocol-http11 */
126         pconf->allow_http11 = (0 != cpv->v.u);
127         break;
128       case 15:/* server.range-requests */
129         pconf->range_requests = (0 != cpv->v.u);
130         break;
131       case 16:/* server.stream-request-body */
132         pconf->stream_request_body = cpv->v.shrt;
133         break;
134       case 17:/* server.stream-response-body */
135         pconf->stream_response_body = cpv->v.shrt;
136         break;
137       case 18:/* server.kbytes-per-second */
138         pconf->global_bytes_per_second = (unsigned int)((off_t *)cpv->v.v)[1];
139         pconf->global_bytes_per_second_cnt_ptr = cpv->v.v;
140         break;
141       case 19:/* connection.kbytes-per-second */
142         pconf->bytes_per_second = (unsigned int)cpv->v.shrt << 10;/* (*=1024) */
143         break;
144       case 20:/* mimetype.assign */
145         pconf->mimetypes = cpv->v.a;
146         break;
147       case 21:/* mimetype.use-xattr */
148         pconf->use_xattr = (0 != cpv->v.u);
149         break;
150       case 22:/* etag.use-inode */
151         cpv->v.u
152           ? (pconf->etag_flags |=  ETAG_USE_INODE)
153           : (pconf->etag_flags &= ~ETAG_USE_INODE);
154         break;
155       case 23:/* etag.use-mtime */
156         cpv->v.u
157           ? (pconf->etag_flags |=  ETAG_USE_MTIME)
158           : (pconf->etag_flags &= ~ETAG_USE_MTIME);
159         break;
160       case 24:/* etag.use-size */
161         cpv->v.u
162           ? (pconf->etag_flags |=  ETAG_USE_SIZE)
163           : (pconf->etag_flags &= ~ETAG_USE_SIZE);
164         break;
165       case 25:/* debug.log-condition-handling */
166         pconf->log_condition_handling = (0 != cpv->v.u);
167         break;
168       case 26:/* debug.log-file-not-found */
169         pconf->log_file_not_found = (0 != cpv->v.u);
170         break;
171       case 27:/* debug.log-request-handling */
172         pconf->log_request_handling = (0 != cpv->v.u);
173         break;
174       case 28:/* debug.log-request-header */
175         pconf->log_request_header = (0 != cpv->v.u);
176         break;
177       case 29:/* debug.log-response-header */
178         pconf->log_response_header = (0 != cpv->v.u);
179         break;
180       case 30:/* debug.log-timeouts */
181         pconf->log_timeouts = (0 != cpv->v.u);
182         break;
183       case 31: /* server.errorlog */
184         if (cpv->vtype == T_CONFIG_LOCAL) pconf->errh = cpv->v.v;
185         break;
186       case 32:/* server.breakagelog */
187         if (cpv->vtype == T_CONFIG_LOCAL) pconf->serrh = cpv->v.v;
188         break;
189       default:/* should not happen */
190         return;
191     }
192 }
193 
194 static void config_merge_config(request_config * const pconf, const config_plugin_value_t *cpv) {
195     do {
196         config_merge_config_cpv(pconf, cpv);
197     } while ((++cpv)->k_id != -1);
198 }
199 
200 void config_patch_config(request_st * const r) {
201     config_data_base * const p = r->con->config_data_base;
202 
203     /* performed by config_reset_config() */
204     /*memcpy(&r->conf, &p->defaults, sizeof(request_config));*/
205 
206     for (int i = 1, used = p->nconfig; i < used; ++i) {
207         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
208             config_merge_config(&r->conf, p->cvlist + p->cvlist[i].v.u2[0]);
209     }
210 }
211 
212 void config_reset_config(request_st * const r) {
213     /* initialize request_config (r->conf) from top-level request_config */
214     config_data_base * const p = r->con->config_data_base;
215     r->server_name = p->defaults.server_name;
216     memcpy(&r->conf, &p->defaults, sizeof(request_config));
217 }
218 
219 static int config_burl_normalize_cond (server *srv) {
220     buffer * const tb = srv->tmp_buf;
221     for (uint32_t i = 0; i < srv->config_context->used; ++i) {
222         data_config * const config =(data_config *)srv->config_context->data[i];
223         if (COMP_HTTP_QUERY_STRING != config->comp) continue;
224         switch(config->cond) {
225         case CONFIG_COND_NE:
226         case CONFIG_COND_EQ:
227             /* (can use this routine as long as it does not perform
228              *  any regex-specific normalization of first arg) */
229             pcre_keyvalue_burl_normalize_key(&config->string, tb);
230             break;
231         case CONFIG_COND_NOMATCH:
232         case CONFIG_COND_MATCH:
233             pcre_keyvalue_burl_normalize_key(&config->string, tb);
234             if (!data_config_pcre_compile(config)) return 0;
235             break;
236         default:
237             break;
238         }
239     }
240 
241     return 1;
242 }
243 
244 #if defined(HAVE_MYSQL) || (defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER))
245 static void config_warn_authn_module (server *srv, const char *module, size_t len) {
246 	for (uint32_t i = 0; i < srv->config_context->used; ++i) {
247 		const data_config *config = (data_config const*)srv->config_context->data[i];
248 		const data_unset *du = array_get_element_klen(config->value, CONST_STR_LEN("auth.backend"));
249 		if (NULL != du && du->type == TYPE_STRING) {
250 			data_string *ds = (data_string *)du;
251 			if (buffer_is_equal_string(&ds->value, module, len)) {
252 				buffer * const tb = srv->tmp_buf;
253 				buffer_copy_string_len(tb, CONST_STR_LEN("mod_authn_"));
254 				buffer_append_string_len(tb, module, len);
255 				array_insert_value(srv->srvconf.modules, CONST_BUF_LEN(tb));
256 				log_error(srv->errh, __FILE__, __LINE__,
257 				  "Warning: please add \"mod_authn_%s\" to server.modules list "
258 				  "in lighttpd.conf.  A future release of lighttpd 1.4.x will "
259 				  "not automatically load mod_authn_%s and lighttpd will fail "
260 				  "to start up since your lighttpd.conf uses "
261 				  "auth.backend = \"%s\".", module, module, module);
262 				return;
263 			}
264 		}
265 	}
266 }
267 #endif
268 
269 #ifdef USE_OPENSSL_CRYPTO
270 static void config_warn_openssl_module (server *srv) {
271 	for (uint32_t i = 0; i < srv->config_context->used; ++i) {
272 		const data_config *config = (data_config const*)srv->config_context->data[i];
273 		for (uint32_t j = 0; j < config->value->used; ++j) {
274 			data_unset *du = config->value->data[j];
275 			if (0 == strncmp(du->key.ptr, "ssl.", sizeof("ssl.")-1)) {
276 				/* mod_openssl should be loaded after mod_extforward */
277 				array_insert_value(srv->srvconf.modules, CONST_STR_LEN("mod_openssl"));
278 				log_error(srv->errh, __FILE__, __LINE__,
279 				  "Warning: please add \"mod_openssl\" to server.modules list "
280 				  "in lighttpd.conf.  A future release of lighttpd 1.4.x "
281 				  "*will not* automatically load mod_openssl and lighttpd "
282 				  "*will not* use SSL/TLS where your lighttpd.conf contains "
283 				  "ssl.* directives");
284 				return;
285 			}
286 		}
287 	}
288 }
289 #endif
290 
291 static void config_compat_module_load (server *srv) {
292     int prepend_mod_indexfile  = 1;
293     int append_mod_dirlisting  = 1;
294     int append_mod_staticfile  = 1;
295     int append_mod_authn_file  = 1;
296     int append_mod_authn_ldap  = 1;
297     int append_mod_authn_mysql = 1;
298     int append_mod_openssl     = 1;
299     int contains_mod_auth      = 0;
300 
301     for (uint32_t i = 0; i < srv->srvconf.modules->used; ++i) {
302         buffer *m = &((data_string *)srv->srvconf.modules->data[i])->value;
303 
304         if (buffer_eq_slen(m, CONST_STR_LEN("mod_indexfile")))
305             prepend_mod_indexfile = 0;
306         else if (buffer_eq_slen(m, CONST_STR_LEN("mod_staticfile")))
307             append_mod_staticfile = 0;
308         else if (buffer_eq_slen(m, CONST_STR_LEN("mod_dirlisting")))
309             append_mod_dirlisting = 0;
310         else if (buffer_eq_slen(m, CONST_STR_LEN("mod_openssl")))
311             append_mod_openssl = 0;
312         else if (buffer_eq_slen(m, CONST_STR_LEN("mod_authn_file")))
313             append_mod_authn_file = 0;
314         else if (buffer_eq_slen(m, CONST_STR_LEN("mod_authn_ldap")))
315             append_mod_authn_ldap = 0;
316         else if (buffer_eq_slen(m, CONST_STR_LEN("mod_authn_mysql")))
317             append_mod_authn_mysql = 0;
318         else if (buffer_eq_slen(m, CONST_STR_LEN("mod_auth")))
319             contains_mod_auth = 1;
320 
321         if (0 == prepend_mod_indexfile &&
322             0 == append_mod_dirlisting &&
323             0 == append_mod_staticfile &&
324             0 == append_mod_openssl &&
325             0 == append_mod_authn_file &&
326             0 == append_mod_authn_ldap &&
327             0 == append_mod_authn_mysql &&
328             1 == contains_mod_auth) {
329             break;
330         }
331     }
332 
333     /* prepend default modules */
334 
335     if (prepend_mod_indexfile) {
336         /* mod_indexfile has to be loaded before mod_fastcgi and friends */
337         array *modules = array_init(srv->srvconf.modules->used+4);
338         array_insert_value(modules, CONST_STR_LEN("mod_indexfile"));
339 
340         for (uint32_t i = 0; i < srv->srvconf.modules->used; ++i) {
341             data_string *ds = (data_string *)srv->srvconf.modules->data[i];
342             array_insert_value(modules, CONST_BUF_LEN(&ds->value));
343         }
344 
345         array_free(srv->srvconf.modules);
346         srv->srvconf.modules = modules;
347     }
348 
349     /* append default modules */
350 
351     if (append_mod_dirlisting) {
352         array_insert_value(srv->srvconf.modules, CONST_STR_LEN("mod_dirlisting"));
353     }
354 
355     if (append_mod_staticfile) {
356         array_insert_value(srv->srvconf.modules, CONST_STR_LEN("mod_staticfile"));
357     }
358 
359     if (append_mod_openssl) {
360       #ifdef USE_OPENSSL_CRYPTO
361         config_warn_openssl_module(srv);
362       #endif
363     }
364 
365     /* mod_auth.c,http_auth.c auth backends were split into separate modules
366      * Automatically load auth backend modules for compatibility with
367      * existing lighttpd 1.4.x configs */
368     if (contains_mod_auth) {
369         if (append_mod_authn_file) {
370             array_insert_value(srv->srvconf.modules, CONST_STR_LEN("mod_authn_file"));
371         }
372         if (append_mod_authn_ldap) {
373           #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER)
374             config_warn_authn_module(srv, CONST_STR_LEN("ldap"));
375           #endif
376         }
377         if (append_mod_authn_mysql) {
378           #if defined(HAVE_MYSQL)
379             config_warn_authn_module(srv, CONST_STR_LEN("mysql"));
380           #endif
381         }
382     }
383 }
384 
385 static int config_http_parseopts (server *srv, const array *a) {
386     unsigned short int opts = srv->srvconf.http_url_normalize;
387     unsigned short int decode_2f = 1;
388     int rc = 1;
389     for (size_t i = 0; i < a->used; ++i) {
390         const data_string * const ds = (const data_string *)a->data[i];
391         const buffer *k = &ds->key;
392         const buffer *v = &ds->value;
393         unsigned short int opt;
394         int val = 0;
395         if (buffer_eq_slen(v, CONST_STR_LEN("enable")))
396             val = 1;
397         else if (buffer_eq_slen(v, CONST_STR_LEN("disable")))
398             val = 0;
399         else {
400             log_error(srv->errh, __FILE__, __LINE__,
401               "unrecognized value for server.http-parseopts: "
402               "%s => %s (expect \"[enable|disable]\")", k->ptr, v->ptr);
403             rc = 0;
404         }
405         if (buffer_eq_slen(k, CONST_STR_LEN("url-normalize")))
406             opt = HTTP_PARSEOPT_URL_NORMALIZE;
407         else if (buffer_eq_slen(k, CONST_STR_LEN("url-normalize-unreserved")))
408             opt = HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED;
409         else if (buffer_eq_slen(k, CONST_STR_LEN("url-normalize-required")))
410             opt = HTTP_PARSEOPT_URL_NORMALIZE_REQUIRED;
411         else if (buffer_eq_slen(k, CONST_STR_LEN("url-ctrls-reject")))
412             opt = HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT;
413         else if (buffer_eq_slen(k, CONST_STR_LEN("url-path-backslash-trans")))
414             opt = HTTP_PARSEOPT_URL_NORMALIZE_PATH_BACKSLASH_TRANS;
415         else if (buffer_eq_slen(k, CONST_STR_LEN("url-path-2f-decode")))
416             opt = HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE;
417         else if (buffer_eq_slen(k, CONST_STR_LEN("url-path-2f-reject")))
418             opt = HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT;
419         else if (buffer_eq_slen(k, CONST_STR_LEN("url-path-dotseg-remove")))
420             opt = HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE;
421         else if (buffer_eq_slen(k, CONST_STR_LEN("url-path-dotseg-reject")))
422             opt = HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT;
423         else if (buffer_eq_slen(k, CONST_STR_LEN("url-query-20-plus")))
424             opt = HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS;
425         else if (buffer_eq_slen(k, CONST_STR_LEN("header-strict"))) {
426             srv->srvconf.http_header_strict = val;
427             continue;
428         }
429         else if (buffer_eq_slen(k, CONST_STR_LEN("host-strict"))) {
430             srv->srvconf.http_host_strict = val;
431             continue;
432         }
433         else if (buffer_eq_slen(k, CONST_STR_LEN("host-normalize"))) {
434             srv->srvconf.http_host_normalize = val;
435             continue;
436         }
437         else if (buffer_eq_slen(k, CONST_STR_LEN("method-get-body"))) {
438             srv->srvconf.http_method_get_body = val;
439             continue;
440         }
441         else {
442             log_error(srv->errh, __FILE__, __LINE__,
443               "unrecognized key for server.http-parseopts: %s", k->ptr);
444             rc = 0;
445             continue;
446         }
447         if (val)
448             opts |= opt;
449         else {
450             opts &= ~opt;
451             if (opt == HTTP_PARSEOPT_URL_NORMALIZE) {
452                 opts = 0;
453                 break;
454             }
455             if (opt == HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE) {
456                 decode_2f = 0;
457             }
458         }
459     }
460     if (opts != 0) {
461         opts |= HTTP_PARSEOPT_URL_NORMALIZE;
462         if ((opts & (HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE
463                     |HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT))
464                  == (HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE
465                     |HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT)) {
466             log_error(srv->errh, __FILE__, __LINE__,
467               "conflicting options in server.http-parseopts:"
468               "url-path-2f-decode, url-path-2f-reject");
469             rc = 0;
470         }
471         if ((opts & (HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE
472                     |HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT))
473                  == (HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE
474                     |HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT)) {
475             log_error(srv->errh, __FILE__, __LINE__,
476               "conflicting options in server.http-parseopts:"
477               "url-path-dotseg-remove, url-path-dotseg-reject");
478             rc = 0;
479         }
480         if (!(opts & (HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED
481                      |HTTP_PARSEOPT_URL_NORMALIZE_REQUIRED))) {
482             opts |= HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED;
483             if (decode_2f
484                 && !(opts & HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT))
485                 opts |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE;
486         }
487     }
488     srv->srvconf.http_url_normalize = opts;
489     return rc;
490 }
491 
492 static int config_insert_srvconf(server *srv) {
493     static const config_plugin_keys_t cpk[] = {
494       { CONST_STR_LEN("server.modules"),
495         T_CONFIG_ARRAY_VLIST,
496         T_CONFIG_SCOPE_SERVER }
497      ,{ CONST_STR_LEN("server.compat-module-load"),
498         T_CONFIG_BOOL,
499         T_CONFIG_SCOPE_SERVER }
500      ,{ CONST_STR_LEN("server.systemd-socket-activation"),
501         T_CONFIG_BOOL,
502         T_CONFIG_SCOPE_SERVER }
503      ,{ CONST_STR_LEN("server.port"),
504         T_CONFIG_SHORT,
505         T_CONFIG_SCOPE_SERVER }
506      ,{ CONST_STR_LEN("server.bind"),
507         T_CONFIG_STRING,
508         T_CONFIG_SCOPE_SERVER }
509      ,{ CONST_STR_LEN("server.network-backend"),
510         T_CONFIG_STRING,
511         T_CONFIG_SCOPE_SERVER }
512      ,{ CONST_STR_LEN("server.chroot"),
513         T_CONFIG_STRING,
514         T_CONFIG_SCOPE_SERVER }
515      ,{ CONST_STR_LEN("server.username"),
516         T_CONFIG_STRING,
517         T_CONFIG_SCOPE_SERVER }
518      ,{ CONST_STR_LEN("server.groupname"),
519         T_CONFIG_STRING,
520         T_CONFIG_SCOPE_SERVER }
521      ,{ CONST_STR_LEN("server.errorlog-placeholder-moved-to-config-insert"),
522         T_CONFIG_STRING,
523         T_CONFIG_SCOPE_SERVER }
524      ,{ CONST_STR_LEN("server.breakagelog-placeholder-moved-to-config-insert"),
525         T_CONFIG_STRING,
526         T_CONFIG_SCOPE_SERVER }
527      ,{ CONST_STR_LEN("server.errorlog-use-syslog"),
528         T_CONFIG_BOOL,
529         T_CONFIG_SCOPE_SERVER }
530      ,{ CONST_STR_LEN("server.syslog-facility"),
531         T_CONFIG_STRING,
532         T_CONFIG_SCOPE_SERVER }
533      ,{ CONST_STR_LEN("server.core-files"),
534         T_CONFIG_BOOL,
535         T_CONFIG_SCOPE_SERVER }
536      ,{ CONST_STR_LEN("server.event-handler"),
537         T_CONFIG_STRING,
538         T_CONFIG_SCOPE_SERVER }
539      ,{ CONST_STR_LEN("server.pid-file"),
540         T_CONFIG_STRING,
541         T_CONFIG_SCOPE_SERVER }
542      ,{ CONST_STR_LEN("server.max-worker"),
543         T_CONFIG_SHORT,
544         T_CONFIG_SCOPE_SERVER }
545      ,{ CONST_STR_LEN("server.max-fds"),
546         T_CONFIG_SHORT,
547         T_CONFIG_SCOPE_SERVER }
548      ,{ CONST_STR_LEN("server.max-connections"),
549         T_CONFIG_SHORT,
550         T_CONFIG_SCOPE_SERVER }
551      ,{ CONST_STR_LEN("server.max-request-field-size"),
552         T_CONFIG_INT,
553         T_CONFIG_SCOPE_SERVER }
554      ,{ CONST_STR_LEN("server.chunkqueue-chunk-sz"),
555         T_CONFIG_INT,
556         T_CONFIG_SCOPE_SERVER }
557      ,{ CONST_STR_LEN("server.upload-temp-file-size"),
558         T_CONFIG_INT,
559         T_CONFIG_SCOPE_SERVER }
560      ,{ CONST_STR_LEN("server.upload-dirs"),
561         T_CONFIG_ARRAY_VLIST,
562         T_CONFIG_SCOPE_SERVER }
563      ,{ CONST_STR_LEN("server.http-parseopts"),
564         T_CONFIG_ARRAY_KVSTRING,
565         T_CONFIG_SCOPE_SERVER }
566      ,{ CONST_STR_LEN("server.http-parseopt-header-strict"),
567         T_CONFIG_BOOL,
568         T_CONFIG_SCOPE_SERVER }
569      ,{ CONST_STR_LEN("server.http-parseopt-host-strict"),
570         T_CONFIG_BOOL,
571         T_CONFIG_SCOPE_SERVER }
572      ,{ CONST_STR_LEN("server.http-parseopt-host-normalize"),
573         T_CONFIG_BOOL,
574         T_CONFIG_SCOPE_SERVER }
575      ,{ CONST_STR_LEN("server.reject-expect-100-with-417"), /*(ignored)*/
576         T_CONFIG_BOOL,
577         T_CONFIG_SCOPE_SERVER }
578      ,{ CONST_STR_LEN("server.stat-cache-engine"),
579         T_CONFIG_STRING,
580         T_CONFIG_SCOPE_SERVER }
581      ,{ CONST_STR_LEN("mimetype.xattr-name"),
582         T_CONFIG_STRING,
583         T_CONFIG_SCOPE_SERVER }
584      ,{ CONST_STR_LEN("ssl.engine"),
585         T_CONFIG_BOOL,
586         T_CONFIG_SCOPE_CONNECTION }
587      ,{ CONST_STR_LEN("debug.log-request-header-on-error"),
588         T_CONFIG_BOOL,
589         T_CONFIG_SCOPE_SERVER }
590      ,{ CONST_STR_LEN("debug.log-state-handling"),
591         T_CONFIG_BOOL,
592         T_CONFIG_SCOPE_SERVER }
593      ,{ NULL, 0,
594         T_CONFIG_UNSET,
595         T_CONFIG_SCOPE_UNSET }
596     };
597 
598     int rc = 0;
599     plugin_data_base srvplug;
600     memset(&srvplug, 0, sizeof(srvplug));
601     plugin_data_base * const p = &srvplug;
602     if (!config_plugin_values_init(srv, p, cpk, "global"))
603         return HANDLER_ERROR;
604 
605     int ssl_enabled = 0; /*(directive checked here only to set default port)*/
606 
607     /* process and validate T_CONFIG_SCOPE_SERVER config directives */
608     if (p->cvlist[0].v.u2[1]) {
609         config_plugin_value_t *cpv = p->cvlist + p->cvlist[0].v.u2[0];
610         for (; -1 != cpv->k_id; ++cpv) {
611             switch (cpv->k_id) {
612               case 0: /* server.modules */
613                 array_copy_array(srv->srvconf.modules, cpv->v.a);
614                 break;
615               case 1: /* server.compat-module-load */
616                 srv->srvconf.compat_module_load = (unsigned short)cpv->v.u;
617                 break;
618               case 2: /* server.systemd-socket-activation */
619                 srv->srvconf.systemd_socket_activation=(unsigned short)cpv->v.u;
620                 break;
621               case 3: /* server.port */
622                 srv->srvconf.port = cpv->v.shrt;
623                 break;
624               case 4: /* server.bind */
625                 srv->srvconf.bindhost = cpv->v.b;
626                 break;
627               case 5: /* server.network-backend */
628                 srv->srvconf.network_backend = cpv->v.b;
629                 break;
630               case 6: /* server.chroot */
631                 srv->srvconf.changeroot = cpv->v.b;
632                 break;
633               case 7: /* server.username */
634                 srv->srvconf.username = cpv->v.b;
635                 break;
636               case 8: /* server.groupname */
637                 srv->srvconf.groupname = cpv->v.b;
638                 break;
639               case 9: /* server.errorlog */    /* moved to config_insert() */
640                 /*srv->srvconf.errorlog_file = cpv->v.b;*/
641                 break;
642               case 10:/* server.breakagelog */ /* moved to config_insert() */
643                 /*srv->srvconf.breakagelog_file = cpv->v.b;*/
644                 break;
645               case 11:/* server.errorlog-use-syslog */
646                 srv->srvconf.errorlog_use_syslog = (unsigned short)cpv->v.u;
647                 break;
648               case 12:/* server.syslog-facility */
649                 srv->srvconf.syslog_facility = cpv->v.b;
650                 break;
651               case 13:/* server.core-files */
652                 srv->srvconf.enable_cores = (unsigned short)cpv->v.u;
653                 break;
654               case 14:/* server.event-handler */
655                 srv->srvconf.event_handler = cpv->v.b->ptr;
656                 break;
657               case 15:/* server.pid-file */
658                 *(const buffer **)&srv->srvconf.pid_file = cpv->v.b;
659                 break;
660               case 16:/* server.max-worker */
661                 srv->srvconf.max_worker = (unsigned short)cpv->v.u;
662                 break;
663               case 17:/* server.max-fds */
664                 srv->srvconf.max_fds = (unsigned short)cpv->v.u;
665                 break;
666               case 18:/* server.max-connections */
667                 srv->srvconf.max_conns = (unsigned short)cpv->v.u;
668                 break;
669               case 19:/* server.max-request-field-size */
670                 srv->srvconf.max_request_field_size = cpv->v.u;
671                 break;
672               case 20:/* server.chunkqueue-chunk-sz */
673                 chunkqueue_set_chunk_size(cpv->v.u);
674                 break;
675               case 21:/* server.upload-temp-file-size */
676                 srv->srvconf.upload_temp_file_size = cpv->v.u;
677                 break;
678               case 22:/* server.upload-dirs */
679                 array_copy_array(srv->srvconf.upload_tempdirs, cpv->v.a);
680                 break;
681               case 23:/* server.http-parseopts */
682                 if (!config_http_parseopts(srv, cpv->v.a))
683                     rc = HANDLER_ERROR;
684                 break;
685               case 24:/* server.http-parseopt-header-strict */
686                 srv->srvconf.http_header_strict = (0 != cpv->v.u);
687                 break;
688               case 25:/* server.http-parseopt-host-strict */
689                 srv->srvconf.http_host_strict = (0 != cpv->v.u);
690                 break;
691               case 26:/* server.http-parseopt-host-normalize */
692                 srv->srvconf.http_host_normalize = (0 != cpv->v.u);
693                 break;
694               case 27:/* server.reject-expect-100-with-417 *//*(ignored)*/
695                 break;
696               case 28:/* server.stat-cache-engine */
697                 if (0 != stat_cache_choose_engine(cpv->v.b, srv->errh))
698                     rc = HANDLER_ERROR;
699                 break;
700               case 29:/* mimetype.xattr-name */
701                 stat_cache_xattrname(cpv->v.b->ptr);
702                 break;
703               case 30:/* ssl.engine */
704                 ssl_enabled = (0 != cpv->v.u);
705                #ifndef USE_OPENSSL_CRYPTO
706                 if (ssl_enabled) {
707                     log_error(srv->errh, __FILE__, __LINE__,
708                       "ssl support is missing; "
709                       "recompile with e.g. --with-openssl");
710                     rc = HANDLER_ERROR;
711                     break;
712                 }
713                #endif
714                 break;
715               case 31:/* debug.log-request-header-on-error */
716                 srv->srvconf.log_request_header_on_error = (0 != cpv->v.u);
717                 break;
718               case 32:/* debug.log-state-handling */
719                 srv->srvconf.log_state_handling = (0 != cpv->v.u);
720                 break;
721               default:/* should not happen */
722                 break;
723             }
724         }
725     }
726 
727     if (0 == srv->srvconf.port)
728         srv->srvconf.port = ssl_enabled ? 443 : 80;
729 
730     if (srv->srvconf.compat_module_load)
731         config_compat_module_load(srv);
732 
733     if (srv->srvconf.http_url_normalize && !config_burl_normalize_cond(srv))
734         rc = HANDLER_ERROR;
735 
736     free(srvplug.cvlist);
737     return rc;
738 }
739 
740 static int config_insert(server *srv) {
741     static const config_plugin_keys_t cpk[] = {
742       { CONST_STR_LEN("server.document-root"),
743         T_CONFIG_STRING,
744         T_CONFIG_SCOPE_CONNECTION }
745      ,{ CONST_STR_LEN("server.name"),
746         T_CONFIG_STRING,
747         T_CONFIG_SCOPE_CONNECTION }
748      ,{ CONST_STR_LEN("server.tag"),
749         T_CONFIG_STRING,
750         T_CONFIG_SCOPE_CONNECTION }
751      ,{ CONST_STR_LEN("server.max-request-size"),
752         T_CONFIG_INT,
753         T_CONFIG_SCOPE_CONNECTION }
754      ,{ CONST_STR_LEN("server.max-keep-alive-requests"),
755         T_CONFIG_SHORT,
756         T_CONFIG_SCOPE_CONNECTION }
757      ,{ CONST_STR_LEN("server.max-keep-alive-idle"),
758         T_CONFIG_SHORT,
759         T_CONFIG_SCOPE_CONNECTION }
760      ,{ CONST_STR_LEN("server.max-read-idle"),
761         T_CONFIG_SHORT,
762         T_CONFIG_SCOPE_CONNECTION }
763      ,{ CONST_STR_LEN("server.max-write-idle"),
764         T_CONFIG_SHORT,
765         T_CONFIG_SCOPE_CONNECTION }
766      ,{ CONST_STR_LEN("server.errorfile-prefix"),
767         T_CONFIG_STRING,
768         T_CONFIG_SCOPE_CONNECTION }
769      ,{ CONST_STR_LEN("server.error-handler"),
770         T_CONFIG_STRING,
771         T_CONFIG_SCOPE_CONNECTION }
772      ,{ CONST_STR_LEN("server.error-handler-404"),
773         T_CONFIG_STRING,
774         T_CONFIG_SCOPE_CONNECTION }
775      ,{ CONST_STR_LEN("server.error-intercept"),
776         T_CONFIG_BOOL,
777         T_CONFIG_SCOPE_CONNECTION }
778      ,{ CONST_STR_LEN("server.force-lowercase-filenames"),
779         T_CONFIG_BOOL,
780         T_CONFIG_SCOPE_CONNECTION }
781      ,{ CONST_STR_LEN("server.follow-symlink"),
782         T_CONFIG_BOOL,
783         T_CONFIG_SCOPE_CONNECTION }
784      ,{ CONST_STR_LEN("server.protocol-http11"),
785         T_CONFIG_BOOL,
786         T_CONFIG_SCOPE_CONNECTION }
787      ,{ CONST_STR_LEN("server.range-requests"),
788         T_CONFIG_BOOL,
789         T_CONFIG_SCOPE_CONNECTION }
790      ,{ CONST_STR_LEN("server.stream-request-body"),
791         T_CONFIG_SHORT,
792         T_CONFIG_SCOPE_CONNECTION }
793      ,{ CONST_STR_LEN("server.stream-response-body"),
794         T_CONFIG_SHORT,
795         T_CONFIG_SCOPE_CONNECTION }
796      ,{ CONST_STR_LEN("server.kbytes-per-second"),
797         T_CONFIG_SHORT,
798         T_CONFIG_SCOPE_CONNECTION }
799      ,{ CONST_STR_LEN("connection.kbytes-per-second"),
800         T_CONFIG_SHORT,
801         T_CONFIG_SCOPE_CONNECTION }
802      ,{ CONST_STR_LEN("mimetype.assign"),
803         T_CONFIG_ARRAY_KVSTRING,
804         T_CONFIG_SCOPE_CONNECTION }
805      ,{ CONST_STR_LEN("mimetype.use-xattr"),
806         T_CONFIG_BOOL,
807         T_CONFIG_SCOPE_CONNECTION }
808      ,{ CONST_STR_LEN("etag.use-inode"),
809         T_CONFIG_BOOL,
810         T_CONFIG_SCOPE_CONNECTION }
811      ,{ CONST_STR_LEN("etag.use-mtime"),
812         T_CONFIG_BOOL,
813         T_CONFIG_SCOPE_CONNECTION }
814      ,{ CONST_STR_LEN("etag.use-size"),
815         T_CONFIG_BOOL,
816         T_CONFIG_SCOPE_CONNECTION }
817      ,{ CONST_STR_LEN("debug.log-condition-handling"),
818         T_CONFIG_BOOL,
819         T_CONFIG_SCOPE_CONNECTION }
820      ,{ CONST_STR_LEN("debug.log-file-not-found"),
821         T_CONFIG_BOOL,
822         T_CONFIG_SCOPE_CONNECTION }
823      ,{ CONST_STR_LEN("debug.log-request-handling"),
824         T_CONFIG_BOOL,
825         T_CONFIG_SCOPE_CONNECTION }
826      ,{ CONST_STR_LEN("debug.log-request-header"),
827         T_CONFIG_BOOL,
828         T_CONFIG_SCOPE_CONNECTION }
829      ,{ CONST_STR_LEN("debug.log-response-header"),
830         T_CONFIG_BOOL,
831         T_CONFIG_SCOPE_CONNECTION }
832      ,{ CONST_STR_LEN("debug.log-timeouts"),
833         T_CONFIG_BOOL,
834         T_CONFIG_SCOPE_CONNECTION }
835      ,{ CONST_STR_LEN("server.errorlog"),
836         T_CONFIG_STRING,
837         T_CONFIG_SCOPE_CONNECTION }
838      ,{ CONST_STR_LEN("server.breakagelog"),
839         T_CONFIG_STRING,
840         T_CONFIG_SCOPE_CONNECTION }
841      ,{ NULL, 0,
842         T_CONFIG_UNSET,
843         T_CONFIG_SCOPE_UNSET }
844     };
845 
846     int rc = 0;
847     config_data_base * const p = calloc(1, sizeof(config_data_base));
848     force_assert(p);
849     srv->config_data_base = p;
850 
851     if (!config_plugin_values_init(srv, p, cpk, "base"))
852         return HANDLER_ERROR;
853 
854     /* process and validate T_CONFIG_SCOPE_CONNECTION config directives
855      * (init i to 0 if global context; to 1 to skip empty global context) */
856     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
857         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
858         for (; -1 != cpv->k_id; ++cpv) {
859             switch (cpv->k_id) {
860               case 0: /* server.document-root */
861               case 1: /* server.name */
862                 break;
863               case 2: /* server.tag */
864                 if (!buffer_string_is_empty(cpv->v.b)) {
865                     buffer *b;
866                     *(const buffer **)&b = cpv->v.b;
867                     for (char *t=strchr(b->ptr,'\n'); t; t=strchr(t+2,'\n')) {
868                         /* not expecting admin to define multi-line server.tag,
869                          * but ensure server_tag has proper header continuation,
870                          * if needed */
871                         if (t[1] == ' ' || t[1] == '\t') continue;
872                         off_t off = t - b->ptr;
873                         size_t len = buffer_string_length(b);
874                         buffer_string_prepare_append(b, 1);
875                         t = b->ptr+off;
876                         memmove(t+2, t+1, len - off - 1);
877                         t[1] = ' ';
878                         buffer_commit(b, 1);
879                     }
880                 }
881                 break;
882               case 3: /* server.max-request-size */
883               case 4: /* server.max-keep-alive-requests */
884               case 5: /* server.max-keep-alive-idle */
885               case 6: /* server.max-read-idle */
886               case 7: /* server.max-write-idle */
887               case 8: /* server.errorfile-prefix */
888               case 9: /* server.error-handler */
889               case 10:/* server.error-handler-404 */
890               case 11:/* server.error-intercept */
891                 break;
892               case 12:/* server.force-lowercase-filenames */
893                #ifndef HAVE_LSTAT
894                 if (0 == cpv->v.u)
895                     log_error(srv->errh, __FILE__, __LINE__,
896                       "Your system lacks lstat(). "
897                       "We can not differ symlinks from files. "
898                       "Please remove server.follow-symlinks from your config.");
899                #endif
900                 break;
901               case 13:/* server.follow-symlink */
902               case 14:/* server.protocol-http11 */
903               case 15:/* server.range-requests */
904                 break;
905               case 16:/* server.stream-request-body */
906                 if (cpv->v.shrt & FDEVENT_STREAM_REQUEST_BUFMIN)
907                     cpv->v.shrt |=FDEVENT_STREAM_REQUEST;
908                 break;
909               case 17:/* server.stream-response-body */
910                 if (cpv->v.shrt & FDEVENT_STREAM_RESPONSE_BUFMIN)
911                     cpv->v.shrt |=FDEVENT_STREAM_RESPONSE;
912                 break;
913               case 18:{/*server.kbytes-per-second */
914                 off_t * const cnt = malloc(2*sizeof(off_t));
915                 force_assert(cnt);
916                 cnt[0] = 0;
917                 cnt[1] = (off_t)cpv->v.shrt << 10;
918                 cpv->v.v = cnt;
919                 cpv->vtype = T_CONFIG_LOCAL;
920                 break;
921               }
922               case 19:/* connection.kbytes-per-second */
923               case 20:/* mimetype.assign */
924               case 21:/* mimetype.use-xattr */
925               case 22:/* etag.use-inode */
926               case 23:/* etag.use-mtime */
927               case 24:/* etag.use-size */
928               case 25:/* debug.log-condition-handling */
929               case 26:/* debug.log-file-not-found */
930               case 27:/* debug.log-request-handling */
931               case 28:/* debug.log-request-header */
932               case 29:/* debug.log-response-header */
933               case 30:/* debug.log-timeouts */
934               case 31:/* server.errorlog */   /*(idx in server.c must match)*/
935               case 32:/* server.breakagelog *//*(idx in server.c must match)*/
936                 break;
937               default:/* should not happen */
938                 break;
939             }
940         }
941     }
942 
943     p->defaults.errh = srv->errh;
944     p->defaults.max_keep_alive_requests = 100;
945     p->defaults.max_keep_alive_idle = 5;
946     p->defaults.max_read_idle = 60;
947     p->defaults.max_write_idle = 360;
948     p->defaults.follow_symlink = 1;
949     p->defaults.allow_http11 = 1;
950     p->defaults.etag_flags = ETAG_USE_INODE | ETAG_USE_MTIME | ETAG_USE_SIZE;
951     p->defaults.range_requests = 1;
952     /* use 2 to detect later if value is set by user config in global section */
953     p->defaults.force_lowercase_filenames = 2;
954 
955     /*(global, but store in r->conf.http_parseopts)*/
956     p->defaults.http_parseopts =
957         (srv->srvconf.http_header_strict   ?  HTTP_PARSEOPT_HEADER_STRICT   :0)
958       | (srv->srvconf.http_host_strict     ? (HTTP_PARSEOPT_HOST_STRICT
959                                              |HTTP_PARSEOPT_HOST_NORMALIZE) :0)
960       | (srv->srvconf.http_host_normalize  ?  HTTP_PARSEOPT_HOST_NORMALIZE  :0)
961       | (srv->srvconf.http_method_get_body ?  HTTP_PARSEOPT_METHOD_GET_BODY :0);
962     p->defaults.http_parseopts |= srv->srvconf.http_url_normalize;
963     p->defaults.mimetypes = &srv->srvconf.empty_array; /*(must not be NULL)*/
964 
965     /* initialize p->defaults from global config context */
966     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
967         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
968         if (-1 != cpv->k_id)
969             config_merge_config(&p->defaults, cpv);
970     }
971 
972     /* (after processing config defaults) */
973     p->defaults.max_request_field_size = srv->srvconf.max_request_field_size;
974     p->defaults.log_state_handling = srv->srvconf.log_state_handling;
975     p->defaults.log_request_header_on_error =
976       srv->srvconf.log_request_header_on_error;
977     if (p->defaults.log_request_handling || p->defaults.log_request_header)
978         p->defaults.log_request_header_on_error = 1;
979 
980     return rc;
981 }
982 
983 int config_finalize(server *srv, const buffer *default_server_tag) {
984     /* (call after plugins_call_set_defaults()) */
985 
986     config_data_base * const p = srv->config_data_base;
987 
988     /* settings might be enabled during plugins_call_set_defaults() */
989     p->defaults.high_precision_timestamps =
990       srv->srvconf.high_precision_timestamps;
991 
992     /* configure default server_tag if not set
993      * (if configured to blank, unset server_tag)*/
994     if (buffer_is_empty(p->defaults.server_tag))
995         p->defaults.server_tag = default_server_tag;
996     else if (buffer_string_is_empty(p->defaults.server_tag))
997         p->defaults.server_tag = NULL;
998 
999     /* dump unused config keys */
1000     for (uint32_t i = 0; i < srv->config_context->used; ++i) {
1001         array *config = ((data_config *)srv->config_context->data[i])->value;
1002         for (uint32_t j = 0; config && j < config->used; ++j) {
1003             const buffer * const k = &config->data[j]->key;
1004 
1005             /* all var.* is known as user defined variable */
1006             if (strncmp(k->ptr, "var.", sizeof("var.") - 1) == 0)
1007                 continue;
1008 
1009             if (!array_get_element_klen(srv->srvconf.config_touched,
1010                                         CONST_BUF_LEN(k)))
1011                 log_error(srv->errh, __FILE__, __LINE__,
1012                   "WARNING: unknown config-key: %s (ignored)", k->ptr);
1013         }
1014     }
1015 
1016     array_free(srv->srvconf.config_touched);
1017     srv->srvconf.config_touched = NULL;
1018 
1019     if (srv->srvconf.config_unsupported || srv->srvconf.config_deprecated) {
1020         if (srv->srvconf.config_unsupported)
1021             log_error(srv->errh, __FILE__, __LINE__,
1022               "Configuration contains unsupported keys. Going down.");
1023         if (srv->srvconf.config_deprecated)
1024             log_error(srv->errh, __FILE__, __LINE__,
1025               "Configuration contains deprecated keys. Going down.");
1026         return 0;
1027     }
1028 
1029     return 1;
1030 }
1031 
1032 void config_print(server *srv) {
1033     data_unset *dc = srv->config_context->data[0];
1034     dc->fn->print(dc, 0);
1035 }
1036 
1037 void config_free(server *srv) {
1038     config_free_config(srv->config_data_base);
1039 
1040     array_free(srv->config_context);
1041     array_free(srv->srvconf.config_touched);
1042     array_free(srv->srvconf.modules);
1043     buffer_free(srv->srvconf.modules_dir);
1044     array_free(srv->srvconf.upload_tempdirs);
1045 }
1046 
1047 void config_init(server *srv) {
1048     srv->config_context = array_init(16);
1049     srv->srvconf.config_touched = array_init(128);
1050 
1051     srv->srvconf.port = 0;
1052     srv->srvconf.dont_daemonize = 0;
1053     srv->srvconf.preflight_check = 0;
1054     srv->srvconf.compat_module_load = 1;
1055     srv->srvconf.systemd_socket_activation = 0;
1056 
1057     srv->srvconf.high_precision_timestamps = 0;
1058     srv->srvconf.max_request_field_size = 8192;
1059 
1060     srv->srvconf.http_header_strict  = 1;
1061     srv->srvconf.http_host_strict    = 1; /*(implies http_host_normalize)*/
1062     srv->srvconf.http_host_normalize = 0;
1063     srv->srvconf.http_url_normalize =
1064         HTTP_PARSEOPT_URL_NORMALIZE
1065       | HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED
1066       | HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT
1067       | HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE
1068       | HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE;
1069 
1070     srv->srvconf.modules = array_init(16);
1071     srv->srvconf.modules_dir = buffer_init_string(LIBRARY_DIR);
1072     srv->srvconf.upload_tempdirs = array_init(2);
1073 }
1074 
1075 /**
1076  * open the errorlog
1077  *
1078  * we have 4 possibilities:
1079  * - stderr (default)
1080  * - syslog
1081  * - logfile
1082  * - pipe
1083  *
1084  */
1085 
1086 static void config_log_error_open_syslog(server *srv, log_error_st *errh, const buffer *syslog_facility) {
1087   #ifdef HAVE_SYSLOG_H
1088     errh->errorlog_mode = ERRORLOG_SYSLOG;
1089     /* perhaps someone wants to use syslog() */
1090     int facility = -1;
1091     if (!buffer_string_is_empty(syslog_facility)) {
1092         static const struct facility_name_st {
1093           const char *name;
1094           int val;
1095         } facility_names[] = {
1096             { "auth",     LOG_AUTH }
1097           #ifdef LOG_AUTHPRIV
1098            ,{ "authpriv", LOG_AUTHPRIV }
1099           #endif
1100           #ifdef LOG_CRON
1101            ,{ "cron",     LOG_CRON }
1102           #endif
1103            ,{ "daemon",   LOG_DAEMON }
1104           #ifdef LOG_FTP
1105            ,{ "ftp",      LOG_FTP }
1106           #endif
1107           #ifdef LOG_KERN
1108            ,{ "kern",     LOG_KERN }
1109           #endif
1110           #ifdef LOG_LPR
1111            ,{ "lpr",      LOG_LPR }
1112           #endif
1113           #ifdef LOG_MAIL
1114            ,{ "mail",     LOG_MAIL }
1115           #endif
1116           #ifdef LOG_NEWS
1117            ,{ "news",     LOG_NEWS }
1118           #endif
1119            ,{ "security", LOG_AUTH }           /* DEPRECATED */
1120           #ifdef LOG_SYSLOG
1121            ,{ "syslog",   LOG_SYSLOG }
1122           #endif
1123           #ifdef LOG_USER
1124            ,{ "user",     LOG_USER }
1125           #endif
1126           #ifdef LOG_UUCP
1127            ,{ "uucp",     LOG_UUCP }
1128           #endif
1129            ,{ "local0",   LOG_LOCAL0 }
1130            ,{ "local1",   LOG_LOCAL1 }
1131            ,{ "local2",   LOG_LOCAL2 }
1132            ,{ "local3",   LOG_LOCAL3 }
1133            ,{ "local4",   LOG_LOCAL4 }
1134            ,{ "local5",   LOG_LOCAL5 }
1135            ,{ "local6",   LOG_LOCAL6 }
1136            ,{ "local7",   LOG_LOCAL7 }
1137         };
1138         for (unsigned int i = 0; i < sizeof(facility_names)/sizeof(facility_names[0]); ++i) {
1139             const struct facility_name_st *f = facility_names+i;
1140             if (0 == strcmp(syslog_facility->ptr, f->name)) {
1141                 facility = f->val;
1142                 break;
1143             }
1144         }
1145         if (-1 == facility) {
1146             log_error(srv->errh, __FILE__, __LINE__,
1147               "unrecognized server.syslog-facility: \"%s\"; "
1148               "defaulting to \"daemon\" facility",
1149               syslog_facility->ptr);
1150         }
1151     }
1152     openlog("lighttpd", LOG_CONS|LOG_PID, -1==facility ? LOG_DAEMON : facility);
1153   #endif
1154 }
1155 
1156 static int config_log_error_open_fn(server *srv, log_error_st *errh, const char *fn) {
1157     int fd = fdevent_open_logger(fn);
1158     if (-1 == fd) {
1159         log_perror(srv->errh, __FILE__, __LINE__,
1160           "opening errorlog '%s' failed", fn);
1161         return -1;
1162     }
1163     errh->errorlog_fd = fd;
1164     errh->errorlog_mode = fn[0] == '|' ? ERRORLOG_PIPE : ERRORLOG_FILE;
1165     errh->fn = fn;
1166 
1167     return 0;
1168 }
1169 
1170 int config_log_error_open(server *srv) {
1171     /* logs are opened after preflight check (srv->srvconf.preflight_check)
1172      * and after dropping privileges instead of being opened during config
1173      * processing */
1174 
1175     /* Note: implementation does not de-dup repeated files or pipe commands */
1176 
1177     config_data_base * const p = srv->config_data_base;
1178     log_error_st *serrh = NULL;
1179 
1180     /* future: might be slightly faster to have allocated array of open files
1181      * rather than walking config, but only might matter with many directives */
1182     /* (init i to 0 if global context; to 1 to skip empty global context) */
1183     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
1184         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
1185         for (; -1 != cpv->k_id; ++cpv) {
1186             const char *fn = NULL;
1187             log_error_st *errh = NULL;
1188             switch (cpv->k_id) {
1189               /* NB: these indexes are repeated below switch() block
1190                *     and all must stay in sync with configfile.c */
1191               case 31:/* server.errorlog */
1192                 if (0 == i) {
1193                     if (srv->srvconf.errorlog_use_syslog) continue;
1194                     errh = srv->errh;
1195                 }
1196                 __attribute_fallthrough__
1197               case 32:/* server.breakagelog */
1198                 if (!buffer_string_is_empty(cpv->v.b)) fn = cpv->v.b->ptr;
1199                 break;
1200               default:
1201                 break;
1202             }
1203 
1204             if (NULL == fn) continue;
1205 
1206             if (NULL == errh) errh = log_error_st_init();
1207             cpv->v.v = errh;
1208             cpv->vtype = T_CONFIG_LOCAL;
1209 
1210             if (0 != config_log_error_open_fn(srv, errh, fn)) return -1;
1211 
1212             if (0 == i && errh != srv->errh) /*(top-level server.breakagelog)*/
1213                 serrh = errh;
1214         }
1215     }
1216 
1217     if (srv->srvconf.errorlog_use_syslog) /*(restricted to global scope)*/
1218         config_log_error_open_syslog(srv, srv->errh,
1219                                      srv->srvconf.syslog_facility);
1220     else if (srv->errh->errorlog_mode == ERRORLOG_FD
1221              && !srv->srvconf.dont_daemonize)
1222         srv->errh->errorlog_fd = -1;
1223         /* We can only log to stderr in dont-daemonize mode;
1224          * if we do daemonize and no errorlog file is specified,
1225          * we log into /dev/null
1226          */
1227 
1228     /* Note: serrh should not be stored in p->defaults.serrh
1229      * If left as NULL, scripts (e.g. mod_cgi and mod_ssi exec) will inherit
1230      * the current STDERR_FILENO, which already is the top-level breakagelog. */
1231     /*p->defaults.serrh = serrh;*/
1232 
1233     int errfd;
1234     if (NULL != serrh) {
1235         if (srv->errh->errorlog_mode == ERRORLOG_FD) {
1236             srv->errh->errorlog_fd = dup(STDERR_FILENO);
1237             fdevent_setfd_cloexec(srv->errh->errorlog_fd);
1238         }
1239 
1240         errfd = serrh->errorlog_fd;
1241         if (*serrh->fn == '|') fdevent_breakagelog_logger_pipe(errfd);
1242     }
1243     else if (!srv->srvconf.dont_daemonize) {
1244         /* move STDERR_FILENO to /dev/null */
1245         if (-1 == (errfd = fdevent_open_devnull())) {
1246             log_perror(srv->errh,__FILE__,__LINE__,"opening /dev/null failed");
1247             return -1;
1248         }
1249     }
1250     else {
1251         /*(leave STDERR_FILENO as-is)*/
1252         errfd = -1;
1253     }
1254 
1255     if (0 != fdevent_set_stdin_stdout_stderr(-1, -1, errfd)) {
1256         log_perror(srv->errh, __FILE__, __LINE__, "setting stderr failed");
1257       #ifdef FD_CLOEXEC
1258         if (-1 != errfd && NULL == serrh) close(errfd);
1259       #endif
1260         return -1;
1261     }
1262   #ifdef FD_CLOEXEC
1263     if (-1 != errfd && NULL == serrh) close(errfd);
1264   #endif
1265 
1266     if (NULL != serrh) {
1267         close(errfd); /* serrh->errorlog_fd */
1268         serrh->errorlog_fd = STDERR_FILENO;
1269     }
1270 
1271     return 0;
1272 }
1273 
1274 /**
1275  * cycle the errorlog
1276  *
1277  */
1278 
1279 void config_log_error_cycle(server *srv) {
1280     /* All logs are rotated in parent and children workers so that all have
1281      * valid filehandles.  The parent might reap a child and respawn, so the
1282      * parent needs valid handles for more than top-level srv->errh */
1283 
1284     /*(no need to flush error log before cycling; error logs are not buffered)*/
1285 
1286     config_data_base * const p = srv->config_data_base;
1287 
1288     /* future: might be slightly faster to have allocated array of open files
1289      * rather than walking config, but only might matter with many directives */
1290     /* (init i to 0 if global context; to 1 to skip empty global context) */
1291     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
1292         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
1293         for (; -1 != cpv->k_id; ++cpv) {
1294             if (cpv->vtype != T_CONFIG_LOCAL || NULL == cpv->v.v) continue;
1295             log_error_st *errh;
1296             switch (cpv->k_id) {
1297               case 31:/* server.errorlog */
1298               case 32:/* server.breakagelog */
1299                 errh = cpv->v.v; /* cycle only if the error log is a file */
1300                 if (errh->errorlog_mode != ERRORLOG_FILE) continue;
1301                 if (-1 == fdevent_cycle_logger(errh->fn, &errh->errorlog_fd)) {
1302                     /* write to top-level error log
1303                      * (the prior log if srv->errh is the one being cycled) */
1304                     log_perror(srv->errh, __FILE__, __LINE__,
1305                       "cycling errorlog '%s' failed", errh->fn);
1306                 }
1307                 else if (0 == i && errh != srv->errh) { /*(server.breakagelog)*/
1308                     int fd = errh->errorlog_fd;
1309                     if (STDERR_FILENO != dup2(fd, STDERR_FILENO)) {
1310                         errh->errorlog_fd = STDERR_FILENO;
1311                         close(fd);
1312                     }
1313                     else {
1314                         log_perror(srv->errh, __FILE__, __LINE__,
1315                           "dup2() %s to STDERR failed", errh->fn);
1316                     }
1317                 }
1318                 break;
1319               default:
1320                 break;
1321             }
1322         }
1323     }
1324 }
1325 
1326 void config_log_error_close(server *srv) {
1327     config_data_base * const p = srv->config_data_base;
1328     if (NULL == p) return;
1329 
1330     /* future: might be slightly faster to have allocated array of open files
1331      * rather than walking config, but only might matter with many directives */
1332     /* (init i to 0 if global context; to 1 to skip empty global context) */
1333     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
1334         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
1335         for (; -1 != cpv->k_id; ++cpv) {
1336             if (cpv->vtype != T_CONFIG_LOCAL || NULL == cpv->v.v) continue;
1337             log_error_st *errh = NULL;
1338             switch (cpv->k_id) {
1339               /* NB: these indexes are repeated below switch() block
1340                *     and all must stay in sync with configfile.c */
1341               case 31:/* server.errorlog */
1342                 if (0 == i) continue; /*(srv->errh is free'd later)*/
1343                 __attribute_fallthrough__
1344               case 32:/* server.breakagelog */
1345                 errh = cpv->v.v; /* cycle only if the error log is a file */
1346                 break;
1347               default:
1348                 break;
1349             }
1350 
1351             if (NULL == errh) continue;
1352 
1353             switch(errh->errorlog_mode) {
1354               case ERRORLOG_PIPE:
1355               case ERRORLOG_FILE:
1356               case ERRORLOG_FD:
1357                 if (-1 != errh->errorlog_fd) {
1358                     /* don't close STDERR */
1359                     /* fdevent_close_logger_pipes() closes ERRORLOG_PIPE */
1360                     if (STDERR_FILENO != errh->errorlog_fd
1361                         && ERRORLOG_PIPE != errh->errorlog_mode) {
1362                         close(errh->errorlog_fd);
1363                     }
1364                     errh->errorlog_fd = -1;
1365                 }
1366                 break;
1367               case ERRORLOG_SYSLOG: /*(restricted to global scope)*/
1368                #ifdef HAVE_SYSLOG_H
1369                 closelog();
1370                #endif
1371                 break;
1372             }
1373 
1374             log_error_st_free(errh);
1375         }
1376     }
1377 
1378     fdevent_close_logger_pipes();
1379 
1380     if (srv->errh->errorlog_mode == ERRORLOG_SYSLOG) {
1381         srv->errh->errorlog_mode = ERRORLOG_FD;
1382         srv->errh->errorlog_fd = STDERR_FILENO;
1383       #ifdef HAVE_SYSLOG_H
1384         closelog();
1385       #endif
1386     }
1387 }
1388 
1389 
1390 
1391 typedef struct {
1392 	const char *source;
1393 	const char *input;
1394 	size_t offset;
1395 	size_t size;
1396 
1397 	int line_pos;
1398 	int line;
1399 
1400 	int in_key;
1401 	int in_brace;
1402 	int in_cond;
1403 	int simulate_eol;
1404 } tokenizer_t;
1405 
1406 static int config_skip_newline(tokenizer_t *t) {
1407 	int skipped = 1;
1408 	force_assert(t->input[t->offset] == '\r' || t->input[t->offset] == '\n');
1409 	if (t->input[t->offset] == '\r' && t->input[t->offset + 1] == '\n') {
1410 		skipped ++;
1411 		t->offset ++;
1412 	}
1413 	t->offset ++;
1414 	return skipped;
1415 }
1416 
1417 static int config_skip_comment(tokenizer_t *t) {
1418 	int i;
1419 	force_assert(t->input[t->offset] == '#');
1420 	for (i = 1; t->input[t->offset + i] &&
1421 	     (t->input[t->offset + i] != '\n' && t->input[t->offset + i] != '\r');
1422 	     i++);
1423 	t->offset += i;
1424 	return i;
1425 }
1426 
1427 __attribute_cold__
1428 static int config_tokenizer_err(server *srv, const char *file, unsigned int line, tokenizer_t *t, const char *msg) {
1429     log_error(srv->errh, file, line, "source: %s line: %d pos: %d %s",
1430               t->source, t->line, t->line_pos, msg);
1431     return -1;
1432 }
1433 
1434 static int config_tokenizer(server *srv, tokenizer_t *t, int *token_id, buffer *token) {
1435 	int tid = 0;
1436 	size_t i;
1437 
1438 	if (t->simulate_eol) {
1439 		t->simulate_eol = 0;
1440 		t->in_key = 1;
1441 		tid = TK_EOL;
1442 		buffer_copy_string_len(token, CONST_STR_LEN("(EOL)"));
1443 	}
1444 
1445 	while (tid == 0 && t->offset < t->size && t->input[t->offset]) {
1446 		char c = t->input[t->offset];
1447 		const char *start = NULL;
1448 
1449 		switch (c) {
1450 		case '=':
1451 			if (t->in_brace) {
1452 				if (t->input[t->offset + 1] == '>') {
1453 					t->offset += 2;
1454 
1455 					buffer_copy_string_len(token, CONST_STR_LEN("=>"));
1456 
1457 					tid = TK_ARRAY_ASSIGN;
1458 				} else {
1459 					return config_tokenizer_err(srv, __FILE__, __LINE__, t,
1460 							"use => for assignments in arrays");
1461 				}
1462 			} else if (t->in_cond) {
1463 				if (t->input[t->offset + 1] == '=') {
1464 					t->offset += 2;
1465 
1466 					buffer_copy_string_len(token, CONST_STR_LEN("=="));
1467 
1468 					tid = TK_EQ;
1469 				} else if (t->input[t->offset + 1] == '~') {
1470 					t->offset += 2;
1471 
1472 					buffer_copy_string_len(token, CONST_STR_LEN("=~"));
1473 
1474 					tid = TK_MATCH;
1475 				} else {
1476 					return config_tokenizer_err(srv, __FILE__, __LINE__, t,
1477 							"only =~ and == are allowed in the condition");
1478 				}
1479 				t->in_key = 1;
1480 				t->in_cond = 0;
1481 			} else if (t->in_key) {
1482 				tid = TK_ASSIGN;
1483 
1484 				buffer_copy_string_len(token, t->input + t->offset, 1);
1485 
1486 				t->offset++;
1487 				t->line_pos++;
1488 			} else {
1489 				return config_tokenizer_err(srv, __FILE__, __LINE__, t,
1490 						"unexpected equal-sign: =");
1491 			}
1492 
1493 			break;
1494 		case '!':
1495 			if (t->in_cond) {
1496 				if (t->input[t->offset + 1] == '=') {
1497 					t->offset += 2;
1498 
1499 					buffer_copy_string_len(token, CONST_STR_LEN("!="));
1500 
1501 					tid = TK_NE;
1502 				} else if (t->input[t->offset + 1] == '~') {
1503 					t->offset += 2;
1504 
1505 					buffer_copy_string_len(token, CONST_STR_LEN("!~"));
1506 
1507 					tid = TK_NOMATCH;
1508 				} else {
1509 					return config_tokenizer_err(srv, __FILE__, __LINE__, t,
1510 							"only !~ and != are allowed in the condition");
1511 				}
1512 				t->in_key = 1;
1513 				t->in_cond = 0;
1514 			} else {
1515 				return config_tokenizer_err(srv, __FILE__, __LINE__, t,
1516 						"unexpected exclamation-marks: !");
1517 			}
1518 
1519 			break;
1520 		case '\t':
1521 		case ' ':
1522 			t->offset++;
1523 			t->line_pos++;
1524 			break;
1525 		case '\n':
1526 		case '\r':
1527 			if (t->in_brace == 0) {
1528 				int done = 0;
1529 				while (!done && t->offset < t->size) {
1530 					switch (t->input[t->offset]) {
1531 					case '\r':
1532 					case '\n':
1533 						config_skip_newline(t);
1534 						t->line_pos = 1;
1535 						t->line++;
1536 						break;
1537 
1538 					case '#':
1539 						t->line_pos += config_skip_comment(t);
1540 						break;
1541 
1542 					case '\t':
1543 					case ' ':
1544 						t->offset++;
1545 						t->line_pos++;
1546 						break;
1547 
1548 					default:
1549 						done = 1;
1550 					}
1551 				}
1552 				t->in_key = 1;
1553 				tid = TK_EOL;
1554 				buffer_copy_string_len(token, CONST_STR_LEN("(EOL)"));
1555 			} else {
1556 				config_skip_newline(t);
1557 				t->line_pos = 1;
1558 				t->line++;
1559 			}
1560 			break;
1561 		case ',':
1562 			if (t->in_brace > 0) {
1563 				tid = TK_COMMA;
1564 
1565 				buffer_copy_string_len(token, CONST_STR_LEN("(COMMA)"));
1566 			}
1567 
1568 			t->offset++;
1569 			t->line_pos++;
1570 			break;
1571 		case '"':
1572 			/* search for the terminating " */
1573 			start = t->input + t->offset + 1;
1574 			buffer_copy_string_len(token, CONST_STR_LEN(""));
1575 
1576 			for (i = 1; t->input[t->offset + i]; i++) {
1577 				if (t->input[t->offset + i] == '\\' &&
1578 				    t->input[t->offset + i + 1] == '"') {
1579 
1580 					buffer_append_string_len(token, start, t->input + t->offset + i - start);
1581 
1582 					start = t->input + t->offset + i + 1;
1583 
1584 					/* skip the " */
1585 					i++;
1586 					continue;
1587 				}
1588 
1589 
1590 				if (t->input[t->offset + i] == '"') {
1591 					tid = TK_STRING;
1592 
1593 					buffer_append_string_len(token, start, t->input + t->offset + i - start);
1594 
1595 					break;
1596 				}
1597 			}
1598 
1599 			if (t->input[t->offset + i] == '\0') {
1600 				return config_tokenizer_err(srv, __FILE__, __LINE__, t,
1601 						"missing closing quote");
1602 			}
1603 
1604 			t->offset += i + 1;
1605 			t->line_pos += i + 1;
1606 
1607 			break;
1608 		case '(':
1609 			t->offset++;
1610 			t->in_brace++;
1611 
1612 			tid = TK_LPARAN;
1613 
1614 			buffer_copy_string_len(token, CONST_STR_LEN("("));
1615 			break;
1616 		case ')':
1617 			t->offset++;
1618 			t->in_brace--;
1619 
1620 			tid = TK_RPARAN;
1621 
1622 			buffer_copy_string_len(token, CONST_STR_LEN(")"));
1623 			break;
1624 		case '$':
1625 			t->offset++;
1626 
1627 			tid = TK_DOLLAR;
1628 			t->in_cond = 1;
1629 			t->in_key = 0;
1630 
1631 			buffer_copy_string_len(token, CONST_STR_LEN("$"));
1632 
1633 			break;
1634 
1635 		case '+':
1636 			if (t->input[t->offset + 1] == '=') {
1637 				t->offset += 2;
1638 				buffer_copy_string_len(token, CONST_STR_LEN("+="));
1639 				tid = TK_APPEND;
1640 			} else {
1641 				t->offset++;
1642 				tid = TK_PLUS;
1643 				buffer_copy_string_len(token, CONST_STR_LEN("+"));
1644 			}
1645 			break;
1646 
1647 		case ':':
1648 			if (t->input[t->offset+1] == '=') {
1649 				t->offset += 2;
1650 				tid = TK_FORCE_ASSIGN;
1651 				buffer_copy_string_len(token, CONST_STR_LEN(":="));
1652 			} else {
1653 				return config_tokenizer_err(srv, __FILE__, __LINE__, t,
1654 						"unexpected character ':'");
1655 			}
1656 			break;
1657 
1658 		case '{':
1659 			t->offset++;
1660 
1661 			tid = TK_LCURLY;
1662 
1663 			buffer_copy_string_len(token, CONST_STR_LEN("{"));
1664 
1665 			break;
1666 
1667 		case '}':
1668 			t->offset++;
1669 
1670 			tid = TK_RCURLY;
1671 
1672 			buffer_copy_string_len(token, CONST_STR_LEN("}"));
1673 
1674 			for (; t->offset < t->size; ++t->offset,++t->line_pos) {
1675 				c = t->input[t->offset];
1676 				if (c == '\r' || c == '\n') {
1677 					break;
1678 				}
1679 				else if (c == '#') {
1680 					t->line_pos += config_skip_comment(t);
1681 					break;
1682 				}
1683 				else if (c != ' ' && c != '\t') {
1684 					t->simulate_eol = 1;
1685 					break;
1686 				} /* else (c == ' ' || c == '\t') */
1687 			}
1688 
1689 			break;
1690 
1691 		case '[':
1692 			t->offset++;
1693 
1694 			tid = TK_LBRACKET;
1695 
1696 			buffer_copy_string_len(token, CONST_STR_LEN("["));
1697 
1698 			break;
1699 
1700 		case ']':
1701 			t->offset++;
1702 
1703 			tid = TK_RBRACKET;
1704 
1705 			buffer_copy_string_len(token, CONST_STR_LEN("]"));
1706 
1707 			break;
1708 		case '#':
1709 			t->line_pos += config_skip_comment(t);
1710 
1711 			break;
1712 		default:
1713 			if (t->in_cond) {
1714 				for (i = 0; t->input[t->offset + i] &&
1715 				     (isalpha((unsigned char)t->input[t->offset + i])
1716 				      || t->input[t->offset + i] == '_'); ++i);
1717 
1718 				if (i && t->input[t->offset + i]) {
1719 					tid = TK_SRVVARNAME;
1720 					buffer_copy_string_len(token, t->input + t->offset, i);
1721 
1722 					t->offset += i;
1723 					t->line_pos += i;
1724 				} else {
1725 					return config_tokenizer_err(srv, __FILE__, __LINE__, t,
1726 							"invalid character in condition");
1727 				}
1728 			} else if (isdigit((unsigned char)c)) {
1729 				/* take all digits */
1730 				for (i = 0; t->input[t->offset + i] && isdigit((unsigned char)t->input[t->offset + i]);  i++);
1731 
1732 				/* was there it least a digit ? */
1733 				if (i) {
1734 					tid = TK_INTEGER;
1735 
1736 					buffer_copy_string_len(token, t->input + t->offset, i);
1737 
1738 					t->offset += i;
1739 					t->line_pos += i;
1740 				}
1741 			} else {
1742 				/* the key might consist of [-.0-9a-z] */
1743 				for (i = 0; t->input[t->offset + i] &&
1744 				     (isalnum((unsigned char)t->input[t->offset + i]) ||
1745 				      t->input[t->offset + i] == '.' ||
1746 				      t->input[t->offset + i] == '_' || /* for env.* */
1747 				      t->input[t->offset + i] == '-'
1748 				      ); i++);
1749 
1750 				if (i && t->input[t->offset + i]) {
1751 					buffer_copy_string_len(token, t->input + t->offset, i);
1752 
1753 					if (strcmp(token->ptr, "include") == 0) {
1754 						tid = TK_INCLUDE;
1755 					} else if (strcmp(token->ptr, "include_shell") == 0) {
1756 						tid = TK_INCLUDE_SHELL;
1757 					} else if (strcmp(token->ptr, "global") == 0) {
1758 						tid = TK_GLOBAL;
1759 					} else if (strcmp(token->ptr, "else") == 0) {
1760 						tid = TK_ELSE;
1761 					} else {
1762 						tid = TK_LKEY;
1763 					}
1764 
1765 					t->offset += i;
1766 					t->line_pos += i;
1767 				} else {
1768 					return config_tokenizer_err(srv, __FILE__, __LINE__, t,
1769 							"invalid character in variable name");
1770 				}
1771 			}
1772 			break;
1773 		}
1774 	}
1775 
1776 	if (tid) {
1777 		*token_id = tid;
1778 		return 1;
1779 	} else if (t->offset < t->size) {
1780 		log_error(srv->errh, __FILE__, __LINE__, "%d, %s", tid, token->ptr);
1781 	}
1782 	return 0;
1783 }
1784 
1785 static int config_parse(server *srv, config_t *context, const char *source, const char *input, size_t isize) {
1786 	void *pParser;
1787 	buffer *token, *lasttoken;
1788 	int token_id = 0;
1789 	int ret;
1790 	tokenizer_t t;
1791 
1792 	t.source = source;
1793 	t.input = input;
1794 	t.size = isize;
1795 	t.offset = 0;
1796 	t.line = 1;
1797 	t.line_pos = 1;
1798 
1799 	t.in_key = 1;
1800 	t.in_brace = 0;
1801 	t.in_cond = 0;
1802 	t.simulate_eol = 0;
1803 
1804 	pParser = configparserAlloc( malloc );
1805 	force_assert(pParser);
1806 	lasttoken = buffer_init();
1807 	token = buffer_init();
1808 	while((1 == (ret = config_tokenizer(srv, &t, &token_id, token))) && context->ok) {
1809 		buffer_copy_buffer(lasttoken, token);
1810 		configparser(pParser, token_id, token, context);
1811 
1812 		token = buffer_init();
1813 	}
1814 	buffer_free(token);
1815 
1816 	if (ret != -1 && context->ok) {
1817 		/* add an EOL at EOF, better than say sorry */
1818 		configparser(pParser, TK_EOL, buffer_init_string("(EOL)"), context);
1819 		if (context->ok) {
1820 			configparser(pParser, 0, NULL, context);
1821 		}
1822 	}
1823 	configparserFree(pParser, free);
1824 
1825 	if (ret == -1) {
1826 		log_error(srv->errh, __FILE__, __LINE__,
1827 		          "configfile parser failed at: %s", lasttoken->ptr);
1828 	} else if (context->ok == 0) {
1829 		log_error(srv->errh, __FILE__, __LINE__, "source: %s line: %d pos: %d "
1830 		          "parser failed somehow near here: %s",
1831 		          t.source, t.line, t.line_pos, lasttoken->ptr);
1832 		ret = -1;
1833 	}
1834 	buffer_free(lasttoken);
1835 
1836 	return ret == -1 ? -1 : 0;
1837 }
1838 
1839 static int config_parse_file_stream(server *srv, config_t *context, const char *fn) {
1840 	stream s;
1841 
1842 	if (0 != stream_open(&s, fn)) {
1843 		log_perror(srv->errh, __FILE__, __LINE__,
1844 		  "opening configfile %s failed", fn);
1845 		return -1;
1846 	}
1847 
1848 	int ret = config_parse(srv, context, fn, s.start, (size_t)s.size);
1849 	stream_close(&s);
1850 	return ret;
1851 }
1852 
1853 int config_parse_file(server *srv, config_t *context, const char *fn) {
1854 	buffer *filename;
1855 	int ret = -1;
1856       #ifdef GLOB_BRACE
1857 	int flags = GLOB_BRACE;
1858       #else
1859 	int flags = 0;
1860       #endif
1861 	glob_t gl;
1862 
1863 	if ((fn[0] == '/' || fn[0] == '\\') ||
1864 	    (fn[0] == '.' && (fn[1] == '/' || fn[1] == '\\')) ||
1865 	    (fn[0] == '.' && fn[1] == '.' && (fn[2] == '/' || fn[2] == '\\'))) {
1866 		filename = buffer_init_string(fn);
1867 	} else {
1868 		filename = buffer_init_buffer(context->basedir);
1869 		buffer_append_string(filename, fn);
1870 	}
1871 
1872 	switch (glob(filename->ptr, flags, NULL, &gl)) {
1873 	case 0:
1874 		for (size_t i = 0; i < gl.gl_pathc; ++i) {
1875 			ret = config_parse_file_stream(srv, context, gl.gl_pathv[i]);
1876 			if (0 != ret) break;
1877 		}
1878 		globfree(&gl);
1879 		break;
1880 	case GLOB_NOMATCH:
1881 		if (filename->ptr[strcspn(filename->ptr, "*?[]{}")] != '\0') { /*(contains glob metachars)*/
1882 			ret = 0; /* not an error if no files match glob pattern */
1883 		}
1884 		else {
1885 			log_error(srv->errh, __FILE__, __LINE__, "include file not found: %s", filename->ptr);
1886 		}
1887 		break;
1888 	case GLOB_ABORTED:
1889 	case GLOB_NOSPACE:
1890 		log_perror(srv->errh, __FILE__, __LINE__, "glob() %s failed", filename->ptr);
1891 		break;
1892 	}
1893 
1894 	buffer_free(filename);
1895 	return ret;
1896 }
1897 
1898 #ifdef __CYGWIN__
1899 
1900 static char* getCWD(char *buf, size_t sz) {
1901     if (NULL == getcwd(buf, sz)) {
1902         return NULL;
1903     }
1904     for (size_t i = 0; buf[i]; ++i) {
1905         if (buf[i] == '\\') buf[i] = '/';
1906     }
1907     return buf;
1908 }
1909 
1910 #define getcwd(buf, sz) getCWD((buf),(sz))
1911 
1912 #endif /* __CYGWIN__ */
1913 
1914 int config_parse_cmd(server *srv, config_t *context, const char *cmd) {
1915 	int ret = 0;
1916 	int fds[2];
1917 	char oldpwd[PATH_MAX];
1918 
1919 	if (NULL == getcwd(oldpwd, sizeof(oldpwd))) {
1920 		log_perror(srv->errh, __FILE__, __LINE__, "getcwd()");
1921 		return -1;
1922 	}
1923 
1924 	if (!buffer_string_is_empty(context->basedir)) {
1925 		if (0 != chdir(context->basedir->ptr)) {
1926 			log_perror(srv->errh, __FILE__, __LINE__,
1927 			  "cannot change directory to %s", context->basedir->ptr);
1928 			return -1;
1929 		}
1930 	}
1931 
1932 	if (pipe(fds)) {
1933 		log_perror(srv->errh, __FILE__, __LINE__, "pipe()");
1934 		ret = -1;
1935 	}
1936 	else {
1937 		char *shell = getenv("SHELL");
1938 		char *args[4];
1939 		pid_t pid;
1940 		*(const char **)&args[0] = shell ? shell : "/bin/sh";
1941 		*(const char **)&args[1] = "-c";
1942 		*(const char **)&args[2] = cmd;
1943 		args[3] = NULL;
1944 
1945 		fdevent_setfd_cloexec(fds[0]);
1946 		pid = fdevent_fork_execve(args[0], args, NULL, -1, fds[1], -1, -1);
1947 		if (-1 == pid) {
1948 			log_perror(srv->errh, __FILE__, __LINE__, "fork/exec(%s)", cmd);
1949 			ret = -1;
1950 		}
1951 		else {
1952 			ssize_t rd;
1953 			pid_t wpid;
1954 			int wstatus;
1955 			buffer *out = buffer_init();
1956 			close(fds[1]);
1957 			fds[1] = -1;
1958 			do {
1959 				rd = read(fds[0], buffer_string_prepare_append(out, 1023), 1023);
1960 				if (rd >= 0) buffer_commit(out, (size_t)rd);
1961 			} while (rd > 0 || (-1 == rd && errno == EINTR));
1962 			if (0 != rd) {
1963 				log_perror(srv->errh, __FILE__, __LINE__, "read \"%s\"", cmd);
1964 				ret = -1;
1965 			}
1966 			close(fds[0]);
1967 			fds[0] = -1;
1968 			while (-1 == (wpid = waitpid(pid, &wstatus, 0)) && errno == EINTR) ;
1969 			if (wpid != pid) {
1970 				log_perror(srv->errh, __FILE__, __LINE__, "waitpid \"%s\"",cmd);
1971 				ret = -1;
1972 			}
1973 			if (0 != wstatus) {
1974 				log_error(srv->errh, __FILE__, __LINE__,
1975 				  "command \"%s\" exited non-zero: %d",
1976 				  cmd, WEXITSTATUS(wstatus));
1977 				ret = -1;
1978 			}
1979 
1980 			if (-1 != ret) {
1981 				ret = config_parse(srv, context, cmd, CONST_BUF_LEN(out));
1982 			}
1983 			buffer_free(out);
1984 		}
1985 		if (-1 != fds[0]) close(fds[0]);
1986 		if (-1 != fds[1]) close(fds[1]);
1987 	}
1988 
1989 	if (0 != chdir(oldpwd)) {
1990 		log_perror(srv->errh, __FILE__, __LINE__,
1991 		  "cannot change directory to %s", oldpwd);
1992 		ret = -1;
1993 	}
1994 	return ret;
1995 }
1996 
1997 static void context_init(server *srv, config_t *context) {
1998 	context->srv = srv;
1999 	context->ok = 1;
2000 	vector_config_weak_init(&context->configs_stack);
2001 	context->basedir = buffer_init();
2002 }
2003 
2004 static void context_free(config_t *context) {
2005 	vector_config_weak_clear(&context->configs_stack);
2006 	buffer_free(context->basedir);
2007 }
2008 
2009 int config_read(server *srv, const char *fn) {
2010 	config_t context;
2011 	data_config *dc;
2012 	buffer *dcwd;
2013 	int ret;
2014 	char *pos;
2015 
2016 	context_init(srv, &context);
2017 	context.all_configs = srv->config_context;
2018 
2019 #ifdef __WIN32
2020 	pos = strrchr(fn, '\\');
2021 #else
2022 	pos = strrchr(fn, '/');
2023 #endif
2024 	if (pos) {
2025 		buffer_copy_string_len(context.basedir, fn, pos - fn + 1);
2026 	}
2027 
2028 	dc = data_config_init();
2029 	buffer_copy_string_len(&dc->key, CONST_STR_LEN("global"));
2030 
2031 	force_assert(context.all_configs->used == 0);
2032 	dc->context_ndx = context.all_configs->used;
2033 	array_insert_unique(context.all_configs, (data_unset *)dc);
2034 	context.current = dc;
2035 
2036 	/* default context */
2037 	*array_get_int_ptr(dc->value, CONST_STR_LEN("var.PID")) = getpid();
2038 
2039 	dcwd = srv->tmp_buf;
2040 	buffer_string_prepare_copy(dcwd, PATH_MAX-1);
2041 	if (NULL != getcwd(dcwd->ptr, buffer_string_space(dcwd)+1)) {
2042 		buffer_commit(dcwd, strlen(dcwd->ptr));
2043 		array_set_key_value(dc->value, CONST_STR_LEN("var.CWD"), CONST_BUF_LEN(dcwd));
2044 	}
2045 
2046 	ret = config_parse_file_stream(srv, &context, fn);
2047 
2048 	/* remains nothing if parser is ok */
2049 	force_assert(!(0 == ret && context.ok && 0 != context.configs_stack.used));
2050 	context_free(&context);
2051 
2052 	if (0 != ret) {
2053 		return ret;
2054 	}
2055 
2056 	if (0 != config_insert_srvconf(srv)) {
2057 		return -1;
2058 	}
2059 
2060 	if (0 != config_insert(srv)) {
2061 		return -1;
2062 	}
2063 
2064 	return 0;
2065 }
2066 
2067 int config_set_defaults(server *srv) {
2068 	size_t i;
2069 	request_config *s = &((config_data_base *)srv->config_data_base)->defaults;
2070 	struct stat st1, st2;
2071 
2072 	if (fdevent_config(&srv->srvconf.event_handler, srv->errh) <= 0)
2073 		return -1;
2074 
2075 	if (!buffer_string_is_empty(srv->srvconf.changeroot)) {
2076 		if (-1 == stat(srv->srvconf.changeroot->ptr, &st1)) {
2077 			log_error(srv->errh, __FILE__, __LINE__,
2078 			  "server.chroot doesn't exist: %s",
2079 			  srv->srvconf.changeroot->ptr);
2080 			return -1;
2081 		}
2082 		if (!S_ISDIR(st1.st_mode)) {
2083 			log_error(srv->errh, __FILE__, __LINE__,
2084 			  "server.chroot isn't a directory: %s",
2085 			  srv->srvconf.changeroot->ptr);
2086 			return -1;
2087 		}
2088 	}
2089 
2090 	if (!srv->srvconf.upload_tempdirs->used) {
2091 		const char *tmpdir = getenv("TMPDIR");
2092 		if (NULL == tmpdir) tmpdir = "/var/tmp";
2093 		array_insert_value(srv->srvconf.upload_tempdirs, tmpdir, strlen(tmpdir));
2094 	}
2095 
2096 	if (srv->srvconf.upload_tempdirs->used) {
2097 		buffer * const b = srv->tmp_buf;
2098 		size_t len;
2099 		buffer_clear(b);
2100 		if (!buffer_string_is_empty(srv->srvconf.changeroot)) {
2101 			buffer_copy_buffer(b, srv->srvconf.changeroot);
2102 			buffer_append_slash(b);
2103 		}
2104 		len = buffer_string_length(b);
2105 
2106 		for (i = 0; i < srv->srvconf.upload_tempdirs->used; ++i) {
2107 			const data_string * const ds = (data_string *)srv->srvconf.upload_tempdirs->data[i];
2108 			buffer_string_set_length(b, len); /*(truncate)*/
2109 			buffer_append_string_buffer(b, &ds->value);
2110 			if (-1 == stat(b->ptr, &st1)) {
2111 				log_error(srv->errh, __FILE__, __LINE__,
2112 				  "server.upload-dirs doesn't exist: %s", b->ptr);
2113 			} else if (!S_ISDIR(st1.st_mode)) {
2114 				log_error(srv->errh, __FILE__, __LINE__,
2115 				  "server.upload-dirs isn't a directory: %s", b->ptr);
2116 			}
2117 		}
2118 	}
2119 
2120 	chunkqueue_set_tempdirs_default(
2121 		srv->srvconf.upload_tempdirs,
2122 		srv->srvconf.upload_temp_file_size);
2123 
2124 	if (buffer_string_is_empty(s->document_root)) {
2125 		log_error(srv->errh, __FILE__, __LINE__, "document-root is not set");
2126 		return -1;
2127 	}
2128 
2129 	if (2 == s->force_lowercase_filenames) { /* user didn't configure it in global section? */
2130 		s->force_lowercase_filenames = 0; /* default to 0 */
2131 
2132 		buffer * const tb = srv->tmp_buf;
2133 		buffer_copy_buffer(tb, s->document_root);
2134 
2135 		buffer_to_lower(tb);
2136 
2137 		if (0 == stat(tb->ptr, &st1)) {
2138 			int is_lower = 0;
2139 
2140 			is_lower = buffer_is_equal(tb, s->document_root);
2141 
2142 			/* lower-case existed, check upper-case */
2143 			buffer_copy_buffer(tb, s->document_root);
2144 
2145 			buffer_to_upper(tb);
2146 
2147 			/* we have to handle the special case that upper and lower-casing results in the same filename
2148 			 * as in server.document-root = "/" or "/12345/" */
2149 
2150 			if (is_lower && buffer_is_equal(tb, s->document_root)) {
2151 				/* lower-casing and upper-casing didn't result in
2152 				 * an other filename, no need to stat(),
2153 				 * just assume it is case-sensitive. */
2154 
2155 				s->force_lowercase_filenames = 0;
2156 			} else if (0 == stat(tb->ptr, &st2)) {
2157 
2158 				/* upper case exists too, doesn't the FS handle this ? */
2159 
2160 				/* upper and lower have the same inode -> case-insensitve FS */
2161 
2162 				if (st1.st_ino == st2.st_ino) {
2163 					/* upper and lower have the same inode -> case-insensitve FS */
2164 
2165 					s->force_lowercase_filenames = 1;
2166 				}
2167 			}
2168 		}
2169 	}
2170 
2171 	return 0;
2172 }
2173