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