]> git.ipfire.org Git - thirdparty/squid.git/blob - src/cache_cf.cc
Source Format Enforcement (#571)
[thirdparty/squid.git] / src / cache_cf.cc
1 /*
2 * Copyright (C) 1996-2020 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9 /* DEBUG: section 03 Configuration File Parsing */
10
11 #include "squid.h"
12 #include "acl/Acl.h"
13 #include "acl/AclDenyInfoList.h"
14 #include "acl/AclSizeLimit.h"
15 #include "acl/Address.h"
16 #include "acl/Gadgets.h"
17 #include "acl/MethodData.h"
18 #include "acl/Tree.h"
19 #include "anyp/PortCfg.h"
20 #include "anyp/UriScheme.h"
21 #include "auth/Config.h"
22 #include "auth/Scheme.h"
23 #include "AuthReg.h"
24 #include "base/RunnersRegistry.h"
25 #include "cache_cf.h"
26 #include "CachePeer.h"
27 #include "ConfigParser.h"
28 #include "CpuAffinityMap.h"
29 #include "DiskIO/DiskIOModule.h"
30 #include "eui/Config.h"
31 #include "ExternalACL.h"
32 #include "format/Format.h"
33 #include "ftp/Elements.h"
34 #include "globals.h"
35 #include "HttpHeaderTools.h"
36 #include "icmp/IcmpConfig.h"
37 #include "ident/Config.h"
38 #include "ip/Intercept.h"
39 #include "ip/NfMarkConfig.h"
40 #include "ip/QosConfig.h"
41 #include "ip/tools.h"
42 #include "ipc/Kids.h"
43 #include "log/Config.h"
44 #include "log/CustomLog.h"
45 #include "MemBuf.h"
46 #include "MessageDelayPools.h"
47 #include "mgr/ActionPasswordList.h"
48 #include "mgr/Registration.h"
49 #include "neighbors.h"
50 #include "NeighborTypeDomainList.h"
51 #include "Parsing.h"
52 #include "pconn.h"
53 #include "PeerDigest.h"
54 #include "PeerPoolMgr.h"
55 #include "redirect.h"
56 #include "RefreshPattern.h"
57 #include "rfc1738.h"
58 #include "sbuf/List.h"
59 #include "sbuf/Stream.h"
60 #include "SquidConfig.h"
61 #include "SquidString.h"
62 #include "ssl/ProxyCerts.h"
63 #include "Store.h"
64 #include "store/Disk.h"
65 #include "store/Disks.h"
66 #include "StoreFileSystem.h"
67 #include "tools.h"
68 #include "util.h"
69 #include "wordlist.h"
70 /* wccp2 has its own conditional definitions */
71 #include "wccp2.h"
72 #if USE_ADAPTATION
73 #include "adaptation/Config.h"
74 #endif
75 #if ICAP_CLIENT
76 #include "adaptation/icap/Config.h"
77 #endif
78 #if USE_ECAP
79 #include "adaptation/ecap/Config.h"
80 #endif
81 #if USE_OPENSSL
82 #include "ssl/Config.h"
83 #include "ssl/support.h"
84 #endif
85 #if USE_SQUID_ESI
86 #include "esi/Parser.h"
87 #endif
88 #if SQUID_SNMP
89 #include "snmp.h"
90 #endif
91
92 #if HAVE_GLOB_H
93 #include <glob.h>
94 #endif
95 #include <chrono>
96 #include <limits>
97 #include <list>
98 #if HAVE_PWD_H
99 #include <pwd.h>
100 #endif
101 #if HAVE_GRP_H
102 #include <grp.h>
103 #endif
104 #if HAVE_SYS_SOCKET_H
105 #include <sys/socket.h>
106 #endif
107 #if HAVE_SYS_STAT_H
108 #include <sys/stat.h>
109 #endif
110
111 #if USE_OPENSSL
112 #include "ssl/gadgets.h"
113 #endif
114
115 #if USE_ADAPTATION
116 static void parse_adaptation_service_set_type();
117 static void parse_adaptation_service_chain_type();
118 static void parse_adaptation_access_type();
119 #endif
120
121 #if ICAP_CLIENT
122 static void parse_icap_service_type(Adaptation::Icap::Config *);
123 static void dump_icap_service_type(StoreEntry *, const char *, const Adaptation::Icap::Config &);
124 static void free_icap_service_type(Adaptation::Icap::Config *);
125 static void parse_icap_class_type();
126 static void parse_icap_access_type();
127
128 static void parse_icap_service_failure_limit(Adaptation::Icap::Config *);
129 static void dump_icap_service_failure_limit(StoreEntry *, const char *, const Adaptation::Icap::Config &);
130 static void free_icap_service_failure_limit(Adaptation::Icap::Config *);
131 #endif
132
133 #if USE_ECAP
134 static void parse_ecap_service_type(Adaptation::Ecap::Config *);
135 static void dump_ecap_service_type(StoreEntry *, const char *, const Adaptation::Ecap::Config &);
136 static void free_ecap_service_type(Adaptation::Ecap::Config *);
137 #endif
138
139 static peer_t parseNeighborType(const char *s);
140
141 static const char *const T_NANOSECOND_STR = "nanosecond";
142 static const char *const T_MICROSECOND_STR = "microsecond";
143 static const char *const T_MILLISECOND_STR = "millisecond";
144 static const char *const T_SECOND_STR = "second";
145 static const char *const T_MINUTE_STR = "minute";
146 static const char *const T_HOUR_STR = "hour";
147 static const char *const T_DAY_STR = "day";
148 static const char *const T_WEEK_STR = "week";
149 static const char *const T_FORTNIGHT_STR = "fortnight";
150 static const char *const T_MONTH_STR = "month";
151 static const char *const T_YEAR_STR = "year";
152 static const char *const T_DECADE_STR = "decade";
153
154 static const char *const B_BYTES_STR = "bytes";
155 static const char *const B_KBYTES_STR = "KB";
156 static const char *const B_MBYTES_STR = "MB";
157 static const char *const B_GBYTES_STR = "GB";
158
159 static const char *const list_sep = ", \t\n\r";
160
161 // std::chrono::years requires C++20. Do our own rough calculation for now.
162 static const double HoursPerYear = 24*365.2522;
163
164 static void parse_access_log(CustomLog ** customlog_definitions);
165 static int check_null_access_log(CustomLog *customlog_definitions);
166 static void dump_access_log(StoreEntry * entry, const char *name, CustomLog * definitions);
167 static void free_access_log(CustomLog ** definitions);
168 static bool setLogformat(CustomLog *cl, const char *name, const bool dieWhenMissing);
169
170 static void configDoConfigure(void);
171 static void parse_refreshpattern(RefreshPattern **);
172 static void parse_u_short(unsigned short * var);
173 static void parse_string(char **);
174 static void default_all(void);
175 static void defaults_if_none(void);
176 static void defaults_postscriptum(void);
177 static int parse_line(char *);
178 static void parse_obsolete(const char *);
179 static void parseBytesLine(size_t * bptr, const char *units);
180 static void parseBytesLineSigned(ssize_t * bptr, const char *units);
181 static size_t parseBytesUnits(const char *unit);
182 static void free_all(void);
183 void requirePathnameExists(const char *name, const char *path);
184 static OBJH dump_config;
185 #if USE_HTTP_VIOLATIONS
186 static void free_HeaderManglers(HeaderManglers **pm);
187 static void dump_http_header_access(StoreEntry * entry, const char *name, const HeaderManglers *manglers);
188 static void parse_http_header_access(HeaderManglers **manglers);
189 #define free_http_header_access free_HeaderManglers
190 static void dump_http_header_replace(StoreEntry * entry, const char *name, const HeaderManglers *manglers);
191 static void parse_http_header_replace(HeaderManglers **manglers);
192 #define free_http_header_replace free_HeaderManglers
193 #endif
194 static void dump_HeaderWithAclList(StoreEntry * entry, const char *name, HeaderWithAclList *headers);
195 static void parse_HeaderWithAclList(HeaderWithAclList **header);
196 static void free_HeaderWithAclList(HeaderWithAclList **header);
197 static void parse_note(Notes *);
198 static void dump_note(StoreEntry *, const char *, Notes &);
199 static void free_note(Notes *);
200 static void parse_denyinfo(AclDenyInfoList ** var);
201 static void dump_denyinfo(StoreEntry * entry, const char *name, AclDenyInfoList * var);
202 static void free_denyinfo(AclDenyInfoList ** var);
203
204 #if USE_WCCPv2
205 static void parse_IpAddress_list(Ip::Address_list **);
206 static void dump_IpAddress_list(StoreEntry *, const char *, const Ip::Address_list *);
207 static void free_IpAddress_list(Ip::Address_list **);
208 #if CURRENTLY_UNUSED
209 static int check_null_IpAddress_list(const Ip::Address_list *);
210 #endif /* CURRENTLY_UNUSED */
211 #endif /* USE_WCCPv2 */
212
213 static void parsePortCfg(AnyP::PortCfgPointer *, const char *protocol);
214 #define parse_PortCfg(l) parsePortCfg((l), token)
215 static void dump_PortCfg(StoreEntry *, const char *, const AnyP::PortCfgPointer &);
216 #define free_PortCfg(h) *(h)=NULL
217
218 #if USE_OPENSSL
219 static void parse_sslproxy_cert_sign(sslproxy_cert_sign **cert_sign);
220 static void dump_sslproxy_cert_sign(StoreEntry *entry, const char *name, sslproxy_cert_sign *cert_sign);
221 static void free_sslproxy_cert_sign(sslproxy_cert_sign **cert_sign);
222 static void parse_sslproxy_cert_adapt(sslproxy_cert_adapt **cert_adapt);
223 static void dump_sslproxy_cert_adapt(StoreEntry *entry, const char *name, sslproxy_cert_adapt *cert_adapt);
224 static void free_sslproxy_cert_adapt(sslproxy_cert_adapt **cert_adapt);
225 static void parse_sslproxy_ssl_bump(acl_access **ssl_bump);
226 static void dump_sslproxy_ssl_bump(StoreEntry *entry, const char *name, acl_access *ssl_bump);
227 static void free_sslproxy_ssl_bump(acl_access **ssl_bump);
228 #endif /* USE_OPENSSL */
229
230 static void parse_ftp_epsv(acl_access **ftp_epsv);
231 static void dump_ftp_epsv(StoreEntry *entry, const char *name, acl_access *ftp_epsv);
232 static void free_ftp_epsv(acl_access **ftp_epsv);
233
234 static void parse_b_size_t(size_t * var);
235 static void parse_b_int64_t(int64_t * var);
236
237 static void parse_CpuAffinityMap(CpuAffinityMap **const cpuAffinityMap);
238 static void dump_CpuAffinityMap(StoreEntry *const entry, const char *const name, const CpuAffinityMap *const cpuAffinityMap);
239 static void free_CpuAffinityMap(CpuAffinityMap **const cpuAffinityMap);
240
241 static void parse_UrlHelperTimeout(SquidConfig::UrlHelperTimeout *);
242 static void dump_UrlHelperTimeout(StoreEntry *, const char *, SquidConfig::UrlHelperTimeout &);
243 static void free_UrlHelperTimeout(SquidConfig::UrlHelperTimeout *);
244
245 static int parseOneConfigFile(const char *file_name, unsigned int depth);
246
247 static void parse_configuration_includes_quoted_values(bool *recognizeQuotedValues);
248 static void dump_configuration_includes_quoted_values(StoreEntry *const entry, const char *const name, bool recognizeQuotedValues);
249 static void free_configuration_includes_quoted_values(bool *recognizeQuotedValues);
250 static void parse_on_unsupported_protocol(acl_access **access);
251 static void dump_on_unsupported_protocol(StoreEntry *entry, const char *name, acl_access *access);
252 static void free_on_unsupported_protocol(acl_access **access);
253 static void ParseAclWithAction(acl_access **access, const Acl::Answer &action, const char *desc, ACL *acl = nullptr);
254
255 /*
256 * LegacyParser is a parser for legacy code that uses the global
257 * approach. This is static so that it is only exposed to cache_cf.
258 * Other modules needing access to a ConfigParser should have it
259 * provided to them in their parserFOO methods.
260 */
261 static ConfigParser LegacyParser = ConfigParser();
262
263 void
264 self_destruct(void)
265 {
266 LegacyParser.destruct();
267 }
268
269 static void
270 SetConfigFilename(char const *file_name, bool is_pipe)
271 {
272 if (is_pipe)
273 cfg_filename = file_name + 1;
274 else
275 cfg_filename = file_name;
276 }
277
278 static const char*
279 skip_ws(const char* s)
280 {
281 while (xisspace(*s))
282 ++s;
283
284 return s;
285 }
286
287 static int
288 parseManyConfigFiles(char* files, int depth)
289 {
290 int error_count = 0;
291 char* saveptr = NULL;
292 #if HAVE_GLOB
293 char *path;
294 glob_t globbuf;
295 int i;
296 memset(&globbuf, 0, sizeof(globbuf));
297 for (path = strwordtok(files, &saveptr); path; path = strwordtok(NULL, &saveptr)) {
298 if (glob(path, globbuf.gl_pathc ? GLOB_APPEND : 0, NULL, &globbuf) != 0) {
299 int xerrno = errno;
300 fatalf("Unable to find configuration file: %s: %s", path, xstrerr(xerrno));
301 }
302 }
303 for (i = 0; i < (int)globbuf.gl_pathc; ++i) {
304 error_count += parseOneConfigFile(globbuf.gl_pathv[i], depth);
305 }
306 globfree(&globbuf);
307 #else
308 char* file = strwordtok(files, &saveptr);
309 while (file != NULL) {
310 error_count += parseOneConfigFile(file, depth);
311 file = strwordtok(NULL, &saveptr);
312 }
313 #endif /* HAVE_GLOB */
314 return error_count;
315 }
316
317 static void
318 ReplaceSubstr(char*& str, int& len, unsigned substrIdx, unsigned substrLen, const char* newSubstr)
319 {
320 assert(str != NULL);
321 assert(newSubstr != NULL);
322
323 unsigned newSubstrLen = strlen(newSubstr);
324 if (newSubstrLen > substrLen)
325 str = (char*)realloc(str, len - substrLen + newSubstrLen + 1);
326
327 // move tail part including zero
328 memmove(str + substrIdx + newSubstrLen, str + substrIdx + substrLen, len - substrIdx - substrLen + 1);
329 // copy new substring in place
330 memcpy(str + substrIdx, newSubstr, newSubstrLen);
331
332 len = strlen(str);
333 }
334
335 static void
336 SubstituteMacro(char*& line, int& len, const char* macroName, const char* substStr)
337 {
338 assert(line != NULL);
339 assert(macroName != NULL);
340 assert(substStr != NULL);
341 unsigned macroNameLen = strlen(macroName);
342 while (const char* macroPos = strstr(line, macroName)) // we would replace all occurrences
343 ReplaceSubstr(line, len, macroPos - line, macroNameLen, substStr);
344 }
345
346 static void
347 ProcessMacros(char*& line, int& len)
348 {
349 SubstituteMacro(line, len, "${service_name}", service_name.c_str());
350 SubstituteMacro(line, len, "${process_name}", TheKidName.c_str());
351 SubstituteMacro(line, len, "${process_number}", xitoa(KidIdentifier));
352 }
353
354 static void
355 trim_trailing_ws(char* str)
356 {
357 assert(str != NULL);
358 unsigned i = strlen(str);
359 while ((i > 0) && xisspace(str[i - 1]))
360 --i;
361 str[i] = '\0';
362 }
363
364 static const char*
365 FindStatement(const char* line, const char* statement)
366 {
367 assert(line != NULL);
368 assert(statement != NULL);
369
370 const char* str = skip_ws(line);
371 unsigned len = strlen(statement);
372 if (strncmp(str, statement, len) == 0) {
373 str += len;
374 if (*str == '\0')
375 return str;
376 else if (xisspace(*str))
377 return skip_ws(str);
378 }
379
380 return NULL;
381 }
382
383 static bool
384 StrToInt(const char* str, long& number)
385 {
386 assert(str != NULL);
387
388 char* end;
389 number = strtol(str, &end, 0);
390
391 return (end != str) && (*end == '\0'); // returns true if string contains nothing except number
392 }
393
394 static bool
395 EvalBoolExpr(const char* expr)
396 {
397 assert(expr != NULL);
398 if (strcmp(expr, "true") == 0) {
399 return true;
400 } else if (strcmp(expr, "false") == 0) {
401 return false;
402 } else if (const char* equation = strchr(expr, '=')) {
403 const char* rvalue = skip_ws(equation + 1);
404 char* lvalue = (char*)xmalloc(equation - expr + 1);
405 xstrncpy(lvalue, expr, equation - expr + 1);
406 trim_trailing_ws(lvalue);
407
408 long number1;
409 if (!StrToInt(lvalue, number1))
410 fatalf("String is not a integer number: '%s'\n", lvalue);
411 long number2;
412 if (!StrToInt(rvalue, number2))
413 fatalf("String is not a integer number: '%s'\n", rvalue);
414
415 xfree(lvalue);
416 return number1 == number2;
417 }
418 fatalf("Unable to evaluate expression '%s'\n", expr);
419 return false; // this place cannot be reached
420 }
421
422 static int
423 parseOneConfigFile(const char *file_name, unsigned int depth)
424 {
425 FILE *fp = NULL;
426 const char *orig_cfg_filename = cfg_filename;
427 const int orig_config_lineno = config_lineno;
428 char *token = NULL;
429 char *tmp_line = NULL;
430 int tmp_line_len = 0;
431 int err_count = 0;
432 int is_pipe = 0;
433
434 debugs(3, DBG_IMPORTANT, "Processing Configuration File: " << file_name << " (depth " << depth << ")");
435 if (depth > 16) {
436 fatalf("WARNING: can't include %s: includes are nested too deeply (>16)!\n", file_name);
437 return 1;
438 }
439
440 if (file_name[0] == '!' || file_name[0] == '|') {
441 fp = popen(file_name + 1, "r");
442 is_pipe = 1;
443 } else {
444 fp = fopen(file_name, "r");
445 }
446
447 if (!fp) {
448 int xerrno = errno;
449 fatalf("Unable to open configuration file: %s: %s", file_name, xstrerr(xerrno));
450 }
451
452 #if _SQUID_WINDOWS_
453 setmode(fileno(fp), O_TEXT);
454 #endif
455
456 SetConfigFilename(file_name, bool(is_pipe));
457
458 memset(config_input_line, '\0', BUFSIZ);
459
460 config_lineno = 0;
461
462 std::vector<bool> if_states;
463 while (fgets(config_input_line, BUFSIZ, fp)) {
464 ++config_lineno;
465
466 if ((token = strchr(config_input_line, '\n')))
467 *token = '\0';
468
469 if ((token = strchr(config_input_line, '\r')))
470 *token = '\0';
471
472 // strip any prefix whitespace off the line.
473 const char *p = skip_ws(config_input_line);
474 if (config_input_line != p)
475 memmove(config_input_line, p, strlen(p)+1);
476
477 if (strncmp(config_input_line, "#line ", 6) == 0) {
478 static char new_file_name[1024];
479 static char *file;
480 static char new_lineno;
481 token = config_input_line + 6;
482 new_lineno = strtol(token, &file, 0) - 1;
483
484 if (file == token)
485 continue; /* Not a valid #line directive, may be a comment */
486
487 while (*file && xisspace((unsigned char) *file))
488 ++file;
489
490 if (*file) {
491 if (*file != '"')
492 continue; /* Not a valid #line directive, may be a comment */
493
494 xstrncpy(new_file_name, file + 1, sizeof(new_file_name));
495
496 if ((token = strchr(new_file_name, '"')))
497 *token = '\0';
498
499 SetConfigFilename(new_file_name, false);
500 }
501
502 config_lineno = new_lineno;
503 }
504
505 if (config_input_line[0] == '#')
506 continue;
507
508 if (config_input_line[0] == '\0')
509 continue;
510
511 const char* append = tmp_line_len ? skip_ws(config_input_line) : config_input_line;
512
513 size_t append_len = strlen(append);
514
515 tmp_line = (char*)xrealloc(tmp_line, tmp_line_len + append_len + 1);
516
517 strcpy(tmp_line + tmp_line_len, append);
518
519 tmp_line_len += append_len;
520
521 if (tmp_line[tmp_line_len-1] == '\\') {
522 debugs(3, 5, "parseConfigFile: tmp_line='" << tmp_line << "'");
523 tmp_line[--tmp_line_len] = '\0';
524 continue;
525 }
526
527 trim_trailing_ws(tmp_line);
528 ProcessMacros(tmp_line, tmp_line_len);
529 debugs(3, (opt_parse_cfg_only?1:5), "Processing: " << tmp_line);
530
531 if (const char* expr = FindStatement(tmp_line, "if")) {
532 if_states.push_back(EvalBoolExpr(expr)); // store last if-statement meaning
533 } else if (FindStatement(tmp_line, "endif")) {
534 if (!if_states.empty())
535 if_states.pop_back(); // remove last if-statement meaning
536 else
537 fatalf("'endif' without 'if'\n");
538 } else if (FindStatement(tmp_line, "else")) {
539 if (!if_states.empty())
540 if_states.back() = !if_states.back();
541 else
542 fatalf("'else' without 'if'\n");
543 } else if (if_states.empty() || if_states.back()) { // test last if-statement meaning if present
544 /* Handle includes here */
545 if (tmp_line_len >= 9 && strncmp(tmp_line, "include", 7) == 0 && xisspace(tmp_line[7])) {
546 err_count += parseManyConfigFiles(tmp_line + 8, depth + 1);
547 } else {
548 try {
549 if (!parse_line(tmp_line)) {
550 debugs(3, DBG_CRITICAL, ConfigParser::CurrentLocation() << ": unrecognized: '" << tmp_line << "'");
551 ++err_count;
552 }
553 } catch (...) {
554 // fatal for now
555 debugs(3, DBG_CRITICAL, "configuration error: " << CurrentException);
556 self_destruct();
557 }
558 }
559 }
560
561 safe_free(tmp_line);
562 tmp_line_len = 0;
563
564 }
565 if (!if_states.empty())
566 fatalf("if-statement without 'endif'\n");
567
568 if (is_pipe) {
569 int ret = pclose(fp);
570
571 if (ret != 0)
572 fatalf("parseConfigFile: '%s' failed with exit code %d\n", file_name, ret);
573 } else {
574 fclose(fp);
575 }
576
577 SetConfigFilename(orig_cfg_filename, false);
578 config_lineno = orig_config_lineno;
579
580 xfree(tmp_line);
581 return err_count;
582 }
583
584 static
585 int
586 parseConfigFileOrThrow(const char *file_name)
587 {
588 int err_count = 0;
589
590 debugs(5, 4, HERE);
591
592 configFreeMemory();
593
594 ACLMethodData::ThePurgeCount = 0;
595 default_all();
596
597 err_count = parseOneConfigFile(file_name, 0);
598
599 defaults_if_none();
600
601 defaults_postscriptum();
602
603 /*
604 * We must call configDoConfigure() before leave_suid() because
605 * configDoConfigure() is where we turn username strings into
606 * uid values.
607 */
608 configDoConfigure();
609
610 if (opt_send_signal == -1) {
611 Mgr::RegisterAction("config",
612 "Current Squid Configuration",
613 dump_config,
614 1, 1);
615 }
616
617 return err_count;
618 }
619
620 // TODO: Refactor main.cc to centrally handle (and report) all exceptions.
621 int
622 parseConfigFile(const char *file_name)
623 {
624 try {
625 return parseConfigFileOrThrow(file_name);
626 }
627 catch (const std::exception &ex) {
628 debugs(3, DBG_CRITICAL, "FATAL: bad configuration: " << ex.what());
629 self_destruct();
630 return 1; // not reached
631 }
632 }
633
634 static void
635 configDoConfigure(void)
636 {
637 Config2.clear();
638 /* init memory as early as possible */
639 memConfigure();
640 /* Sanity checks */
641
642 Config.cacheSwap.n_strands = 0; // no diskers by default
643 if (Config.cacheSwap.swapDirs == NULL) {
644 /* Memory-only cache probably in effect. */
645 /* turn off the cache rebuild delays... */
646 StoreController::store_dirs_rebuilding = 0;
647 } else if (InDaemonMode()) { // no diskers in non-daemon mode
648 for (int i = 0; i < Config.cacheSwap.n_configured; ++i) {
649 const RefCount<SwapDir> sd = Config.cacheSwap.swapDirs[i];
650 if (sd->needsDiskStrand())
651 sd->disker = Config.workers + (++Config.cacheSwap.n_strands);
652 }
653 }
654
655 if (Debug::rotateNumber < 0) {
656 Debug::rotateNumber = Config.Log.rotateNumber;
657 }
658
659 #if SIZEOF_OFF_T <= 4
660 if (Config.Store.maxObjectSize > 0x7FFF0000) {
661 debugs(3, DBG_CRITICAL, "WARNING: This Squid binary can not handle files larger than 2GB. Limiting maximum_object_size to just below 2GB");
662 Config.Store.maxObjectSize = 0x7FFF0000;
663 }
664 #endif
665
666 if (Config.Announce.period > 0) {
667 Config.onoff.announce = 1;
668 } else {
669 Config.Announce.period = 86400 * 365; /* one year */
670 Config.onoff.announce = 0;
671 }
672
673 if (Config.onoff.httpd_suppress_version_string)
674 visible_appname_string = (char *)appname_string;
675 else
676 visible_appname_string = (char const *)APP_FULLNAME;
677
678 if (Config.Program.redirect) {
679 if (Config.redirectChildren.n_max < 1) {
680 Config.redirectChildren.n_max = 0;
681 wordlistDestroy(&Config.Program.redirect);
682 }
683 }
684
685 if (Config.Program.store_id) {
686 if (Config.storeIdChildren.n_max < 1) {
687 Config.storeIdChildren.n_max = 0;
688 wordlistDestroy(&Config.Program.store_id);
689 }
690 }
691
692 if (Config.appendDomain)
693 if (*Config.appendDomain != '.')
694 fatal("append_domain must begin with a '.'");
695
696 if (Config.errHtmlText == NULL)
697 Config.errHtmlText = xstrdup(null_string);
698
699 #if !HAVE_SETRLIMIT || !defined(RLIMIT_NOFILE)
700 if (Config.max_filedescriptors > 0) {
701 debugs(0, DBG_IMPORTANT, "WARNING: max_filedescriptors disabled. Operating System setrlimit(RLIMIT_NOFILE) is missing.");
702 }
703 #elif USE_SELECT || USE_SELECT_WIN32
704 if (Config.max_filedescriptors > FD_SETSIZE) {
705 debugs(0, DBG_IMPORTANT, "WARNING: max_filedescriptors limited to " << FD_SETSIZE << " by select() algorithm.");
706 }
707 #endif
708
709 storeConfigure();
710
711 snprintf(ThisCache, sizeof(ThisCache), "%s (%s)",
712 uniqueHostname(),
713 visible_appname_string);
714
715 /*
716 * the extra space is for loop detection in client_side.c -- we search
717 * for substrings in the Via header.
718 */
719 snprintf(ThisCache2, sizeof(ThisCache), " %s (%s)",
720 uniqueHostname(),
721 visible_appname_string);
722
723 /* Use visible_hostname as default surrogate_id */
724 if (!Config.Accel.surrogate_id) {
725 const char *t = getMyHostname();
726 Config.Accel.surrogate_id = xstrdup( (t?t:"unset-id") );
727 }
728
729 if (!Config.udpMaxHitObjsz || Config.udpMaxHitObjsz > SQUID_UDP_SO_SNDBUF)
730 Config.udpMaxHitObjsz = SQUID_UDP_SO_SNDBUF;
731
732 if (Config.appendDomain)
733 Config.appendDomainLen = strlen(Config.appendDomain);
734 else
735 Config.appendDomainLen = 0;
736
737 if (Config.connect_retries > 10) {
738 debugs(0,DBG_CRITICAL, "WARNING: connect_retries cannot be larger than 10. Resetting to 10.");
739 Config.connect_retries = 10;
740 }
741
742 requirePathnameExists("MIME Config Table", Config.mimeTablePathname);
743 #if USE_UNLINKD
744
745 requirePathnameExists("unlinkd_program", Config.Program.unlinkd);
746 #endif
747 bool logDaemonUsed = false;
748 for (const auto *log = Config.Log.accesslogs; !logDaemonUsed && log; log = log->next)
749 logDaemonUsed = log->usesDaemon();
750 #if ICAP_CLIENT
751 for (const auto *log = Config.Log.icaplogs; !logDaemonUsed && log; log = log->next)
752 logDaemonUsed = log->usesDaemon();
753 #endif
754 if (logDaemonUsed)
755 requirePathnameExists("logfile_daemon", Log::TheConfig.logfile_daemon);
756
757 if (Config.Program.redirect)
758 requirePathnameExists("redirect_program", Config.Program.redirect->key);
759
760 if (Config.Program.store_id)
761 requirePathnameExists("store_id_program", Config.Program.store_id->key);
762
763 requirePathnameExists("Icon Directory", Config.icons.directory);
764
765 if (Config.errorDirectory)
766 requirePathnameExists("Error Directory", Config.errorDirectory);
767
768 #if USE_HTTP_VIOLATIONS
769
770 {
771 const RefreshPattern *R;
772
773 for (R = Config.Refresh; R; R = R->next) {
774 if (!R->flags.override_expire)
775 continue;
776
777 debugs(22, DBG_IMPORTANT, "WARNING: use of 'override-expire' in 'refresh_pattern' violates HTTP");
778
779 break;
780 }
781
782 for (R = Config.Refresh; R; R = R->next) {
783 if (!R->flags.override_lastmod)
784 continue;
785
786 debugs(22, DBG_IMPORTANT, "WARNING: use of 'override-lastmod' in 'refresh_pattern' violates HTTP");
787
788 break;
789 }
790
791 for (R = Config.Refresh; R; R = R->next) {
792 if (!R->flags.reload_into_ims)
793 continue;
794
795 debugs(22, DBG_IMPORTANT, "WARNING: use of 'reload-into-ims' in 'refresh_pattern' violates HTTP");
796
797 break;
798 }
799
800 for (R = Config.Refresh; R; R = R->next) {
801 if (!R->flags.ignore_reload)
802 continue;
803
804 debugs(22, DBG_IMPORTANT, "WARNING: use of 'ignore-reload' in 'refresh_pattern' violates HTTP");
805
806 break;
807 }
808
809 for (R = Config.Refresh; R; R = R->next) {
810 if (!R->flags.ignore_no_store)
811 continue;
812
813 debugs(22, DBG_IMPORTANT, "WARNING: use of 'ignore-no-store' in 'refresh_pattern' violates HTTP");
814
815 break;
816 }
817
818 for (R = Config.Refresh; R; R = R->next) {
819 if (!R->flags.ignore_private)
820 continue;
821
822 debugs(22, DBG_IMPORTANT, "WARNING: use of 'ignore-private' in 'refresh_pattern' violates HTTP");
823
824 break;
825 }
826 }
827 #endif
828 #if !USE_HTTP_VIOLATIONS
829 Config.onoff.via = 1;
830 #else
831
832 if (!Config.onoff.via)
833 debugs(22, DBG_IMPORTANT, "WARNING: HTTP requires the use of Via");
834
835 #endif
836
837 // we enable runtime PURGE checks if there is at least one PURGE method ACL
838 // TODO: replace with a dedicated "purge" ACL option?
839 Config2.onoff.enable_purge = (ACLMethodData::ThePurgeCount > 0);
840
841 if (geteuid() == 0) {
842 if (NULL != Config.effectiveUser) {
843
844 struct passwd *pwd = getpwnam(Config.effectiveUser);
845
846 if (NULL == pwd) {
847 /*
848 * Andres Kroonmaa <andre@online.ee>:
849 * Some getpwnam() implementations (Solaris?) require
850 * an available FD < 256 for opening a FILE* to the
851 * passwd file.
852 * DW:
853 * This should be safe at startup, but might still fail
854 * during reconfigure.
855 */
856 fatalf("getpwnam failed to find userid for effective user '%s'",
857 Config.effectiveUser);
858 return;
859 }
860
861 Config2.effectiveUserID = pwd->pw_uid;
862
863 Config2.effectiveGroupID = pwd->pw_gid;
864
865 #if HAVE_PUTENV
866 if (pwd->pw_dir && *pwd->pw_dir) {
867 // putenv() leaks by design; avoid leaks when nothing changes
868 static SBuf lastDir;
869 if (lastDir.isEmpty() || lastDir.cmp(pwd->pw_dir) != 0) {
870 lastDir = pwd->pw_dir;
871 int len = strlen(pwd->pw_dir) + 6;
872 char *env_str = (char *)xcalloc(len, 1);
873 snprintf(env_str, len, "HOME=%s", pwd->pw_dir);
874 putenv(env_str);
875 }
876 }
877 #endif
878 }
879 } else {
880 Config2.effectiveUserID = geteuid();
881 Config2.effectiveGroupID = getegid();
882 }
883
884 if (NULL != Config.effectiveGroup) {
885
886 struct group *grp = getgrnam(Config.effectiveGroup);
887
888 if (NULL == grp) {
889 fatalf("getgrnam failed to find groupid for effective group '%s'",
890 Config.effectiveGroup);
891 return;
892 }
893
894 Config2.effectiveGroupID = grp->gr_gid;
895 }
896
897 #if USE_OPENSSL
898 if (Config.ssl_client.foreignIntermediateCertsPath)
899 Ssl::loadSquidUntrusted(Config.ssl_client.foreignIntermediateCertsPath);
900 #endif
901
902 if (Security::ProxyOutgoingConfig.encryptTransport) {
903 debugs(3, DBG_IMPORTANT, "Initializing https:// proxy context");
904 Config.ssl_client.sslContext = Security::ProxyOutgoingConfig.createClientContext(false);
905 if (!Config.ssl_client.sslContext) {
906 #if USE_OPENSSL
907 fatal("ERROR: Could not initialize https:// proxy context");
908 #else
909 debugs(3, DBG_IMPORTANT, "ERROR: proxying https:// currently still requires --with-openssl");
910 #endif
911 }
912 #if USE_OPENSSL
913 Ssl::useSquidUntrusted(Config.ssl_client.sslContext.get());
914 #endif
915 }
916
917 for (CachePeer *p = Config.peers; p != NULL; p = p->next) {
918
919 // default value for ssldomain= is the peer host/IP
920 if (p->secure.sslDomain.isEmpty())
921 p->secure.sslDomain = p->host;
922
923 if (p->secure.encryptTransport) {
924 debugs(3, DBG_IMPORTANT, "Initializing cache_peer " << p->name << " TLS context");
925 p->sslContext = p->secure.createClientContext(true);
926 if (!p->sslContext) {
927 debugs(3, DBG_CRITICAL, "ERROR: Could not initialize cache_peer " << p->name << " TLS context");
928 self_destruct();
929 return;
930 }
931 }
932 }
933
934 for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
935 if (!s->secure.encryptTransport)
936 continue;
937 debugs(3, DBG_IMPORTANT, "Initializing " << AnyP::UriScheme(s->transport.protocol) << "_port " << s->s << " TLS contexts");
938 s->secure.initServerContexts(*s);
939 }
940
941 // prevent infinite fetch loops in the request parser
942 // due to buffer full but not enough data recived to finish parse
943 if (Config.maxRequestBufferSize <= Config.maxRequestHeaderSize) {
944 fatalf("Client request buffer of %u bytes cannot hold a request with %u bytes of headers." \
945 " Change client_request_buffer_max or request_header_max_size limits.",
946 (uint32_t)Config.maxRequestBufferSize, (uint32_t)Config.maxRequestHeaderSize);
947 }
948
949 /*
950 * Disable client side request pipelining if client_persistent_connections OFF.
951 * Waste of resources queueing any pipelined requests when the first will close the connection.
952 */
953 if (Config.pipeline_max_prefetch > 0 && !Config.onoff.client_pconns) {
954 debugs(3, DBG_PARSE_NOTE(DBG_IMPORTANT), "WARNING: pipeline_prefetch " << Config.pipeline_max_prefetch <<
955 " requires client_persistent_connections ON. Forced pipeline_prefetch 0.");
956 Config.pipeline_max_prefetch = 0;
957 }
958
959 #if USE_AUTH
960 /*
961 * disable client side request pipelining. There is a race with
962 * Negotiate and NTLM when the client sends a second request on an
963 * connection before the authenticate challenge is sent. With
964 * pipelining OFF, the client may fail to authenticate, but squid's
965 * state will be preserved.
966 */
967 if (Config.pipeline_max_prefetch > 0) {
968 Auth::SchemeConfig *nego = Auth::SchemeConfig::Find("Negotiate");
969 Auth::SchemeConfig *ntlm = Auth::SchemeConfig::Find("NTLM");
970 if ((nego && nego->active()) || (ntlm && ntlm->active())) {
971 debugs(3, DBG_PARSE_NOTE(DBG_IMPORTANT), "WARNING: pipeline_prefetch breaks NTLM and Negotiate authentication. Forced pipeline_prefetch 0.");
972 Config.pipeline_max_prefetch = 0;
973 }
974 }
975
976 for (auto &authSchemes : Auth::TheConfig.schemeLists) {
977 authSchemes.expand();
978 if (authSchemes.authConfigs.empty()) {
979 debugs(3, DBG_CRITICAL, "auth_schemes: at least one scheme name is required; got: " << authSchemes.rawSchemes);
980 self_destruct();
981 }
982 }
983 #endif
984 }
985
986 /** Parse a line containing an obsolete directive.
987 * To upgrade it where possible instead of just "Bungled config" for
988 * directives which cannot be marked as simply aliases of the some name.
989 * For example if the parameter order and content has changed.
990 * Or if the directive has been completely removed.
991 */
992 void
993 parse_obsolete(const char *name)
994 {
995 // Directives which have been radically changed rather than removed
996 if (!strcmp(name, "url_rewrite_concurrency")) {
997 int cval;
998 parse_int(&cval);
999 debugs(3, DBG_CRITICAL, "WARNING: url_rewrite_concurrency upgrade overriding url_rewrite_children settings.");
1000 Config.redirectChildren.concurrency = cval;
1001 }
1002
1003 if (!strcmp(name, "log_access")) {
1004 self_destruct();
1005 return;
1006 }
1007
1008 if (!strcmp(name, "log_icap")) {
1009 self_destruct();
1010 return;
1011 }
1012
1013 if (!strcmp(name, "ignore_ims_on_miss")) {
1014 // the replacement directive cache_revalidate_on_miss has opposite meanings for ON/OFF value
1015 // than the 2.7 directive. We need to parse and invert the configured value.
1016 int temp = 0;
1017 parse_onoff(&temp);
1018 Config.onoff.cache_miss_revalidate = !temp;
1019 }
1020
1021 if (!strncmp(name, "sslproxy_", 9)) {
1022 // the replacement directive tls_outgoing_options uses options instead of whole-line input
1023 SBuf tmp;
1024 if (!strcmp(name, "sslproxy_cafile"))
1025 tmp.append("cafile=");
1026 else if (!strcmp(name, "sslproxy_capath"))
1027 tmp.append("capath=");
1028 else if (!strcmp(name, "sslproxy_cipher"))
1029 tmp.append("cipher=");
1030 else if (!strcmp(name, "sslproxy_client_certificate"))
1031 tmp.append("cert=");
1032 else if (!strcmp(name, "sslproxy_client_key"))
1033 tmp.append("key=");
1034 else if (!strcmp(name, "sslproxy_flags"))
1035 tmp.append("flags=");
1036 else if (!strcmp(name, "sslproxy_options"))
1037 tmp.append("options=");
1038 else if (!strcmp(name, "sslproxy_version"))
1039 tmp.append("version=");
1040 else {
1041 debugs(3, DBG_CRITICAL, "ERROR: unknown directive: " << name);
1042 self_destruct();
1043 return;
1044 }
1045
1046 // add the value as unquoted-string because the old values did not support whitespace
1047 const char *token = ConfigParser::NextQuotedOrToEol();
1048 tmp.append(token, strlen(token));
1049 Security::ProxyOutgoingConfig.parse(tmp.c_str());
1050 }
1051 }
1052
1053 template <class MinimalUnit>
1054 static const char *
1055 TimeUnitToString()
1056 {
1057 const auto minUnit = MinimalUnit(1);
1058 if(minUnit == std::chrono::nanoseconds(1))
1059 return T_NANOSECOND_STR;
1060 else if (minUnit == std::chrono::microseconds(1))
1061 return T_MICROSECOND_STR;
1062 else if (minUnit == std::chrono::milliseconds(1))
1063 return T_MILLISECOND_STR;
1064 else {
1065 assert(minUnit >= std::chrono::seconds(1));
1066 return T_SECOND_STR;
1067 }
1068 }
1069
1070 /// Assigns 'ns' the number of nanoseconds corresponding to 'unitName'.
1071 /// \param MinimalUnit is a chrono duration type specifying the minimal
1072 /// allowed time unit.
1073 /// \returns true if unitName is correct and its time unit is not less
1074 /// than MinimalUnit.
1075 template <class MinimalUnit>
1076 static bool
1077 parseTimeUnit(const char *unitName, std::chrono::nanoseconds &ns)
1078 {
1079 if (!unitName)
1080 throw TexcHere("missing time unit");
1081
1082 if (!strncasecmp(unitName, T_NANOSECOND_STR, strlen(T_NANOSECOND_STR)))
1083 ns = std::chrono::nanoseconds(1);
1084 else if (!strncasecmp(unitName, T_MICROSECOND_STR, strlen(T_MICROSECOND_STR)))
1085 ns = std::chrono::microseconds(1);
1086 else if (!strncasecmp(unitName, T_MILLISECOND_STR, strlen(T_MILLISECOND_STR)))
1087 ns = std::chrono::milliseconds(1);
1088 else if (!strncasecmp(unitName, T_SECOND_STR, strlen(T_SECOND_STR)))
1089 ns = std::chrono::seconds(1);
1090 else if (!strncasecmp(unitName, T_MINUTE_STR, strlen(T_MINUTE_STR)))
1091 ns = std::chrono::minutes(1);
1092 else if (!strncasecmp(unitName, T_HOUR_STR, strlen(T_HOUR_STR)))
1093 ns = std::chrono::hours(1);
1094 else if (!strncasecmp(unitName, T_DAY_STR, strlen(T_DAY_STR)))
1095 ns = std::chrono::hours(24);
1096 else if (!strncasecmp(unitName, T_WEEK_STR, strlen(T_WEEK_STR)))
1097 ns = std::chrono::hours(24 * 7);
1098 else if (!strncasecmp(unitName, T_FORTNIGHT_STR, strlen(T_FORTNIGHT_STR)))
1099 ns = std::chrono::hours(24 * 14);
1100 else if (!strncasecmp(unitName, T_MONTH_STR, strlen(T_MONTH_STR)))
1101 ns = std::chrono::hours(24 * 30);
1102 else if (!strncasecmp(unitName, T_YEAR_STR, strlen(T_YEAR_STR)))
1103 ns = std::chrono::hours(static_cast<std::chrono::hours::rep>(HoursPerYear));
1104 else if (!strncasecmp(unitName, T_DECADE_STR, strlen(T_DECADE_STR)))
1105 ns = std::chrono::hours(static_cast<std::chrono::hours::rep>(HoursPerYear * 10));
1106 else
1107 return false;
1108
1109 if (ns < MinimalUnit(1)) {
1110 throw TexcHere(ToSBuf("time unit '", unitName, "' is too small to be used in this context, the minimal unit is ",
1111 TimeUnitToString<MinimalUnit>()));
1112 }
1113
1114 return true;
1115 }
1116
1117 static std::chrono::nanoseconds
1118 CheckTimeValue(const double value, const std::chrono::nanoseconds &unit)
1119 {
1120 if (value < 0)
1121 throw TexcHere("time must have a positive value");
1122
1123 const auto maxNanoseconds = std::chrono::nanoseconds::max().count();
1124 if (value > maxNanoseconds/static_cast<double>(unit.count())) {
1125 const auto maxYears = maxNanoseconds/(HoursPerYear*3600*1000000000);
1126 throw TexcHere(ToSBuf("time values cannot exceed ", maxYears, " years"));
1127 }
1128
1129 return std::chrono::nanoseconds(static_cast<std::chrono::nanoseconds::rep>(unit.count() * value));
1130 }
1131
1132 template <class TimeUnit>
1133 static TimeUnit
1134 FromNanoseconds(const std::chrono::nanoseconds &ns, const double parsedValue)
1135 {
1136 const auto result = std::chrono::duration_cast<TimeUnit>(ns);
1137 if (!result.count()) {
1138 throw TexcHere(ToSBuf("time value '", parsedValue,
1139 "' is too small to be used in this context, the minimal value is 1 ",
1140 TimeUnitToString<TimeUnit>()));
1141 }
1142 return result;
1143 }
1144
1145 /// Parses a time specification from the config file and
1146 /// returns the time as a chrono duration object of 'TimeUnit' type.
1147 template <class TimeUnit>
1148 static TimeUnit
1149 parseTimeLine()
1150 {
1151 const auto valueToken = ConfigParser::NextToken();
1152 if (!valueToken)
1153 throw TexcHere("cannot read a time value");
1154
1155 const auto parsedValue = xatof(valueToken);
1156
1157 if (parsedValue == 0)
1158 return TimeUnit::zero();
1159
1160 std::chrono::nanoseconds parsedUnitDuration;
1161
1162 const auto token = ConfigParser::PeekAtToken();
1163
1164 if (!parseTimeUnit<TimeUnit>(token, parsedUnitDuration))
1165 throw TexcHere(ToSBuf("unknown time unit '", token, "'"));
1166
1167 (void)ConfigParser::NextToken();
1168
1169 const auto nanoseconds = CheckTimeValue(parsedValue, parsedUnitDuration);
1170
1171 // validate precisions (time-units-small only)
1172 if (TimeUnit(1) <= std::chrono::microseconds(1)) {
1173 if (0 < nanoseconds.count() && nanoseconds.count() < 3) {
1174 debugs(3, DBG_PARSE_NOTE(DBG_IMPORTANT), ConfigParser::CurrentLocation() << ": WARNING: " <<
1175 "Squid time measurement precision is likely to be far worse than " <<
1176 "the nanosecond-level precision implied by the configured value: " << parsedValue << ' ' << token);
1177 }
1178 }
1179
1180 return FromNanoseconds<TimeUnit>(nanoseconds, parsedValue);
1181 }
1182
1183 static void
1184 parseBytesLine64(int64_t * bptr, const char *units)
1185 {
1186 char *token;
1187 double d;
1188 int64_t m;
1189 int64_t u;
1190
1191 if ((u = parseBytesUnits(units)) == 0) {
1192 self_destruct();
1193 return;
1194 }
1195
1196 if ((token = ConfigParser::NextToken()) == NULL) {
1197 self_destruct();
1198 return;
1199 }
1200
1201 if (strcmp(token, "none") == 0 || strcmp(token, "-1") == 0) {
1202 *bptr = -1;
1203 return;
1204 }
1205
1206 d = xatof(token);
1207
1208 m = u; /* default to 'units' if none specified */
1209
1210 if (0.0 == d)
1211 (void) 0;
1212 else if ((token = ConfigParser::NextToken()) == NULL)
1213 debugs(3, DBG_CRITICAL, "WARNING: No units on '" <<
1214 config_input_line << "', assuming " <<
1215 d << " " << units );
1216 else if ((m = parseBytesUnits(token)) == 0) {
1217 self_destruct();
1218 return;
1219 }
1220
1221 *bptr = static_cast<int64_t>(m * d / u);
1222
1223 if (static_cast<double>(*bptr) * 2 != (m * d / u) * 2) {
1224 debugs(3, DBG_CRITICAL, "ERROR: Invalid value '" <<
1225 d << " " << token << ": integer overflow (int64_t).");
1226 self_destruct();
1227 }
1228 }
1229
1230 static void
1231 parseBytesLine(size_t * bptr, const char *units)
1232 {
1233 char *token;
1234 double d;
1235 int m;
1236 int u;
1237
1238 if ((u = parseBytesUnits(units)) == 0) {
1239 self_destruct();
1240 return;
1241 }
1242
1243 if ((token = ConfigParser::NextToken()) == NULL) {
1244 self_destruct();
1245 return;
1246 }
1247
1248 if (strcmp(token, "none") == 0 || strcmp(token, "-1") == 0) {
1249 *bptr = static_cast<size_t>(-1);
1250 return;
1251 }
1252
1253 d = xatof(token);
1254
1255 m = u; /* default to 'units' if none specified */
1256
1257 if (0.0 == d)
1258 (void) 0;
1259 else if ((token = ConfigParser::NextToken()) == NULL)
1260 debugs(3, DBG_CRITICAL, "WARNING: No units on '" <<
1261 config_input_line << "', assuming " <<
1262 d << " " << units );
1263 else if ((m = parseBytesUnits(token)) == 0) {
1264 self_destruct();
1265 return;
1266 }
1267
1268 *bptr = static_cast<size_t>(m * d / u);
1269
1270 if (static_cast<double>(*bptr) * 2 != (m * d / u) * 2) {
1271 debugs(3, DBG_CRITICAL, "ERROR: Invalid value '" <<
1272 d << " " << token << ": integer overflow (size_t).");
1273 self_destruct();
1274 }
1275 }
1276
1277 static void
1278 parseBytesLineSigned(ssize_t * bptr, const char *units)
1279 {
1280 char *token;
1281 double d;
1282 int m;
1283 int u;
1284
1285 if ((u = parseBytesUnits(units)) == 0) {
1286 self_destruct();
1287 return;
1288 }
1289
1290 if ((token = ConfigParser::NextToken()) == NULL) {
1291 self_destruct();
1292 return;
1293 }
1294
1295 if (strcmp(token, "none") == 0 || token[0] == '-' /* -N */) {
1296 *bptr = -1;
1297 return;
1298 }
1299
1300 d = xatof(token);
1301
1302 m = u; /* default to 'units' if none specified */
1303
1304 if (0.0 == d)
1305 (void) 0;
1306 else if ((token = ConfigParser::NextToken()) == NULL)
1307 debugs(3, DBG_CRITICAL, "WARNING: No units on '" <<
1308 config_input_line << "', assuming " <<
1309 d << " " << units );
1310 else if ((m = parseBytesUnits(token)) == 0) {
1311 self_destruct();
1312 return;
1313 }
1314
1315 *bptr = static_cast<ssize_t>(m * d / u);
1316
1317 if (static_cast<double>(*bptr) * 2 != (m * d / u) * 2) {
1318 debugs(3, DBG_CRITICAL, "ERROR: Invalid value '" <<
1319 d << " " << token << ": integer overflow (ssize_t).");
1320 self_destruct();
1321 }
1322 }
1323
1324 /**
1325 * Parse bytes from a string.
1326 * Similar to the parseBytesLine function but parses the string value instead of
1327 * the current token value.
1328 */
1329 void
1330 parseBytesOptionValue(size_t * bptr, const char *units, char const * value)
1331 {
1332 int u;
1333 if ((u = parseBytesUnits(units)) == 0) {
1334 self_destruct();
1335 return;
1336 }
1337
1338 // Find number from string beginning.
1339 char const * number_begin = value;
1340 char const * number_end = value;
1341
1342 while ((*number_end >= '0' && *number_end <= '9')) {
1343 ++number_end;
1344 }
1345
1346 String number;
1347 number.assign(number_begin, number_end - number_begin);
1348
1349 int d = xatoi(number.termedBuf());
1350 int m;
1351 if ((m = parseBytesUnits(number_end)) == 0) {
1352 self_destruct();
1353 return;
1354 }
1355
1356 *bptr = static_cast<size_t>(m * d / u);
1357 if (static_cast<double>(*bptr) * 2 != (m * d / u) * 2)
1358 self_destruct();
1359 }
1360
1361 static size_t
1362 parseBytesUnits(const char *unit)
1363 {
1364 if (!strncasecmp(unit, B_BYTES_STR, strlen(B_BYTES_STR)))
1365 return 1;
1366
1367 if (!strncasecmp(unit, B_KBYTES_STR, strlen(B_KBYTES_STR)))
1368 return 1 << 10;
1369
1370 if (!strncasecmp(unit, B_MBYTES_STR, strlen(B_MBYTES_STR)))
1371 return 1 << 20;
1372
1373 if (!strncasecmp(unit, B_GBYTES_STR, strlen(B_GBYTES_STR)))
1374 return 1 << 30;
1375
1376 debugs(3, DBG_CRITICAL, "WARNING: Unknown bytes unit '" << unit << "'");
1377
1378 return 0;
1379 }
1380
1381 static void
1382 parse_SBufList(SBufList * list)
1383 {
1384 while (char *token = ConfigParser::NextQuotedToken())
1385 list->push_back(SBuf(token));
1386 }
1387
1388 // just dump a list, no directive name
1389 static void
1390 dump_SBufList(StoreEntry * entry, const SBufList &words)
1391 {
1392 for (const auto &i : words) {
1393 entry->append(i.rawContent(), i.length());
1394 entry->append(" ",1);
1395 }
1396 entry->append("\n",1);
1397 }
1398
1399 // dump a SBufList type directive with name
1400 static void
1401 dump_SBufList(StoreEntry * entry, const char *name, SBufList &list)
1402 {
1403 if (!list.empty()) {
1404 entry->append(name, strlen(name));
1405 entry->append(" ", 1);
1406 dump_SBufList(entry, list);
1407 }
1408 }
1409
1410 static void
1411 free_SBufList(SBufList *list)
1412 {
1413 if (list)
1414 list->clear();
1415 }
1416
1417 static void
1418 dump_acl(StoreEntry * entry, const char *name, ACL * ae)
1419 {
1420 while (ae != NULL) {
1421 debugs(3, 3, "dump_acl: " << name << " " << ae->name);
1422 storeAppendPrintf(entry, "%s %s %s ",
1423 name,
1424 ae->name,
1425 ae->typeString());
1426 SBufList tail;
1427 tail.splice(tail.end(), ae->dumpOptions());
1428 tail.splice(tail.end(), ae->dump()); // ACL parameters
1429 dump_SBufList(entry, tail);
1430 ae = ae->next;
1431 }
1432 }
1433
1434 static void
1435 parse_acl(ACL ** ae)
1436 {
1437 ACL::ParseAclLine(LegacyParser, ae);
1438 }
1439
1440 static void
1441 free_acl(ACL ** ae)
1442 {
1443 aclDestroyAcls(ae);
1444 }
1445
1446 void
1447 dump_acl_list(StoreEntry * entry, ACLList * head)
1448 {
1449 dump_SBufList(entry, head->dump());
1450 }
1451
1452 void
1453 dump_acl_access(StoreEntry * entry, const char *name, acl_access * head)
1454 {
1455 if (head)
1456 dump_SBufList(entry, head->treeDump(name, &Acl::AllowOrDeny));
1457 }
1458
1459 static void
1460 parse_acl_access(acl_access ** head)
1461 {
1462 aclParseAccessLine(cfg_directive, LegacyParser, head);
1463 }
1464
1465 static void
1466 free_acl_access(acl_access ** head)
1467 {
1468 aclDestroyAccessList(head);
1469 }
1470
1471 static void
1472 dump_address(StoreEntry * entry, const char *name, Ip::Address &addr)
1473 {
1474 char buf[MAX_IPSTRLEN];
1475 storeAppendPrintf(entry, "%s %s\n", name, addr.toStr(buf,MAX_IPSTRLEN) );
1476 }
1477
1478 static void
1479 parse_address(Ip::Address *addr)
1480 {
1481 char *token = ConfigParser::NextToken();
1482
1483 if (!token) {
1484 self_destruct();
1485 return;
1486 }
1487
1488 if (!strcmp(token,"any_addr"))
1489 addr->setAnyAddr();
1490 else if ( (!strcmp(token,"no_addr")) || (!strcmp(token,"full_mask")) )
1491 addr->setNoAddr();
1492 else if ( (*addr = token) ) // try parse numeric/IPA
1493 (void) 0;
1494 else if (addr->GetHostByName(token)) // do not use ipcache
1495 (void) 0;
1496 else { // not an IP and not a hostname
1497 debugs(3, DBG_CRITICAL, "FATAL: invalid IP address or domain name '" << token << "'");
1498 self_destruct();
1499 }
1500 }
1501
1502 static void
1503 free_address(Ip::Address *addr)
1504 {
1505 addr->setEmpty();
1506 }
1507
1508 static void
1509 dump_acl_address(StoreEntry * entry, const char *name, Acl::Address * head)
1510 {
1511 char buf[MAX_IPSTRLEN];
1512
1513 for (Acl::Address *l = head; l; l = l->next) {
1514 if (!l->addr.isAnyAddr())
1515 storeAppendPrintf(entry, "%s %s", name, l->addr.toStr(buf,MAX_IPSTRLEN));
1516 else
1517 storeAppendPrintf(entry, "%s autoselect", name);
1518
1519 dump_acl_list(entry, l->aclList);
1520
1521 storeAppendPrintf(entry, "\n");
1522 }
1523 }
1524
1525 static void
1526 parse_acl_address(Acl::Address ** head)
1527 {
1528 Acl::Address *l = new Acl::Address;
1529 parse_address(&l->addr);
1530 aclParseAclList(LegacyParser, &l->aclList, l->addr);
1531
1532 Acl::Address **tail = head;
1533 while (*tail)
1534 tail = &(*tail)->next;
1535
1536 *tail = l;
1537 }
1538
1539 static void
1540 free_acl_address(Acl::Address ** head)
1541 {
1542 delete *head;
1543 *head = NULL;
1544 }
1545
1546 static void
1547 dump_acl_tos(StoreEntry * entry, const char *name, acl_tos * head)
1548 {
1549 acl_tos *l;
1550
1551 for (l = head; l; l = l->next) {
1552 if (l->tos > 0)
1553 storeAppendPrintf(entry, "%s 0x%02X", name, l->tos);
1554 else
1555 storeAppendPrintf(entry, "%s none", name);
1556
1557 dump_acl_list(entry, l->aclList);
1558
1559 storeAppendPrintf(entry, "\n");
1560 }
1561 }
1562
1563 static void
1564 parse_acl_tos(acl_tos ** head)
1565 {
1566 unsigned int tos; /* Initially uint for strtoui. Casted to tos_t before return */
1567 char *token = ConfigParser::NextToken();
1568
1569 if (!token) {
1570 self_destruct();
1571 return;
1572 }
1573
1574 if (!xstrtoui(token, NULL, &tos, 0, std::numeric_limits<tos_t>::max())) {
1575 self_destruct();
1576 return;
1577 }
1578
1579 const unsigned int chTos = tos & 0xFC;
1580 if (chTos != tos) {
1581 debugs(3, DBG_PARSE_NOTE(DBG_IMPORTANT), "WARNING: Tos value '" << tos << "' adjusted to '" << chTos << "'");
1582 tos = chTos;
1583 }
1584
1585 acl_tos *l = new acl_tos;
1586
1587 l->tos = (tos_t)tos;
1588
1589 aclParseAclList(LegacyParser, &l->aclList, token);
1590
1591 acl_tos **tail = head; /* sane name below */
1592 while (*tail)
1593 tail = &(*tail)->next;
1594
1595 *tail = l;
1596 }
1597
1598 static void
1599 free_acl_tos(acl_tos ** head)
1600 {
1601 delete *head;
1602 *head = NULL;
1603 }
1604
1605 #if SO_MARK && USE_LIBCAP
1606
1607 static void
1608 dump_acl_nfmark(StoreEntry * entry, const char *name, acl_nfmark * head)
1609 {
1610 for (acl_nfmark *l = head; l; l = l->next) {
1611 storeAppendPrintf(entry, "%s %s", name, ToSBuf(l->markConfig).c_str());
1612
1613 dump_acl_list(entry, l->aclList);
1614
1615 storeAppendPrintf(entry, "\n");
1616 }
1617 }
1618
1619 static void
1620 parse_acl_nfmark(acl_nfmark ** head)
1621 {
1622 SBuf token(ConfigParser::NextToken());
1623 const auto mc = Ip::NfMarkConfig::Parse(token);
1624
1625 // Packet marking directives should not allow to use masks.
1626 const auto pkt_dirs = {"mark_client_packet", "clientside_mark", "tcp_outgoing_mark"};
1627 if (mc.hasMask() && std::find(pkt_dirs.begin(), pkt_dirs.end(), cfg_directive) != pkt_dirs.end())
1628 throw TexcHere(ToSBuf("'", cfg_directive, "' does not support masked marks"));
1629
1630 acl_nfmark *l = new acl_nfmark;
1631 l->markConfig = mc;
1632
1633 aclParseAclList(LegacyParser, &l->aclList, token.c_str());
1634
1635 acl_nfmark **tail = head; /* sane name below */
1636 while (*tail)
1637 tail = &(*tail)->next;
1638
1639 *tail = l;
1640 }
1641
1642 static void
1643 free_acl_nfmark(acl_nfmark ** head)
1644 {
1645 delete *head;
1646 *head = NULL;
1647 }
1648 #endif /* SO_MARK */
1649
1650 static void
1651 dump_acl_b_size_t(StoreEntry * entry, const char *name, AclSizeLimit * head)
1652 {
1653 for (AclSizeLimit *l = head; l; l = l->next) {
1654 if (l->size != -1)
1655 storeAppendPrintf(entry, "%s %d %s\n", name, (int) l->size, B_BYTES_STR);
1656 else
1657 storeAppendPrintf(entry, "%s none", name);
1658
1659 dump_acl_list(entry, l->aclList);
1660
1661 storeAppendPrintf(entry, "\n");
1662 }
1663 }
1664
1665 static void
1666 parse_acl_b_size_t(AclSizeLimit ** head)
1667 {
1668 AclSizeLimit *l = new AclSizeLimit;
1669
1670 parse_b_int64_t(&l->size);
1671
1672 aclParseAclList(LegacyParser, &l->aclList, l->size);
1673
1674 AclSizeLimit **tail = head; /* sane name below */
1675 while (*tail)
1676 tail = &(*tail)->next;
1677
1678 *tail = l;
1679 }
1680
1681 static void
1682 free_acl_b_size_t(AclSizeLimit ** head)
1683 {
1684 delete *head;
1685 *head = NULL;
1686 }
1687
1688 #if USE_DELAY_POOLS
1689
1690 #include "DelayConfig.h"
1691 #include "DelayPools.h"
1692 /* do nothing - free_delay_pool_count is the magic free function.
1693 * this is why delay_pool_count isn't just marked TYPE: u_short
1694 */
1695 #define free_delay_pool_class(X)
1696 #define free_delay_pool_access(X)
1697 #define free_delay_pool_rates(X)
1698 #define dump_delay_pool_class(X, Y, Z)
1699 #define dump_delay_pool_access(X, Y, Z)
1700 #define dump_delay_pool_rates(X, Y, Z)
1701
1702 static void
1703 free_delay_pool_count(DelayConfig * cfg)
1704 {
1705 cfg->freePoolCount();
1706 }
1707
1708 static void
1709 dump_delay_pool_count(StoreEntry * entry, const char *name, DelayConfig &cfg)
1710 {
1711 cfg.dumpPoolCount (entry, name);
1712 }
1713
1714 static void
1715 parse_delay_pool_count(DelayConfig * cfg)
1716 {
1717 cfg->parsePoolCount();
1718 }
1719
1720 static void
1721 parse_delay_pool_class(DelayConfig * cfg)
1722 {
1723 cfg->parsePoolClass();
1724 }
1725
1726 static void
1727 parse_delay_pool_rates(DelayConfig * cfg)
1728 {
1729 cfg->parsePoolRates();
1730 }
1731
1732 static void
1733 parse_delay_pool_access(DelayConfig * cfg)
1734 {
1735 cfg->parsePoolAccess(LegacyParser);
1736 }
1737
1738 #endif
1739
1740 #if USE_DELAY_POOLS
1741 #include "ClientDelayConfig.h"
1742 /* do nothing - free_client_delay_pool_count is the magic free function.
1743 * this is why client_delay_pool_count isn't just marked TYPE: u_short
1744 */
1745
1746 #define free_client_delay_pool_access(X)
1747 #define free_client_delay_pool_rates(X)
1748 #define dump_client_delay_pool_access(X, Y, Z)
1749 #define dump_client_delay_pool_rates(X, Y, Z)
1750
1751 static void
1752 free_client_delay_pool_count(ClientDelayConfig * cfg)
1753 {
1754 cfg->freePools();
1755 }
1756
1757 static void
1758 dump_client_delay_pool_count(StoreEntry * entry, const char *name, ClientDelayConfig &cfg)
1759 {
1760 cfg.dumpPoolCount (entry, name);
1761 }
1762
1763 static void
1764 parse_client_delay_pool_count(ClientDelayConfig * cfg)
1765 {
1766 cfg->parsePoolCount();
1767 }
1768
1769 static void
1770 parse_client_delay_pool_rates(ClientDelayConfig * cfg)
1771 {
1772 cfg->parsePoolRates();
1773 }
1774
1775 static void
1776 parse_client_delay_pool_access(ClientDelayConfig * cfg)
1777 {
1778 cfg->parsePoolAccess(LegacyParser);
1779 }
1780 #endif
1781
1782 #if USE_HTTP_VIOLATIONS
1783 static void
1784 dump_http_header_access(StoreEntry * entry, const char *name, const HeaderManglers *manglers)
1785 {
1786 if (manglers)
1787 manglers->dumpAccess(entry, name);
1788 }
1789
1790 static void
1791 parse_http_header_access(HeaderManglers **pm)
1792 {
1793 char *t = NULL;
1794
1795 if ((t = ConfigParser::NextToken()) == NULL) {
1796 debugs(3, DBG_CRITICAL, "" << cfg_filename << " line " << config_lineno << ": " << config_input_line);
1797 debugs(3, DBG_CRITICAL, "parse_http_header_access: missing header name.");
1798 return;
1799 }
1800
1801 if (!*pm)
1802 *pm = new HeaderManglers;
1803 HeaderManglers *manglers = *pm;
1804 headerMangler *mangler = manglers->track(t);
1805 assert(mangler);
1806
1807 std::string directive = "http_header_access ";
1808 directive += t;
1809 aclParseAccessLine(directive.c_str(), LegacyParser, &mangler->access_list);
1810 }
1811
1812 static void
1813 free_HeaderManglers(HeaderManglers **pm)
1814 {
1815 // we delete the entire http_header_* mangler configuration at once
1816 if (const HeaderManglers *manglers = *pm) {
1817 delete manglers;
1818 *pm = NULL;
1819 }
1820 }
1821
1822 static void
1823 dump_http_header_replace(StoreEntry * entry, const char *name, const HeaderManglers *manglers)
1824 {
1825 if (manglers)
1826 manglers->dumpReplacement(entry, name);
1827 }
1828
1829 static void
1830 parse_http_header_replace(HeaderManglers **pm)
1831 {
1832 char *t = NULL;
1833
1834 if ((t = ConfigParser::NextToken()) == NULL) {
1835 debugs(3, DBG_CRITICAL, "" << cfg_filename << " line " << config_lineno << ": " << config_input_line);
1836 debugs(3, DBG_CRITICAL, "parse_http_header_replace: missing header name.");
1837 return;
1838 }
1839
1840 const char *value = ConfigParser::NextQuotedOrToEol();
1841
1842 if (!*pm)
1843 *pm = new HeaderManglers;
1844 HeaderManglers *manglers = *pm;
1845 manglers->setReplacement(t, value);
1846 }
1847
1848 #endif
1849
1850 static void
1851 dump_cachedir(StoreEntry * entry, const char *name, const Store::DiskConfig &swap)
1852 {
1853 SwapDir *s;
1854 int i;
1855 assert (entry);
1856
1857 for (i = 0; i < swap.n_configured; ++i) {
1858 s = dynamic_cast<SwapDir *>(swap.swapDirs[i].getRaw());
1859 if (!s) continue;
1860 storeAppendPrintf(entry, "%s %s %s", name, s->type(), s->path);
1861 s->dump(*entry);
1862 storeAppendPrintf(entry, "\n");
1863 }
1864 }
1865
1866 static int
1867 check_null_string(char *s)
1868 {
1869 return s == NULL;
1870 }
1871
1872 #if USE_AUTH
1873 static void
1874 parse_authparam(Auth::ConfigVector * config)
1875 {
1876 char *type_str = ConfigParser::NextToken();
1877 if (!type_str) {
1878 self_destruct();
1879 return;
1880 }
1881
1882 char *param_str = ConfigParser::NextToken();
1883 if (!param_str) {
1884 self_destruct();
1885 return;
1886 }
1887
1888 /* find a configuration for the scheme in the currently parsed configs... */
1889 Auth::SchemeConfig *schemeCfg = Auth::SchemeConfig::Find(type_str);
1890
1891 if (schemeCfg == NULL) {
1892 /* Create a configuration based on the scheme info */
1893 Auth::Scheme::Pointer theScheme = Auth::Scheme::Find(type_str);
1894
1895 if (theScheme == NULL) {
1896 debugs(3, DBG_CRITICAL, "Parsing Config File: Unknown authentication scheme '" << type_str << "'.");
1897 self_destruct();
1898 return;
1899 }
1900
1901 config->push_back(theScheme->createConfig());
1902 schemeCfg = Auth::SchemeConfig::Find(type_str);
1903 if (schemeCfg == NULL) {
1904 debugs(3, DBG_CRITICAL, "Parsing Config File: Corruption configuring authentication scheme '" << type_str << "'.");
1905 self_destruct();
1906 return;
1907 }
1908 }
1909
1910 schemeCfg->parse(schemeCfg, config->size(), param_str);
1911 }
1912
1913 static void
1914 free_authparam(Auth::ConfigVector * cfg)
1915 {
1916 /* Wipe the Auth globals and Detach/Destruct component config + state. */
1917 cfg->clear();
1918
1919 /* on reconfigure initialize new auth schemes for the new config. */
1920 if (reconfiguring) {
1921 Auth::Init();
1922 }
1923 }
1924
1925 static void
1926 dump_authparam(StoreEntry * entry, const char *name, Auth::ConfigVector cfg)
1927 {
1928 for (auto *scheme : cfg)
1929 scheme->dump(entry, name, scheme);
1930 }
1931
1932 static void
1933 parse_AuthSchemes(acl_access **authSchemes)
1934 {
1935 const char *tok = ConfigParser::NextQuotedToken();
1936 if (!tok) {
1937 debugs(29, DBG_CRITICAL, "FATAL: auth_schemes missing the parameter");
1938 self_destruct();
1939 return;
1940 }
1941 Auth::TheConfig.schemeLists.emplace_back(tok, ConfigParser::LastTokenWasQuoted());
1942 const auto action = Acl::Answer(ACCESS_ALLOWED, Auth::TheConfig.schemeLists.size() - 1);
1943 ParseAclWithAction(authSchemes, action, "auth_schemes");
1944 }
1945
1946 static void
1947 free_AuthSchemes(acl_access **authSchemes)
1948 {
1949 Auth::TheConfig.schemeLists.clear();
1950 free_acl_access(authSchemes);
1951 }
1952
1953 static void
1954 dump_AuthSchemes(StoreEntry *entry, const char *name, acl_access *authSchemes)
1955 {
1956 if (authSchemes)
1957 dump_SBufList(entry, authSchemes->treeDump(name, [](const Acl::Answer &action) {
1958 return Auth::TheConfig.schemeLists.at(action.kind).rawSchemes;
1959 }));
1960 }
1961
1962 #endif /* USE_AUTH */
1963
1964 static void
1965 ParseAclWithAction(acl_access **access, const Acl::Answer &action, const char *desc, ACL *acl)
1966 {
1967 assert(access);
1968 SBuf name;
1969 if (!*access) {
1970 *access = new Acl::Tree;
1971 name.Printf("(%s rules)", desc);
1972 (*access)->context(name.c_str(), config_input_line);
1973 }
1974 Acl::AndNode *rule = new Acl::AndNode;
1975 name.Printf("(%s rule)", desc);
1976 rule->context(name.c_str(), config_input_line);
1977 acl ? rule->add(acl) : rule->lineParse();
1978 (*access)->add(rule, action);
1979 }
1980
1981 /* TODO: just return the object, the # is irrelevant */
1982 static int
1983 find_fstype(char *type)
1984 {
1985 for (size_t i = 0; i < StoreFileSystem::FileSystems().size(); ++i)
1986 if (strcasecmp(type, StoreFileSystem::FileSystems().at(i)->type()) == 0)
1987 return (int)i;
1988
1989 return (-1);
1990 }
1991
1992 static void
1993 parse_cachedir(Store::DiskConfig *swap)
1994 {
1995 char *type_str = ConfigParser::NextToken();
1996 if (!type_str) {
1997 self_destruct();
1998 return;
1999 }
2000
2001 char *path_str = ConfigParser::NextToken();
2002 if (!path_str) {
2003 self_destruct();
2004 return;
2005 }
2006
2007 int fs = find_fstype(type_str);
2008 if (fs < 0) {
2009 debugs(3, DBG_PARSE_NOTE(DBG_IMPORTANT), "ERROR: This proxy does not support the '" << type_str << "' cache type. Ignoring.");
2010 return;
2011 }
2012
2013 /* reconfigure existing dir */
2014
2015 RefCount<SwapDir> sd;
2016 for (int i = 0; i < swap->n_configured; ++i) {
2017 assert (swap->swapDirs[i].getRaw());
2018
2019 if ((strcasecmp(path_str, dynamic_cast<SwapDir *>(swap->swapDirs[i].getRaw())->path)) == 0) {
2020 /* this is specific to on-fs Stores. The right
2021 * way to handle this is probably to have a mapping
2022 * from paths to stores, and have on-fs stores
2023 * register with that, and lookip in that in their
2024 * own setup logic. RBC 20041225. TODO.
2025 */
2026
2027 sd = dynamic_cast<SwapDir *>(swap->swapDirs[i].getRaw());
2028
2029 if (strcmp(sd->type(), StoreFileSystem::FileSystems().at(fs)->type()) != 0) {
2030 debugs(3, DBG_CRITICAL, "ERROR: Can't change type of existing cache_dir " <<
2031 sd->type() << " " << sd->path << " to " << type_str << ". Restart required");
2032 return;
2033 }
2034
2035 sd->reconfigure();
2036 return;
2037 }
2038 }
2039
2040 /* new cache_dir */
2041 if (swap->n_configured > 63) {
2042 /* 7 bits, signed */
2043 debugs(3, DBG_CRITICAL, "WARNING: There is a fixed maximum of 63 cache_dir entries Squid can handle.");
2044 debugs(3, DBG_CRITICAL, "WARNING: '" << path_str << "' is one to many.");
2045 self_destruct();
2046 return;
2047 }
2048
2049 allocate_new_swapdir(swap);
2050
2051 swap->swapDirs[swap->n_configured] = StoreFileSystem::FileSystems().at(fs)->createSwapDir();
2052
2053 sd = dynamic_cast<SwapDir *>(swap->swapDirs[swap->n_configured].getRaw());
2054
2055 /* parse the FS parameters and options */
2056 sd->parse(swap->n_configured, path_str);
2057
2058 ++swap->n_configured;
2059 }
2060
2061 static const char *
2062 peer_type_str(const peer_t type)
2063 {
2064 const char * result;
2065
2066 switch (type) {
2067
2068 case PEER_PARENT:
2069 result = "parent";
2070 break;
2071
2072 case PEER_SIBLING:
2073 result = "sibling";
2074 break;
2075
2076 case PEER_MULTICAST:
2077 result = "multicast";
2078 break;
2079
2080 default:
2081 result = "unknown";
2082 break;
2083 }
2084
2085 return result;
2086 }
2087
2088 static void
2089 dump_peer(StoreEntry * entry, const char *name, CachePeer * p)
2090 {
2091 NeighborTypeDomainList *t;
2092 LOCAL_ARRAY(char, xname, 128);
2093
2094 while (p != NULL) {
2095 storeAppendPrintf(entry, "%s %s %s %d %d name=%s",
2096 name,
2097 p->host,
2098 neighborTypeStr(p),
2099 p->http_port,
2100 p->icp.port,
2101 p->name);
2102 dump_peer_options(entry, p);
2103
2104 if (p->access) {
2105 snprintf(xname, 128, "cache_peer_access %s", p->name);
2106 dump_acl_access(entry, xname, p->access);
2107 }
2108
2109 for (t = p->typelist; t; t = t->next) {
2110 storeAppendPrintf(entry, "neighbor_type_domain %s %s %s\n",
2111 p->host,
2112 peer_type_str(t->type),
2113 t->domain);
2114 }
2115
2116 p = p->next;
2117 }
2118 }
2119
2120 /**
2121 * utility function to prevent getservbyname() being called with a numeric value
2122 * on Windows at least it returns garage results.
2123 */
2124 static bool
2125 isUnsignedNumeric(const char *str, size_t len)
2126 {
2127 if (len < 1) return false;
2128
2129 for (; len >0 && *str; ++str, --len) {
2130 if (! isdigit(*str))
2131 return false;
2132 }
2133 return true;
2134 }
2135
2136 /**
2137 \param proto 'tcp' or 'udp' for protocol
2138 \returns Port the named service is supposed to be listening on.
2139 */
2140 static unsigned short
2141 GetService(const char *proto)
2142 {
2143 struct servent *port = NULL;
2144 /** Parses a port number or service name from the squid.conf */
2145 char *token = ConfigParser::NextToken();
2146 if (token == NULL) {
2147 self_destruct();
2148 return 0; /* NEVER REACHED */
2149 }
2150 /** Returns either the service port number from /etc/services */
2151 if ( !isUnsignedNumeric(token, strlen(token)) )
2152 port = getservbyname(token, proto);
2153 if (port != NULL) {
2154 return ntohs((unsigned short)port->s_port);
2155 }
2156 /** Or a numeric translation of the config text. */
2157 return xatos(token);
2158 }
2159
2160 /**
2161 \returns Port the named TCP service is supposed to be listening on.
2162 \copydoc GetService(const char *proto)
2163 */
2164 inline unsigned short
2165 GetTcpService(void)
2166 {
2167 return GetService("tcp");
2168 }
2169
2170 /**
2171 \returns Port the named UDP service is supposed to be listening on.
2172 \copydoc GetService(const char *proto)
2173 */
2174 inline unsigned short
2175 GetUdpService(void)
2176 {
2177 return GetService("udp");
2178 }
2179
2180 static void
2181 parse_peer(CachePeer ** head)
2182 {
2183 char *host_str = ConfigParser::NextToken();
2184 if (!host_str) {
2185 self_destruct();
2186 return;
2187 }
2188
2189 char *token = ConfigParser::NextToken();
2190 if (!token) {
2191 self_destruct();
2192 return;
2193 }
2194
2195 CachePeer *p = new CachePeer;
2196 p->host = xstrdup(host_str);
2197 Tolower(p->host);
2198 p->name = xstrdup(host_str);
2199 p->type = parseNeighborType(token);
2200
2201 if (p->type == PEER_MULTICAST) {
2202 p->options.no_digest = true;
2203 p->options.no_netdb_exchange = true;
2204 }
2205
2206 p->http_port = GetTcpService();
2207
2208 if (!p->http_port) {
2209 delete p;
2210 self_destruct();
2211 return;
2212 }
2213
2214 p->icp.port = GetUdpService();
2215
2216 while ((token = ConfigParser::NextToken())) {
2217 if (!strcmp(token, "proxy-only")) {
2218 p->options.proxy_only = true;
2219 } else if (!strcmp(token, "no-query")) {
2220 p->options.no_query = true;
2221 } else if (!strcmp(token, "background-ping")) {
2222 p->options.background_ping = true;
2223 } else if (!strcmp(token, "no-digest")) {
2224 p->options.no_digest = true;
2225 } else if (!strcmp(token, "no-tproxy")) {
2226 p->options.no_tproxy = true;
2227 } else if (!strcmp(token, "multicast-responder")) {
2228 p->options.mcast_responder = true;
2229 #if PEER_MULTICAST_SIBLINGS
2230 } else if (!strcmp(token, "multicast-siblings")) {
2231 p->options.mcast_siblings = true;
2232 #endif
2233 } else if (!strncmp(token, "weight=", 7)) {
2234 p->weight = xatoi(token + 7);
2235 } else if (!strncmp(token, "basetime=", 9)) {
2236 p->basetime = xatoi(token + 9);
2237 } else if (!strcmp(token, "closest-only")) {
2238 p->options.closest_only = true;
2239 } else if (!strncmp(token, "ttl=", 4)) {
2240 p->mcast.ttl = xatoi(token + 4);
2241
2242 if (p->mcast.ttl < 0)
2243 p->mcast.ttl = 0;
2244
2245 if (p->mcast.ttl > 128)
2246 p->mcast.ttl = 128;
2247 } else if (!strcmp(token, "default")) {
2248 p->options.default_parent = true;
2249 } else if (!strcmp(token, "round-robin")) {
2250 p->options.roundrobin = true;
2251 } else if (!strcmp(token, "weighted-round-robin")) {
2252 p->options.weighted_roundrobin = true;
2253 #if USE_HTCP
2254 } else if (!strcmp(token, "htcp")) {
2255 p->options.htcp = true;
2256 } else if (!strncmp(token, "htcp=", 5) || !strncmp(token, "htcp-", 5)) {
2257 /* Note: The htcp- form is deprecated, replaced by htcp= */
2258 p->options.htcp = true;
2259 char *tmp = xstrdup(token+5);
2260 char *mode, *nextmode;
2261 for (mode = nextmode = tmp; mode; mode = nextmode) {
2262 nextmode = strchr(mode, ',');
2263 if (nextmode) {
2264 *nextmode = '\0';
2265 ++nextmode;
2266 }
2267 if (!strcmp(mode, "no-clr")) {
2268 if (p->options.htcp_only_clr)
2269 fatalf("parse_peer: can't set htcp-no-clr and htcp-only-clr simultaneously");
2270 p->options.htcp_no_clr = true;
2271 } else if (!strcmp(mode, "no-purge-clr")) {
2272 p->options.htcp_no_purge_clr = true;
2273 } else if (!strcmp(mode, "only-clr")) {
2274 if (p->options.htcp_no_clr)
2275 fatalf("parse_peer: can't set htcp no-clr and only-clr simultaneously");
2276 p->options.htcp_only_clr = true;
2277 } else if (!strcmp(mode, "forward-clr")) {
2278 p->options.htcp_forward_clr = true;
2279 } else if (!strcmp(mode, "oldsquid")) {
2280 p->options.htcp_oldsquid = true;
2281 } else {
2282 fatalf("invalid HTCP mode '%s'", mode);
2283 }
2284 }
2285 safe_free(tmp);
2286 #endif
2287 } else if (!strcmp(token, "no-netdb-exchange")) {
2288 p->options.no_netdb_exchange = true;
2289
2290 } else if (!strcmp(token, "carp")) {
2291 if (p->type != PEER_PARENT)
2292 fatalf("parse_peer: non-parent carp peer %s/%d\n", p->host, p->http_port);
2293
2294 p->options.carp = true;
2295 } else if (!strncmp(token, "carp-key=", 9)) {
2296 if (p->options.carp != true)
2297 fatalf("parse_peer: carp-key specified on non-carp peer %s/%d\n", p->host, p->http_port);
2298 p->options.carp_key.set = true;
2299 char *nextkey=token+strlen("carp-key="), *key=nextkey;
2300 for (; key; key = nextkey) {
2301 nextkey=strchr(key,',');
2302 if (nextkey) ++nextkey; // skip the comma, any
2303 if (0==strncmp(key,"scheme",6)) {
2304 p->options.carp_key.scheme = true;
2305 } else if (0==strncmp(key,"host",4)) {
2306 p->options.carp_key.host = true;
2307 } else if (0==strncmp(key,"port",4)) {
2308 p->options.carp_key.port = true;
2309 } else if (0==strncmp(key,"path",4)) {
2310 p->options.carp_key.path = true;
2311 } else if (0==strncmp(key,"params",6)) {
2312 p->options.carp_key.params = true;
2313 } else {
2314 fatalf("invalid carp-key '%s'",key);
2315 }
2316 }
2317 } else if (!strcmp(token, "userhash")) {
2318 #if USE_AUTH
2319 if (p->type != PEER_PARENT)
2320 fatalf("parse_peer: non-parent userhash peer %s/%d\n", p->host, p->http_port);
2321
2322 p->options.userhash = true;
2323 #else
2324 fatalf("parse_peer: userhash requires authentication. peer %s/%d\n", p->host, p->http_port);
2325 #endif
2326 } else if (!strcmp(token, "sourcehash")) {
2327 if (p->type != PEER_PARENT)
2328 fatalf("parse_peer: non-parent sourcehash peer %s/%d\n", p->host, p->http_port);
2329
2330 p->options.sourcehash = true;
2331
2332 } else if (!strcmp(token, "no-delay")) {
2333 #if USE_DELAY_POOLS
2334 p->options.no_delay = true;
2335 #else
2336 debugs(0, DBG_CRITICAL, "WARNING: cache_peer option 'no-delay' requires --enable-delay-pools");
2337 #endif
2338 } else if (!strncmp(token, "login=", 6)) {
2339 p->login = xstrdup(token + 6);
2340 rfc1738_unescape(p->login);
2341 } else if (!strcmp(token, "auth-no-keytab")) {
2342 p->options.auth_no_keytab = 1;
2343 } else if (!strncmp(token, "connect-timeout=", 16)) {
2344 p->connect_timeout_raw = xatoi(token + 16);
2345 } else if (!strncmp(token, "connect-fail-limit=", 19)) {
2346 p->connect_fail_limit = xatoi(token + 19);
2347 #if USE_CACHE_DIGESTS
2348 } else if (!strncmp(token, "digest-url=", 11)) {
2349 p->digest_url = xstrdup(token + 11);
2350 #endif
2351
2352 } else if (!strcmp(token, "allow-miss")) {
2353 p->options.allow_miss = true;
2354 } else if (!strncmp(token, "max-conn=", 9)) {
2355 p->max_conn = xatoi(token + 9);
2356 } else if (!strncmp(token, "standby=", 8)) {
2357 p->standby.limit = xatoi(token + 8);
2358 } else if (!strcmp(token, "originserver")) {
2359 p->options.originserver = true;
2360 } else if (!strncmp(token, "name=", 5)) {
2361 safe_free(p->name);
2362
2363 if (token[5])
2364 p->name = xstrdup(token + 5);
2365 } else if (!strncmp(token, "forceddomain=", 13)) {
2366 safe_free(p->domain);
2367 if (token[13])
2368 p->domain = xstrdup(token + 13);
2369
2370 } else if (strncmp(token, "ssl", 3) == 0) {
2371 #if !USE_OPENSSL
2372 debugs(0, DBG_CRITICAL, "WARNING: cache_peer option '" << token << "' requires --with-openssl");
2373 #else
2374 p->secure.parse(token+3);
2375 #endif
2376 } else if (strncmp(token, "tls-", 4) == 0) {
2377 p->secure.parse(token+4);
2378 } else if (strncmp(token, "tls", 3) == 0) {
2379 p->secure.parse(token+3);
2380 } else if (strcmp(token, "front-end-https") == 0) {
2381 p->front_end_https = 1;
2382 } else if (strcmp(token, "front-end-https=on") == 0) {
2383 p->front_end_https = 1;
2384 } else if (strcmp(token, "front-end-https=auto") == 0) {
2385 p->front_end_https = 2;
2386 } else if (strcmp(token, "connection-auth=off") == 0) {
2387 p->connection_auth = 0;
2388 } else if (strcmp(token, "connection-auth") == 0) {
2389 p->connection_auth = 1;
2390 } else if (strcmp(token, "connection-auth=on") == 0) {
2391 p->connection_auth = 1;
2392 } else if (strcmp(token, "connection-auth=auto") == 0) {
2393 p->connection_auth = 2;
2394 } else if (token[0] == '#') {
2395 // start of a text comment. stop reading this line.
2396 break;
2397 } else {
2398 debugs(3, DBG_PARSE_NOTE(DBG_IMPORTANT), "ERROR: Ignoring unknown cache_peer option '" << token << "'");
2399 }
2400 }
2401
2402 if (peerFindByName(p->name))
2403 fatalf("ERROR: cache_peer %s specified twice\n", p->name);
2404
2405 if (p->max_conn > 0 && p->max_conn < p->standby.limit)
2406 fatalf("ERROR: cache_peer %s max-conn=%d is lower than its standby=%d\n", p->host, p->max_conn, p->standby.limit);
2407
2408 if (p->weight < 1)
2409 p->weight = 1;
2410
2411 if (p->connect_fail_limit < 1)
2412 p->connect_fail_limit = 10;
2413
2414 #if USE_CACHE_DIGESTS
2415 if (!p->options.no_digest)
2416 peerDigestCreate(p);
2417 #endif
2418
2419 if (p->secure.encryptTransport)
2420 p->secure.parseOptions();
2421
2422 p->index = ++Config.npeers;
2423
2424 while (*head != NULL)
2425 head = &(*head)->next;
2426
2427 *head = p;
2428
2429 peerClearRRStart();
2430 }
2431
2432 static void
2433 free_peer(CachePeer ** P)
2434 {
2435 delete *P;
2436 *P = NULL;
2437 Config.npeers = 0;
2438 }
2439
2440 static void
2441 dump_cachemgrpasswd(StoreEntry * entry, const char *name, Mgr::ActionPasswordList * list)
2442 {
2443 while (list) {
2444 if (strcmp(list->passwd, "none") && strcmp(list->passwd, "disable"))
2445 storeAppendPrintf(entry, "%s XXXXXXXXXX", name);
2446 else
2447 storeAppendPrintf(entry, "%s %s", name, list->passwd);
2448
2449 for (auto w : list->actions)
2450 entry->appendf(" " SQUIDSBUFPH, SQUIDSBUFPRINT(w));
2451
2452 storeAppendPrintf(entry, "\n");
2453 list = list->next;
2454 }
2455 }
2456
2457 static void
2458 parse_cachemgrpasswd(Mgr::ActionPasswordList ** head)
2459 {
2460 char *passwd = nullptr;
2461 parse_string(&passwd);
2462
2463 Mgr::ActionPasswordList *p = new Mgr::ActionPasswordList;
2464 p->passwd = passwd;
2465
2466 while (char *token = ConfigParser::NextQuotedToken())
2467 p->actions.push_back(SBuf(token));
2468
2469 Mgr::ActionPasswordList **P;
2470 for (P = head; *P; P = &(*P)->next) {
2471 /*
2472 * See if any of the actions from this line already have a
2473 * password from previous lines. The password checking
2474 * routines in cache_manager.c take the the password from
2475 * the first Mgr::ActionPasswordList that contains the
2476 * requested action. Thus, we should warn users who might
2477 * think they can have two passwords for the same action.
2478 */
2479 for (const auto &w : (*P)->actions) {
2480 for (const auto &u : p->actions) {
2481 if (w != u)
2482 continue;
2483
2484 debugs(0, DBG_PARSE_NOTE(1), "ERROR: action '" << u << "' (line " << config_lineno << ") already has a password");
2485 }
2486 }
2487 }
2488
2489 *P = p;
2490 }
2491
2492 static void
2493 free_cachemgrpasswd(Mgr::ActionPasswordList ** head)
2494 {
2495 delete *head;
2496 *head = nullptr;
2497 }
2498
2499 static void
2500 dump_denyinfo(StoreEntry * entry, const char *name, AclDenyInfoList * var)
2501 {
2502 while (var != NULL) {
2503 storeAppendPrintf(entry, "%s %s", name, var->err_page_name);
2504
2505 for (const auto &aclName: var->acl_list)
2506 storeAppendPrintf(entry, " " SQUIDSBUFPH, SQUIDSBUFPRINT(aclName));
2507
2508 storeAppendPrintf(entry, "\n");
2509
2510 var = var->next;
2511 }
2512 }
2513
2514 static void
2515 parse_denyinfo(AclDenyInfoList ** var)
2516 {
2517 aclParseDenyInfoLine(var);
2518 }
2519
2520 void
2521 free_denyinfo(AclDenyInfoList ** list)
2522 {
2523 delete *list;
2524 *list = nullptr;
2525 }
2526
2527 static void
2528 parse_peer_access(void)
2529 {
2530 char *host = ConfigParser::NextToken();
2531 if (!host) {
2532 self_destruct();
2533 return;
2534 }
2535
2536 CachePeer *p = peerFindByName(host);
2537 if (!p) {
2538 debugs(15, DBG_CRITICAL, "ERROR: " << cfg_filename << ", line " << config_lineno << ": No cache_peer '" << host << "'");
2539 return;
2540 }
2541
2542 std::string directive = "peer_access ";
2543 directive += host;
2544 aclParseAccessLine(directive.c_str(), LegacyParser, &p->access);
2545 }
2546
2547 static void
2548 parse_hostdomaintype(void)
2549 {
2550 char *host = ConfigParser::NextToken();
2551 if (!host) {
2552 self_destruct();
2553 return;
2554 }
2555
2556 char *type = ConfigParser::NextToken();
2557 if (!type) {
2558 self_destruct();
2559 return;
2560 }
2561
2562 char *domain = nullptr;
2563 while ((domain = ConfigParser::NextToken())) {
2564 CachePeer *p = peerFindByName(host);
2565 if (!p) {
2566 debugs(15, DBG_CRITICAL, "" << cfg_filename << ", line " << config_lineno << ": No cache_peer '" << host << "'");
2567 return;
2568 }
2569
2570 auto *l = static_cast<NeighborTypeDomainList *>(xcalloc(1, sizeof(NeighborTypeDomainList)));
2571 l->type = parseNeighborType(type);
2572 l->domain = xstrdup(domain);
2573
2574 NeighborTypeDomainList **L = nullptr;
2575 for (L = &(p->typelist); *L; L = &((*L)->next));
2576 *L = l;
2577 }
2578 }
2579
2580 static void
2581 dump_int(StoreEntry * entry, const char *name, int var)
2582 {
2583 storeAppendPrintf(entry, "%s %d\n", name, var);
2584 }
2585
2586 void
2587 parse_int(int *var)
2588 {
2589 int i;
2590 i = GetInteger();
2591 *var = i;
2592 }
2593
2594 static void
2595 free_int(int *var)
2596 {
2597 *var = 0;
2598 }
2599
2600 static void
2601 dump_int64_t(StoreEntry * entry, const char *name, int64_t var)
2602 {
2603 storeAppendPrintf(entry, "%s %" PRId64 "\n", name, var);
2604 }
2605
2606 void
2607 parse_int64_t(int64_t *var)
2608 {
2609 int64_t i;
2610 i = GetInteger64();
2611 *var = i;
2612 }
2613
2614 static void
2615 free_int64_t(int64_t *var)
2616 {
2617 *var = 0;
2618 }
2619
2620 static void
2621 dump_onoff(StoreEntry * entry, const char *name, int var)
2622 {
2623 storeAppendPrintf(entry, "%s %s\n", name, var ? "on" : "off");
2624 }
2625
2626 void
2627 parse_onoff(int *var)
2628 {
2629 char *token = ConfigParser::NextToken();
2630 if (!token) {
2631 self_destruct();
2632 return;
2633 }
2634
2635 if (!strcmp(token, "on")) {
2636 *var = 1;
2637 } else if (!strcmp(token, "enable")) {
2638 debugs(0, DBG_PARSE_NOTE(DBG_IMPORTANT), "WARNING: 'enable' is deprecated. Please update to use 'on'.");
2639 *var = 1;
2640 } else if (!strcmp(token, "off")) {
2641 *var = 0;
2642 } else if (!strcmp(token, "disable")) {
2643 debugs(0, DBG_PARSE_NOTE(DBG_IMPORTANT), "WARNING: 'disable' is deprecated. Please update to use 'off'.");
2644 *var = 0;
2645 } else {
2646 debugs(0, DBG_PARSE_NOTE(DBG_IMPORTANT), "ERROR: Invalid option: Boolean options can only be 'on' or 'off'.");
2647 self_destruct();
2648 }
2649 }
2650
2651 #define free_onoff free_int
2652
2653 static void
2654 dump_tristate(StoreEntry * entry, const char *name, int var)
2655 {
2656 const char *state;
2657
2658 if (var > 0)
2659 state = "on";
2660 else if (var < 0)
2661 state = "warn";
2662 else
2663 state = "off";
2664
2665 storeAppendPrintf(entry, "%s %s\n", name, state);
2666 }
2667
2668 static void
2669 parse_tristate(int *var)
2670 {
2671 char *token = ConfigParser::NextToken();
2672 if (!token) {
2673 self_destruct();
2674 return;
2675 }
2676
2677 if (!strcmp(token, "on")) {
2678 *var = 1;
2679 } else if (!strcmp(token, "enable")) {
2680 debugs(0, DBG_PARSE_NOTE(DBG_IMPORTANT), "WARNING: 'enable' is deprecated. Please update to use value 'on'.");
2681 *var = 1;
2682 } else if (!strcmp(token, "warn")) {
2683 *var = -1;
2684 } else if (!strcmp(token, "off")) {
2685 *var = 0;
2686 } else if (!strcmp(token, "disable")) {
2687 debugs(0, DBG_PARSE_NOTE(DBG_IMPORTANT), "WARNING: 'disable' is deprecated. Please update to use value 'off'.");
2688 *var = 0;
2689 } else {
2690 debugs(0, DBG_PARSE_NOTE(DBG_IMPORTANT), "ERROR: Invalid option: Tristate options can only be 'on', 'off', or 'warn'.");
2691 self_destruct();
2692 }
2693 }
2694
2695 #define free_tristate free_int
2696
2697 void
2698 parse_pipelinePrefetch(int *var)
2699 {
2700 char *token = ConfigParser::PeekAtToken();
2701 if (!token) {
2702 self_destruct();
2703 return;
2704 }
2705
2706 if (!strcmp(token, "on")) {
2707 debugs(0, DBG_PARSE_NOTE(DBG_IMPORTANT), "WARNING: 'pipeline_prefetch on' is deprecated. Please update to use 1 (or a higher number).");
2708 *var = 1;
2709 //pop the token
2710 (void)ConfigParser::NextToken();
2711 } else if (!strcmp(token, "off")) {
2712 debugs(0, DBG_PARSE_NOTE(2), "WARNING: 'pipeline_prefetch off' is deprecated. Please update to use '0'.");
2713 *var = 0;
2714 //pop the token
2715 (void)ConfigParser::NextToken();
2716 } else
2717 parse_int(var);
2718 }
2719
2720 #define free_pipelinePrefetch free_int
2721 #define dump_pipelinePrefetch dump_int
2722
2723 static void
2724 dump_refreshpattern(StoreEntry * entry, const char *name, RefreshPattern * head)
2725 {
2726 while (head != NULL) {
2727 storeAppendPrintf(entry, "%s%s %s %d %d%% %d",
2728 name,
2729 head->pattern.flags&REG_ICASE ? " -i" : null_string,
2730 head->pattern.c_str(),
2731 (int) head->min / 60,
2732 (int) (100.0 * head->pct + 0.5),
2733 (int) head->max / 60);
2734
2735 if (head->max_stale >= 0)
2736 storeAppendPrintf(entry, " max-stale=%d", head->max_stale);
2737
2738 if (head->flags.refresh_ims)
2739 storeAppendPrintf(entry, " refresh-ims");
2740
2741 if (head->flags.store_stale)
2742 storeAppendPrintf(entry, " store-stale");
2743
2744 #if USE_HTTP_VIOLATIONS
2745
2746 if (head->flags.override_expire)
2747 storeAppendPrintf(entry, " override-expire");
2748
2749 if (head->flags.override_lastmod)
2750 storeAppendPrintf(entry, " override-lastmod");
2751
2752 if (head->flags.reload_into_ims)
2753 storeAppendPrintf(entry, " reload-into-ims");
2754
2755 if (head->flags.ignore_reload)
2756 storeAppendPrintf(entry, " ignore-reload");
2757
2758 if (head->flags.ignore_no_store)
2759 storeAppendPrintf(entry, " ignore-no-store");
2760
2761 if (head->flags.ignore_private)
2762 storeAppendPrintf(entry, " ignore-private");
2763 #endif
2764
2765 storeAppendPrintf(entry, "\n");
2766
2767 head = head->next;
2768 }
2769 }
2770
2771 static void
2772 parse_refreshpattern(RefreshPattern ** head)
2773 {
2774 char *token;
2775 char *pattern;
2776 time_t min = 0;
2777 double pct = 0.0;
2778 time_t max = 0;
2779 int refresh_ims = 0;
2780 int store_stale = 0;
2781 int max_stale = -1;
2782
2783 #if USE_HTTP_VIOLATIONS
2784
2785 int override_expire = 0;
2786 int override_lastmod = 0;
2787 int reload_into_ims = 0;
2788 int ignore_reload = 0;
2789 int ignore_no_store = 0;
2790 int ignore_private = 0;
2791 #endif
2792
2793 int i;
2794 RefreshPattern *t;
2795 regex_t comp;
2796 int errcode;
2797 int flags = REG_EXTENDED | REG_NOSUB;
2798
2799 if ((token = ConfigParser::RegexPattern()) != NULL) {
2800
2801 if (strcmp(token, "-i") == 0) {
2802 flags |= REG_ICASE;
2803 token = ConfigParser::RegexPattern();
2804 } else if (strcmp(token, "+i") == 0) {
2805 flags &= ~REG_ICASE;
2806 token = ConfigParser::RegexPattern();
2807 }
2808
2809 }
2810
2811 if (token == NULL) {
2812 debugs(3, DBG_CRITICAL, "FATAL: refresh_pattern missing the regex pattern parameter");
2813 self_destruct();
2814 return;
2815 }
2816
2817 pattern = xstrdup(token);
2818
2819 i = GetInteger(); /* token: min */
2820
2821 /* catch negative and insanely huge values close to 32-bit wrap */
2822 if (i < 0) {
2823 debugs(3, DBG_IMPORTANT, "WARNING: refresh_pattern minimum age negative. Cropped back to zero.");
2824 i = 0;
2825 }
2826 if (i > 60*24*365) {
2827 debugs(3, DBG_IMPORTANT, "WARNING: refresh_pattern minimum age too high. Cropped back to 1 year.");
2828 i = 60*24*365;
2829 }
2830
2831 min = (time_t) (i * 60); /* convert minutes to seconds */
2832
2833 pct = GetPercentage(false); /* token: pct . with no limit on size */
2834
2835 i = GetInteger(); /* token: max */
2836
2837 /* catch negative and insanely huge values close to 32-bit wrap */
2838 if (i < 0) {
2839 debugs(3, DBG_IMPORTANT, "WARNING: refresh_pattern maximum age negative. Cropped back to zero.");
2840 i = 0;
2841 }
2842 if (i > 60*24*365) {
2843 debugs(3, DBG_IMPORTANT, "WARNING: refresh_pattern maximum age too high. Cropped back to 1 year.");
2844 i = 60*24*365;
2845 }
2846
2847 max = (time_t) (i * 60); /* convert minutes to seconds */
2848
2849 /* Options */
2850 while ((token = ConfigParser::NextToken()) != NULL) {
2851 if (!strcmp(token, "refresh-ims")) {
2852 refresh_ims = 1;
2853 } else if (!strcmp(token, "store-stale")) {
2854 store_stale = 1;
2855 } else if (!strncmp(token, "max-stale=", 10)) {
2856 max_stale = xatoi(token + 10);
2857
2858 #if USE_HTTP_VIOLATIONS
2859
2860 } else if (!strcmp(token, "override-expire"))
2861 override_expire = 1;
2862 else if (!strcmp(token, "override-lastmod"))
2863 override_lastmod = 1;
2864 else if (!strcmp(token, "ignore-no-store"))
2865 ignore_no_store = 1;
2866 else if (!strcmp(token, "ignore-private"))
2867 ignore_private = 1;
2868 else if (!strcmp(token, "reload-into-ims")) {
2869 reload_into_ims = 1;
2870 refresh_nocache_hack = 1;
2871 /* tell client_side.c that this is used */
2872 } else if (!strcmp(token, "ignore-reload")) {
2873 ignore_reload = 1;
2874 refresh_nocache_hack = 1;
2875 /* tell client_side.c that this is used */
2876 #endif
2877
2878 } else if (!strcmp(token, "ignore-no-cache") ||
2879 !strcmp(token, "ignore-must-revalidate") ||
2880 !strcmp(token, "ignore-auth")
2881 ) {
2882 debugs(22, DBG_PARSE_NOTE(2), "UPGRADE: refresh_pattern option '" << token << "' is obsolete. Remove it.");
2883 } else
2884 debugs(22, DBG_CRITICAL, "refreshAddToList: Unknown option '" << pattern << "': " << token);
2885 }
2886
2887 if ((errcode = regcomp(&comp, pattern, flags)) != 0) {
2888 char errbuf[256];
2889 regerror(errcode, &comp, errbuf, sizeof errbuf);
2890 debugs(22, DBG_CRITICAL, "" << cfg_filename << " line " << config_lineno << ": " << config_input_line);
2891 debugs(22, DBG_CRITICAL, "refreshAddToList: Invalid regular expression '" << pattern << "': " << errbuf);
2892 xfree(pattern);
2893 return;
2894 }
2895
2896 pct = pct < 0.0 ? 0.0 : pct;
2897 max = max < 0 ? 0 : max;
2898 t = new RefreshPattern(pattern, flags);
2899 t->pattern.regex = comp;
2900 t->min = min;
2901 t->pct = pct;
2902 t->max = max;
2903
2904 if (refresh_ims)
2905 t->flags.refresh_ims = true;
2906
2907 if (store_stale)
2908 t->flags.store_stale = true;
2909
2910 t->max_stale = max_stale;
2911
2912 #if USE_HTTP_VIOLATIONS
2913
2914 if (override_expire)
2915 t->flags.override_expire = true;
2916
2917 if (override_lastmod)
2918 t->flags.override_lastmod = true;
2919
2920 if (reload_into_ims)
2921 t->flags.reload_into_ims = true;
2922
2923 if (ignore_reload)
2924 t->flags.ignore_reload = true;
2925
2926 if (ignore_no_store)
2927 t->flags.ignore_no_store = true;
2928
2929 if (ignore_private)
2930 t->flags.ignore_private = true;
2931 #endif
2932
2933 t->next = NULL;
2934
2935 while (*head)
2936 head = &(*head)->next;
2937
2938 *head = t;
2939
2940 xfree(pattern);
2941 }
2942
2943 static void
2944 free_refreshpattern(RefreshPattern ** head)
2945 {
2946 delete *head;
2947 *head = nullptr;
2948
2949 #if USE_HTTP_VIOLATIONS
2950 refresh_nocache_hack = 0;
2951
2952 #endif
2953 }
2954
2955 static void
2956 dump_string(StoreEntry * entry, const char *name, char *var)
2957 {
2958 if (var != NULL)
2959 storeAppendPrintf(entry, "%s %s\n", name, var);
2960 }
2961
2962 static void
2963 parse_string(char **var)
2964 {
2965 safe_free(*var);
2966
2967 char *token = ConfigParser::NextToken();
2968 if (!token) {
2969 self_destruct();
2970 return;
2971 }
2972
2973 *var = xstrdup(token);
2974 }
2975
2976 static void
2977 free_string(char **var)
2978 {
2979 safe_free(*var);
2980 }
2981
2982 void
2983 parse_eol(char *volatile *var)
2984 {
2985 if (!var) {
2986 self_destruct();
2987 return;
2988 }
2989
2990 unsigned char *token = (unsigned char *) ConfigParser::NextQuotedOrToEol();
2991 safe_free(*var);
2992
2993 if (!token) {
2994 self_destruct();
2995 return;
2996 }
2997
2998 while (*token && xisspace(*token))
2999 ++token;
3000
3001 if (!*token) {
3002 self_destruct();
3003 return;
3004 }
3005
3006 *var = xstrdup((char *) token);
3007 }
3008
3009 #define dump_eol dump_string
3010 #define free_eol free_string
3011
3012 static void
3013 parse_TokenOrQuotedString(char **var)
3014 {
3015 safe_free(*var);
3016
3017 char *token = ConfigParser::NextQuotedToken();
3018 if (!token) {
3019 self_destruct();
3020 return;
3021 }
3022
3023 *var = xstrdup(token);
3024 }
3025
3026 #define dump_TokenOrQuotedString dump_string
3027 #define free_TokenOrQuotedString free_string
3028
3029 static void
3030 dump_time_t(StoreEntry * entry, const char *name, time_t var)
3031 {
3032 storeAppendPrintf(entry, "%s %d seconds\n", name, (int) var);
3033 }
3034
3035 void
3036 parse_time_t(time_t * var)
3037 {
3038 const auto maxTime = std::numeric_limits<time_t>::max();
3039 const auto seconds = parseTimeLine<std::chrono::seconds>();
3040 if (maxTime < seconds.count())
3041 throw TexcHere(ToSBuf("directive supports time values up to ", maxTime, " but is given ", seconds.count(), " seconds"));
3042 *var = static_cast<time_t>(seconds.count());
3043 }
3044
3045 static void
3046 free_time_t(time_t * var)
3047 {
3048 *var = 0;
3049 }
3050
3051 static void
3052 dump_time_msec(StoreEntry * entry, const char *name, time_msec_t var)
3053 {
3054 if (var % 1000)
3055 storeAppendPrintf(entry, "%s %" PRId64 " milliseconds\n", name, var);
3056 else
3057 storeAppendPrintf(entry, "%s %d seconds\n", name, (int)(var/1000) );
3058 }
3059
3060 void
3061 parse_time_msec(time_msec_t * var)
3062 {
3063 *var = parseTimeLine<std::chrono::milliseconds>().count();
3064 }
3065
3066 static void
3067 free_time_msec(time_msec_t * var)
3068 {
3069 *var = 0;
3070 }
3071
3072 static void
3073 dump_time_nanoseconds(StoreEntry *entry, const char *name, const std::chrono::nanoseconds &var)
3074 {
3075 storeAppendPrintf(entry, "%s %" PRId64 " nanoseconds\n", name, var.count());
3076 }
3077
3078 static void
3079 parse_time_nanoseconds(std::chrono::nanoseconds *var)
3080 {
3081 *var = parseTimeLine<std::chrono::nanoseconds>();
3082 }
3083
3084 static void
3085 free_time_nanoseconds(std::chrono::nanoseconds *var)
3086 {
3087 *var = std::chrono::nanoseconds::zero();
3088 }
3089
3090 #if UNUSED_CODE
3091 static void
3092 dump_size_t(StoreEntry * entry, const char *name, size_t var)
3093 {
3094 storeAppendPrintf(entry, "%s %d\n", name, (int) var);
3095 }
3096 #endif
3097
3098 static void
3099 dump_b_size_t(StoreEntry * entry, const char *name, size_t var)
3100 {
3101 storeAppendPrintf(entry, "%s %d %s\n", name, (int) var, B_BYTES_STR);
3102 }
3103
3104 static void
3105 dump_b_ssize_t(StoreEntry * entry, const char *name, ssize_t var)
3106 {
3107 storeAppendPrintf(entry, "%s %d %s\n", name, (int) var, B_BYTES_STR);
3108 }
3109
3110 #if UNUSED_CODE
3111 static void
3112 dump_kb_size_t(StoreEntry * entry, const char *name, size_t var)
3113 {
3114 storeAppendPrintf(entry, "%s %d %s\n", name, (int) var, B_KBYTES_STR);
3115 }
3116 #endif
3117
3118 static void
3119 dump_b_int64_t(StoreEntry * entry, const char *name, int64_t var)
3120 {
3121 storeAppendPrintf(entry, "%s %" PRId64 " %s\n", name, var, B_BYTES_STR);
3122 }
3123
3124 static void
3125 dump_kb_int64_t(StoreEntry * entry, const char *name, int64_t var)
3126 {
3127 storeAppendPrintf(entry, "%s %" PRId64 " %s\n", name, var, B_KBYTES_STR);
3128 }
3129
3130 #if UNUSED_CODE
3131 static void
3132 parse_size_t(size_t * var)
3133 {
3134 int i;
3135 i = GetInteger();
3136 *var = (size_t) i;
3137 }
3138 #endif
3139
3140 static void
3141 parse_b_size_t(size_t * var)
3142 {
3143 parseBytesLine(var, B_BYTES_STR);
3144 }
3145
3146 static void
3147 parse_b_ssize_t(ssize_t * var)
3148 {
3149 parseBytesLineSigned(var, B_BYTES_STR);
3150 }
3151
3152 #if UNUSED_CODE
3153 static void
3154 parse_kb_size_t(size_t * var)
3155 {
3156 parseBytesLine(var, B_KBYTES_STR);
3157 }
3158 #endif
3159
3160 static void
3161 parse_b_int64_t(int64_t * var)
3162 {
3163 parseBytesLine64(var, B_BYTES_STR);
3164 }
3165
3166 static void
3167 parse_kb_int64_t(int64_t * var)
3168 {
3169 parseBytesLine64(var, B_KBYTES_STR);
3170 }
3171
3172 static void
3173 free_size_t(size_t * var)
3174 {
3175 *var = 0;
3176 }
3177
3178 static void
3179 free_ssize_t(ssize_t * var)
3180 {
3181 *var = 0;
3182 }
3183
3184 static void
3185 free_b_int64_t(int64_t * var)
3186 {
3187 *var = 0;
3188 }
3189
3190 #define free_b_size_t free_size_t
3191 #define free_b_ssize_t free_ssize_t
3192 #define free_kb_size_t free_size_t
3193 #define free_mb_size_t free_size_t
3194 #define free_gb_size_t free_size_t
3195 #define free_kb_int64_t free_b_int64_t
3196
3197 static void
3198 dump_u_short(StoreEntry * entry, const char *name, unsigned short var)
3199 {
3200 storeAppendPrintf(entry, "%s %d\n", name, var);
3201 }
3202
3203 static void
3204 free_u_short(unsigned short * u)
3205 {
3206 *u = 0;
3207 }
3208
3209 static void
3210 parse_u_short(unsigned short * var)
3211 {
3212 ConfigParser::ParseUShort(var);
3213 }
3214
3215 void
3216 ConfigParser::ParseUShort(unsigned short *var)
3217 {
3218 *var = GetShort();
3219 }
3220
3221 void
3222 ConfigParser::ParseBool(bool *var)
3223 {
3224 int i = GetInteger();
3225
3226 if (0 == i)
3227 *var = false;
3228 else if (1 == i)
3229 *var = true;
3230 else
3231 self_destruct();
3232 }
3233
3234 static void
3235 dump_wordlist(StoreEntry * entry, const char *name, wordlist * list)
3236 {
3237 while (list != NULL) {
3238 storeAppendPrintf(entry, "%s %s\n", name, list->key);
3239 list = list->next;
3240 }
3241 }
3242
3243 void
3244 ConfigParser::ParseWordList(wordlist ** list)
3245 {
3246 parse_wordlist(list);
3247 }
3248
3249 void
3250 parse_wordlist(wordlist ** list)
3251 {
3252 char *token;
3253 while ((token = ConfigParser::NextQuotedToken()))
3254 wordlistAdd(list, token);
3255 }
3256
3257 #if 0 /* now unused */
3258 static int
3259 check_null_wordlist(wordlist * w)
3260 {
3261 return w == NULL;
3262 }
3263 #endif
3264
3265 static int
3266 check_null_acl_access(acl_access * a)
3267 {
3268 return a == NULL;
3269 }
3270
3271 #define free_wordlist wordlistDestroy
3272
3273 #define free_uri_whitespace free_int
3274
3275 static void
3276 parse_uri_whitespace(int *var)
3277 {
3278 char *token = ConfigParser::NextToken();
3279 if (!token) {
3280 self_destruct();
3281 return;
3282 }
3283
3284 if (!strcmp(token, "strip"))
3285 *var = URI_WHITESPACE_STRIP;
3286 else if (!strcmp(token, "deny"))
3287 *var = URI_WHITESPACE_DENY;
3288 else if (!strcmp(token, "allow"))
3289 *var = URI_WHITESPACE_ALLOW;
3290 else if (!strcmp(token, "encode"))
3291 *var = URI_WHITESPACE_ENCODE;
3292 else if (!strcmp(token, "chop"))
3293 *var = URI_WHITESPACE_CHOP;
3294 else {
3295 debugs(0, DBG_PARSE_NOTE(2), "ERROR: Invalid option '" << token << "': 'uri_whitespace' accepts 'strip', 'deny', 'allow', 'encode', and 'chop'.");
3296 self_destruct();
3297 }
3298 }
3299
3300 static void
3301 dump_uri_whitespace(StoreEntry * entry, const char *name, int var)
3302 {
3303 const char *s;
3304
3305 if (var == URI_WHITESPACE_ALLOW)
3306 s = "allow";
3307 else if (var == URI_WHITESPACE_ENCODE)
3308 s = "encode";
3309 else if (var == URI_WHITESPACE_CHOP)
3310 s = "chop";
3311 else if (var == URI_WHITESPACE_DENY)
3312 s = "deny";
3313 else
3314 s = "strip";
3315
3316 storeAppendPrintf(entry, "%s %s\n", name, s);
3317 }
3318
3319 static void
3320 free_removalpolicy(RemovalPolicySettings ** settings)
3321 {
3322 if (!*settings)
3323 return;
3324
3325 free_string(&(*settings)->type);
3326
3327 free_wordlist(&(*settings)->args);
3328
3329 delete *settings;
3330
3331 *settings = NULL;
3332 }
3333
3334 static void
3335 parse_removalpolicy(RemovalPolicySettings ** settings)
3336 {
3337 if (*settings)
3338 free_removalpolicy(settings);
3339
3340 *settings = new RemovalPolicySettings;
3341
3342 parse_string(&(*settings)->type);
3343
3344 parse_wordlist(&(*settings)->args);
3345 }
3346
3347 static void
3348 dump_removalpolicy(StoreEntry * entry, const char *name, RemovalPolicySettings * settings)
3349 {
3350 wordlist *args;
3351 storeAppendPrintf(entry, "%s %s", name, settings->type);
3352 args = settings->args;
3353
3354 while (args) {
3355 storeAppendPrintf(entry, " %s", args->key);
3356 args = args->next;
3357 }
3358
3359 storeAppendPrintf(entry, "\n");
3360 }
3361
3362 inline void
3363 free_YesNoNone(YesNoNone *)
3364 {}
3365
3366 static void
3367 parse_YesNoNone(YesNoNone *option)
3368 {
3369 int value = 0;
3370 parse_onoff(&value);
3371 option->configure(value > 0);
3372 }
3373
3374 static void
3375 dump_YesNoNone(StoreEntry * entry, const char *name, YesNoNone &option)
3376 {
3377 if (option.configured())
3378 dump_onoff(entry, name, option ? 1 : 0);
3379 }
3380
3381 static void
3382 free_memcachemode(SquidConfig *)
3383 {}
3384
3385 static void
3386 parse_memcachemode(SquidConfig *)
3387 {
3388 char *token = ConfigParser::NextToken();
3389 if (!token) {
3390 self_destruct();
3391 return;
3392 }
3393
3394 if (strcmp(token, "always") == 0) {
3395 Config.onoff.memory_cache_first = 1;
3396 Config.onoff.memory_cache_disk = 1;
3397 } else if (strcmp(token, "disk") == 0) {
3398 Config.onoff.memory_cache_first = 0;
3399 Config.onoff.memory_cache_disk = 1;
3400 } else if (strncmp(token, "net", 3) == 0) {
3401 Config.onoff.memory_cache_first = 1;
3402 Config.onoff.memory_cache_disk = 0;
3403 } else if (strcmp(token, "never") == 0) {
3404 Config.onoff.memory_cache_first = 0;
3405 Config.onoff.memory_cache_disk = 0;
3406 } else {
3407 debugs(0, DBG_PARSE_NOTE(2), "ERROR: Invalid option '" << token << "': 'memory_cache_mode' accepts 'always', 'disk', 'network', and 'never'.");
3408 self_destruct();
3409 }
3410 }
3411
3412 static void
3413 dump_memcachemode(StoreEntry * entry, const char *name, SquidConfig &)
3414 {
3415 storeAppendPrintf(entry, "%s ", name);
3416 if (Config.onoff.memory_cache_first && Config.onoff.memory_cache_disk)
3417 storeAppendPrintf(entry, "always");
3418 else if (!Config.onoff.memory_cache_first && Config.onoff.memory_cache_disk)
3419 storeAppendPrintf(entry, "disk");
3420 else if (Config.onoff.memory_cache_first && !Config.onoff.memory_cache_disk)
3421 storeAppendPrintf(entry, "network");
3422 else if (!Config.onoff.memory_cache_first && !Config.onoff.memory_cache_disk)
3423 storeAppendPrintf(entry, "none");
3424 storeAppendPrintf(entry, "\n");
3425 }
3426
3427 #include "cf_parser.cci"
3428
3429 peer_t
3430 parseNeighborType(const char *s)
3431 {
3432 if (!strcmp(s, "parent"))
3433 return PEER_PARENT;
3434
3435 if (!strcmp(s, "neighbor"))
3436 return PEER_SIBLING;
3437
3438 if (!strcmp(s, "neighbour"))
3439 return PEER_SIBLING;
3440
3441 if (!strcmp(s, "sibling"))
3442 return PEER_SIBLING;
3443
3444 if (!strcmp(s, "multicast"))
3445 return PEER_MULTICAST;
3446
3447 debugs(15, DBG_CRITICAL, "WARNING: Unknown neighbor type: " << s);
3448
3449 return PEER_SIBLING;
3450 }
3451
3452 #if USE_WCCPv2
3453 static void
3454 parse_IpAddress_list(Ip::Address_list ** head)
3455 {
3456 char *token;
3457 Ip::Address_list *s;
3458 Ip::Address ipa;
3459
3460 while ((token = ConfigParser::NextToken())) {
3461 if (GetHostWithPort(token, &ipa)) {
3462
3463 while (*head)
3464 head = &(*head)->next;
3465
3466 s = static_cast<Ip::Address_list *>(xcalloc(1, sizeof(*s)));
3467 s->s = ipa;
3468
3469 *head = s;
3470 } else {
3471 self_destruct();
3472 return;
3473 }
3474 }
3475 }
3476
3477 static void
3478 dump_IpAddress_list(StoreEntry * e, const char *n, const Ip::Address_list * s)
3479 {
3480 char ntoabuf[MAX_IPSTRLEN];
3481
3482 while (s) {
3483 storeAppendPrintf(e, "%s %s\n",
3484 n,
3485 s->s.toStr(ntoabuf,MAX_IPSTRLEN));
3486 s = s->next;
3487 }
3488 }
3489
3490 static void
3491 free_IpAddress_list(Ip::Address_list ** head)
3492 {
3493 if (*head) delete *head;
3494 *head = NULL;
3495 }
3496
3497 #if CURRENTLY_UNUSED
3498 /* This code was previously used by http_port. Left as it really should
3499 * be used by icp_port and htcp_port
3500 */
3501 static int
3502 check_null_IpAddress_list(const Ip::Address_list * s)
3503 {
3504 return NULL == s;
3505 }
3506
3507 #endif /* CURRENTLY_UNUSED */
3508 #endif /* USE_WCCPv2 */
3509
3510 static void
3511 parsePortSpecification(const AnyP::PortCfgPointer &s, char *token)
3512 {
3513 char *host = NULL;
3514 unsigned short port = 0;
3515 char *t = NULL;
3516 char *junk = NULL;
3517
3518 s->disable_pmtu_discovery = DISABLE_PMTU_OFF;
3519 s->name = xstrdup(token);
3520 s->connection_auth_disabled = false;
3521
3522 const SBuf &portType = AnyP::UriScheme(s->transport.protocol).image();
3523
3524 if (*token == '[') {
3525 /* [ipv6]:port */
3526 host = token + 1;
3527 t = strchr(host, ']');
3528 if (!t) {
3529 debugs(3, DBG_CRITICAL, "FATAL: " << portType << "_port: missing ']' on IPv6 address: " << token);
3530 self_destruct();
3531 return;
3532 }
3533 *t = '\0';
3534 ++t;
3535 if (*t != ':') {
3536 debugs(3, DBG_CRITICAL, "FATAL: " << portType << "_port: missing Port in: " << token);
3537 self_destruct();
3538 return;
3539 }
3540 if (!Ip::EnableIpv6) {
3541 debugs(3, DBG_CRITICAL, "FATAL: " << portType << "_port: IPv6 is not available.");
3542 self_destruct();
3543 return;
3544 }
3545 port = xatos(t + 1);
3546 } else if ((t = strchr(token, ':'))) {
3547 /* host:port */
3548 /* ipv4:port */
3549 host = token;
3550 *t = '\0';
3551 port = xatos(t + 1);
3552
3553 } else if (strtol(token, &junk, 10) && !*junk) {
3554 port = xatos(token);
3555 debugs(3, 3, portType << "_port: found Listen on Port: " << port);
3556 } else {
3557 debugs(3, DBG_CRITICAL, "FATAL: " << portType << "_port: missing Port: " << token);
3558 self_destruct();
3559 return;
3560 }
3561
3562 if (port == 0 && host != NULL) {
3563 debugs(3, DBG_CRITICAL, "FATAL: " << portType << "_port: Port cannot be 0: " << token);
3564 self_destruct();
3565 return;
3566 }
3567
3568 if (NULL == host) {
3569 s->s.setAnyAddr();
3570 s->s.port(port);
3571 if (!Ip::EnableIpv6)
3572 s->s.setIPv4();
3573 debugs(3, 3, portType << "_port: found Listen on wildcard address: *:" << s->s.port());
3574 } else if ( (s->s = host) ) { /* check/parse numeric IPA */
3575 s->s.port(port);
3576 if (!Ip::EnableIpv6)
3577 s->s.setIPv4();
3578 debugs(3, 3, portType << "_port: Listen on Host/IP: " << host << " --> " << s->s);
3579 } else if ( s->s.GetHostByName(host) ) { /* check/parse for FQDN */
3580 /* do not use ipcache */
3581 s->defaultsite = xstrdup(host);
3582 s->s.port(port);
3583 if (!Ip::EnableIpv6)
3584 s->s.setIPv4();
3585 debugs(3, 3, portType << "_port: found Listen as Host " << s->defaultsite << " on IP: " << s->s);
3586 } else {
3587 debugs(3, DBG_CRITICAL, "FATAL: " << portType << "_port: failed to resolve Host/IP: " << host);
3588 self_destruct();
3589 }
3590 }
3591
3592 /// parses the protocol= option of the *_port directive, returning parsed value
3593 /// unsupported option values result in a fatal error message
3594 /// upper case values required; caller may convert for backward compatibility
3595 static AnyP::ProtocolVersion
3596 parsePortProtocol(const SBuf &value)
3597 {
3598 // HTTP/1.0 not supported because we are version 1.1 which contains a superset of 1.0
3599 // and RFC 2616 requires us to upgrade 1.0 to 1.1
3600 if (value.cmp("HTTP") == 0 || value.cmp("HTTP/1.1") == 0)
3601 return Http::ProtocolVersion(1,1);
3602
3603 if (value.cmp("HTTPS") == 0 || value.cmp("HTTPS/1.1") == 0)
3604 return AnyP::ProtocolVersion(AnyP::PROTO_HTTPS, 1,1);
3605
3606 if (value.cmp("FTP") == 0)
3607 return Ftp::ProtocolVersion();
3608
3609 fatalf("%s directive does not support protocol=" SQUIDSBUFPH "\n", cfg_directive, SQUIDSBUFPRINT(value));
3610 return AnyP::ProtocolVersion(); // not reached
3611 }
3612
3613 static void
3614 parse_port_option(AnyP::PortCfgPointer &s, char *token)
3615 {
3616 /* modes first */
3617
3618 if (strcmp(token, "accel") == 0) {
3619 if (s->flags.isIntercepted()) {
3620 debugs(3, DBG_CRITICAL, "FATAL: " << cfg_directive << ": Accelerator mode requires its own port. It cannot be shared with other modes.");
3621 self_destruct();
3622 return;
3623 }
3624 s->flags.accelSurrogate = true;
3625 s->vhost = true;
3626 } else if (strcmp(token, "transparent") == 0 || strcmp(token, "intercept") == 0) {
3627 if (s->flags.accelSurrogate || s->flags.tproxyIntercept) {
3628 debugs(3, DBG_CRITICAL, "FATAL: " << cfg_directive << ": Intercept mode requires its own interception port. It cannot be shared with other modes.");
3629 self_destruct();
3630 return;
3631 }
3632 s->flags.natIntercept = true;
3633 Ip::Interceptor.StartInterception();
3634 /* Log information regarding the port modes under interception. */
3635 debugs(3, DBG_IMPORTANT, "Starting Authentication on port " << s->s);
3636 debugs(3, DBG_IMPORTANT, "Disabling Authentication on port " << s->s << " (interception enabled)");
3637 } else if (strcmp(token, "tproxy") == 0) {
3638 if (s->flags.natIntercept || s->flags.accelSurrogate) {
3639 debugs(3,DBG_CRITICAL, "FATAL: " << cfg_directive << ": TPROXY option requires its own interception port. It cannot be shared with other modes.");
3640 self_destruct();
3641 return;
3642 }
3643 s->flags.tproxyIntercept = true;
3644 Ip::Interceptor.StartTransparency();
3645 /* Log information regarding the port modes under transparency. */
3646 debugs(3, DBG_IMPORTANT, "Disabling Authentication on port " << s->s << " (TPROXY enabled)");
3647
3648 if (s->flags.proxySurrogate) {
3649 debugs(3, DBG_IMPORTANT, "Disabling TPROXY Spoofing on port " << s->s << " (require-proxy-header enabled)");
3650 }
3651
3652 if (!Ip::Interceptor.ProbeForTproxy(s->s)) {
3653 debugs(3, DBG_CRITICAL, "FATAL: " << cfg_directive << ": TPROXY support in the system does not work.");
3654 self_destruct();
3655 return;
3656 }
3657
3658 } else if (strcmp(token, "require-proxy-header") == 0) {
3659 s->flags.proxySurrogate = true;
3660 if (s->flags.tproxyIntercept) {
3661 // receiving is still permitted, so we do not unset the TPROXY flag
3662 // spoofing access control override takes care of the spoof disable later
3663 debugs(3, DBG_IMPORTANT, "Disabling TPROXY Spoofing on port " << s->s << " (require-proxy-header enabled)");
3664 }
3665
3666 } else if (strncmp(token, "defaultsite=", 12) == 0) {
3667 if (!s->flags.accelSurrogate) {
3668 debugs(3, DBG_CRITICAL, "FATAL: " << cfg_directive << ": defaultsite option requires Acceleration mode flag.");
3669 self_destruct();
3670 return;
3671 }
3672 safe_free(s->defaultsite);
3673 s->defaultsite = xstrdup(token + 12);
3674 } else if (strcmp(token, "vhost") == 0) {
3675 if (!s->flags.accelSurrogate) {
3676 debugs(3, DBG_CRITICAL, "WARNING: " << cfg_directive << ": vhost option is deprecated. Use 'accel' mode flag instead.");
3677 }
3678 s->flags.accelSurrogate = true;
3679 s->vhost = true;
3680 } else if (strcmp(token, "no-vhost") == 0) {
3681 if (!s->flags.accelSurrogate) {
3682 debugs(3, DBG_IMPORTANT, "ERROR: " << cfg_directive << ": no-vhost option requires Acceleration mode flag.");
3683 }
3684 s->vhost = false;
3685 } else if (strcmp(token, "vport") == 0) {
3686 if (!s->flags.accelSurrogate) {
3687 debugs(3, DBG_CRITICAL, "FATAL: " << cfg_directive << ": vport option requires Acceleration mode flag.");
3688 self_destruct();
3689 return;
3690 }
3691 s->vport = -1;
3692 } else if (strncmp(token, "vport=", 6) == 0) {
3693 if (!s->flags.accelSurrogate) {
3694 debugs(3, DBG_CRITICAL, "FATAL: " << cfg_directive << ": vport option requires Acceleration mode flag.");
3695 self_destruct();
3696 return;
3697 }
3698 s->vport = xatos(token + 6);
3699 } else if (strncmp(token, "protocol=", 9) == 0) {
3700 if (!s->flags.accelSurrogate) {
3701 debugs(3, DBG_CRITICAL, "FATAL: " << cfg_directive << ": protocol option requires Acceleration mode flag.");
3702 self_destruct();
3703 return;
3704 }
3705 s->transport = parsePortProtocol(ToUpper(SBuf(token + 9)));
3706 } else if (strcmp(token, "allow-direct") == 0) {
3707 if (!s->flags.accelSurrogate) {
3708 debugs(3, DBG_CRITICAL, "FATAL: " << cfg_directive << ": allow-direct option requires Acceleration mode flag.");
3709 self_destruct();
3710 return;
3711 }
3712 s->allow_direct = true;
3713 } else if (strcmp(token, "act-as-origin") == 0) {
3714 if (!s->flags.accelSurrogate) {
3715 debugs(3, DBG_IMPORTANT, "ERROR: " << cfg_directive << ": act-as-origin option requires Acceleration mode flag.");
3716 } else
3717 s->actAsOrigin = true;
3718 } else if (strcmp(token, "ignore-cc") == 0) {
3719 #if !USE_HTTP_VIOLATIONS
3720 if (!s->flags.accelSurrogate) {
3721 debugs(3, DBG_CRITICAL, "FATAL: " << cfg_directive << ": ignore-cc option requires Acceleration mode flag.");
3722 self_destruct();
3723 return;
3724 }
3725 #endif
3726 s->ignore_cc = true;
3727 } else if (strncmp(token, "name=", 5) == 0) {
3728 safe_free(s->name);
3729 s->name = xstrdup(token + 5);
3730 } else if (strcmp(token, "no-connection-auth") == 0) {
3731 s->connection_auth_disabled = true;
3732 } else if (strcmp(token, "connection-auth=off") == 0) {
3733 s->connection_auth_disabled = true;
3734 } else if (strcmp(token, "connection-auth") == 0) {
3735 s->connection_auth_disabled = false;
3736 } else if (strcmp(token, "connection-auth=on") == 0) {
3737 s->connection_auth_disabled = false;
3738 } else if (strncmp(token, "disable-pmtu-discovery=", 23) == 0) {
3739 if (!strcmp(token + 23, "off"))
3740 s->disable_pmtu_discovery = DISABLE_PMTU_OFF;
3741 else if (!strcmp(token + 23, "transparent"))
3742 s->disable_pmtu_discovery = DISABLE_PMTU_TRANSPARENT;
3743 else if (!strcmp(token + 23, "always"))
3744 s->disable_pmtu_discovery = DISABLE_PMTU_ALWAYS;
3745 else {
3746 self_destruct();
3747 return;
3748 }
3749 } else if (strcmp(token, "ipv4") == 0) {
3750 if ( !s->s.setIPv4() ) {
3751 debugs(3, DBG_CRITICAL, "FATAL: " << cfg_directive << ": IPv6 addresses cannot be used as IPv4-Only. " << s->s );
3752 self_destruct();
3753 return;
3754 }
3755 } else if (strcmp(token, "tcpkeepalive") == 0) {
3756 s->tcp_keepalive.enabled = true;
3757 } else if (strncmp(token, "tcpkeepalive=", 13) == 0) {
3758 char *t = token + 13;
3759 s->tcp_keepalive.enabled = true;
3760 s->tcp_keepalive.idle = xatoui(t,',');
3761 t = strchr(t, ',');
3762 if (t) {
3763 ++t;
3764 s->tcp_keepalive.interval = xatoui(t,',');
3765 t = strchr(t, ',');
3766 }
3767 if (t) {
3768 ++t;
3769 s->tcp_keepalive.timeout = xatoui(t);
3770 }
3771 #if USE_OPENSSL
3772 } else if (strcmp(token, "sslBump") == 0) {
3773 debugs(3, DBG_PARSE_NOTE(1), "WARNING: '" << token << "' is deprecated " <<
3774 "in " << cfg_directive << ". Use 'ssl-bump' instead.");
3775 s->flags.tunnelSslBumping = true;
3776 } else if (strcmp(token, "ssl-bump") == 0) {
3777 s->flags.tunnelSslBumping = true;
3778 } else if (strncmp(token, "cert=", 5) == 0) {
3779 s->secure.parse(token);
3780 } else if (strncmp(token, "key=", 4) == 0) {
3781 s->secure.parse(token);
3782 } else if (strncmp(token, "version=", 8) == 0) {
3783 debugs(3, DBG_PARSE_NOTE(1), "UPGRADE WARNING: '" << token << "' is deprecated " <<
3784 "in " << cfg_directive << ". Use 'options=' instead.");
3785 s->secure.parse(token);
3786 } else if (strncmp(token, "options=", 8) == 0) {
3787 s->secure.parse(token);
3788 } else if (strncmp(token, "cipher=", 7) == 0) {
3789 s->secure.parse(token);
3790 } else if (strncmp(token, "clientca=", 9) == 0) {
3791 s->secure.parse(token);
3792 } else if (strncmp(token, "cafile=", 7) == 0) {
3793 debugs(3, DBG_PARSE_NOTE(1), "UPGRADE WARNING: '" << token << "' is deprecated " <<
3794 "in " << cfg_directive << ". Use 'tls-cafile=' instead.");
3795 s->secure.parse(token);
3796 } else if (strncmp(token, "capath=", 7) == 0) {
3797 s->secure.parse(token);
3798 } else if (strncmp(token, "crlfile=", 8) == 0) {
3799 s->secure.parse(token);
3800 } else if (strncmp(token, "dhparams=", 9) == 0) {
3801 debugs(3, DBG_PARSE_NOTE(DBG_IMPORTANT), "WARNING: '" << token << "' is deprecated " <<
3802 "in " << cfg_directive << ". Use 'tls-dh=' instead.");
3803 s->secure.parse(token);
3804 } else if (strncmp(token, "sslflags=", 9) == 0) {
3805 // NP: deprecation warnings output by secure.parse() when relevant
3806 s->secure.parse(token+3);
3807 } else if (strncmp(token, "sslcontext=", 11) == 0) {
3808 // NP: deprecation warnings output by secure.parse() when relevant
3809 s->secure.parse(token+3);
3810 } else if (strncmp(token, "generate-host-certificates", 26) == 0) {
3811 s->secure.parse(token);
3812 #endif
3813 } else if (strncmp(token, "dynamic_cert_mem_cache_size=", 28) == 0) {
3814 s->secure.parse(token);
3815 } else if (strncmp(token, "tls-", 4) == 0) {
3816 s->secure.parse(token+4);
3817 } else if (strcmp(token, "ftp-track-dirs") == 0) {
3818 s->ftp_track_dirs = true;
3819 } else if (strcmp(token, "worker-queues") == 0) {
3820 #if !defined(SO_REUSEADDR)
3821 #error missing system #include that #defines SO_* constants
3822 #endif
3823 #if !defined(SO_REUSEPORT)
3824 throw TexcHere(ToSBuf(cfg_directive, ' ', token, " option requires building Squid where SO_REUSEPORT is supported by the TCP stack"));
3825 #endif
3826 s->workerQueues = true;
3827 } else {
3828 debugs(3, DBG_CRITICAL, "FATAL: Unknown " << cfg_directive << " option '" << token << "'.");
3829 self_destruct();
3830 }
3831 }
3832
3833 void
3834 add_http_port(char *portspec)
3835 {
3836 AnyP::PortCfgPointer s = new AnyP::PortCfg();
3837 s->transport = parsePortProtocol(SBuf("HTTP"));
3838 parsePortSpecification(s, portspec);
3839 // we may need to merge better if the above returns a list with clones
3840 assert(s->next == NULL);
3841 s->next = HttpPortList;
3842 HttpPortList = s;
3843 }
3844
3845 static void
3846 parsePortCfg(AnyP::PortCfgPointer *head, const char *optionName)
3847 {
3848 SBuf protoName;
3849 if (strcmp(optionName, "http_port") == 0 ||
3850 strcmp(optionName, "ascii_port") == 0)
3851 protoName = "HTTP";
3852 else if (strcmp(optionName, "https_port") == 0)
3853 protoName = "HTTPS";
3854 else if (strcmp(optionName, "ftp_port") == 0)
3855 protoName = "FTP";
3856 if (protoName.isEmpty()) {
3857 self_destruct();
3858 return;
3859 }
3860
3861 char *token = ConfigParser::NextToken();
3862
3863 if (!token) {
3864 self_destruct();
3865 return;
3866 }
3867
3868 AnyP::PortCfgPointer s = new AnyP::PortCfg();
3869 s->transport = parsePortProtocol(protoName); // default; protocol=... overwrites
3870 parsePortSpecification(s, token);
3871
3872 /* parse options ... */
3873 while ((token = ConfigParser::NextToken())) {
3874 parse_port_option(s, token);
3875 }
3876
3877 s->secure.syncCaFiles();
3878
3879 if (s->transport.protocol == AnyP::PROTO_HTTPS) {
3880 s->secure.encryptTransport = true;
3881 #if USE_OPENSSL
3882 /* ssl-bump on https_port configuration requires either tproxy or intercept, and vice versa */
3883 const bool hijacked = s->flags.isIntercepted();
3884 if (s->flags.tunnelSslBumping && !hijacked) {
3885 debugs(3, DBG_CRITICAL, "FATAL: ssl-bump on https_port requires tproxy/intercept which is missing.");
3886 self_destruct();
3887 return;
3888 }
3889 if (hijacked && !s->flags.tunnelSslBumping) {
3890 debugs(3, DBG_CRITICAL, "FATAL: tproxy/intercept on https_port requires ssl-bump which is missing.");
3891 self_destruct();
3892 return;
3893 }
3894 #endif
3895 if (s->flags.proxySurrogate) {
3896 debugs(3,DBG_CRITICAL, "FATAL: https_port: require-proxy-header option is not supported on HTTPS ports.");
3897 self_destruct();
3898 return;
3899 }
3900 } else if (protoName.cmp("FTP") == 0) {
3901 /* ftp_port does not support ssl-bump */
3902 if (s->flags.tunnelSslBumping) {
3903 debugs(3, DBG_CRITICAL, "FATAL: ssl-bump is not supported for ftp_port.");
3904 self_destruct();
3905 return;
3906 }
3907 if (s->flags.proxySurrogate) {
3908 // Passive FTP data channel does not work without deep protocol inspection in the frontend.
3909 debugs(3,DBG_CRITICAL, "FATAL: require-proxy-header option is not supported on ftp_port.");
3910 self_destruct();
3911 return;
3912 }
3913 }
3914
3915 if (s->secure.encryptTransport) {
3916 if (s->secure.certs.empty()) {
3917 debugs(3, DBG_CRITICAL, "FATAL: " << AnyP::UriScheme(s->transport.protocol) << "_port requires a cert= parameter");
3918 self_destruct();
3919 return;
3920 }
3921 s->secure.parseOptions();
3922 }
3923
3924 // *_port line should now be fully valid so we can clone it if necessary
3925 if (Ip::EnableIpv6&IPV6_SPECIAL_SPLITSTACK && s->s.isAnyAddr()) {
3926 // clone the port options from *s to *(s->next)
3927 s->next = s->clone();
3928 s->next->s.setIPv4();
3929 debugs(3, 3, AnyP::UriScheme(s->transport.protocol).image() << "_port: clone wildcard address for split-stack: " << s->s << " and " << s->next->s);
3930 }
3931
3932 while (*head != NULL)
3933 head = &((*head)->next);
3934
3935 *head = s;
3936 }
3937
3938 static void
3939 dump_generic_port(StoreEntry * e, const char *n, const AnyP::PortCfgPointer &s)
3940 {
3941 char buf[MAX_IPSTRLEN];
3942
3943 storeAppendPrintf(e, "%s %s",
3944 n,
3945 s->s.toUrl(buf,MAX_IPSTRLEN));
3946
3947 // MODES and specific sub-options.
3948 if (s->flags.natIntercept)
3949 storeAppendPrintf(e, " intercept");
3950
3951 else if (s->flags.tproxyIntercept)
3952 storeAppendPrintf(e, " tproxy");
3953
3954 else if (s->flags.proxySurrogate)
3955 storeAppendPrintf(e, " require-proxy-header");
3956
3957 else if (s->flags.accelSurrogate) {
3958 storeAppendPrintf(e, " accel");
3959
3960 if (s->vhost)
3961 storeAppendPrintf(e, " vhost");
3962
3963 if (s->vport < 0)
3964 storeAppendPrintf(e, " vport");
3965 else if (s->vport > 0)
3966 storeAppendPrintf(e, " vport=%d", s->vport);
3967
3968 if (s->defaultsite)
3969 storeAppendPrintf(e, " defaultsite=%s", s->defaultsite);
3970
3971 // TODO: compare against prefix of 'n' instead of assuming http_port
3972 if (s->transport.protocol != AnyP::PROTO_HTTP)
3973 storeAppendPrintf(e, " protocol=%s", AnyP::ProtocolType_str[s->transport.protocol]);
3974
3975 if (s->allow_direct)
3976 storeAppendPrintf(e, " allow-direct");
3977
3978 if (s->ignore_cc)
3979 storeAppendPrintf(e, " ignore-cc");
3980
3981 }
3982
3983 // Generic independent options
3984
3985 if (s->name)
3986 storeAppendPrintf(e, " name=%s", s->name);
3987
3988 #if USE_HTTP_VIOLATIONS
3989 if (!s->flags.accelSurrogate && s->ignore_cc)
3990 storeAppendPrintf(e, " ignore-cc");
3991 #endif
3992
3993 if (s->connection_auth_disabled)
3994 storeAppendPrintf(e, " connection-auth=off");
3995 else
3996 storeAppendPrintf(e, " connection-auth=on");
3997
3998 if (s->disable_pmtu_discovery != DISABLE_PMTU_OFF) {
3999 const char *pmtu;
4000
4001 if (s->disable_pmtu_discovery == DISABLE_PMTU_ALWAYS)
4002 pmtu = "always";
4003 else
4004 pmtu = "transparent";
4005
4006 storeAppendPrintf(e, " disable-pmtu-discovery=%s", pmtu);
4007 }
4008
4009 if (s->s.isAnyAddr() && !s->s.isIPv6())
4010 storeAppendPrintf(e, " ipv4");
4011
4012 if (s->tcp_keepalive.enabled) {
4013 if (s->tcp_keepalive.idle || s->tcp_keepalive.interval || s->tcp_keepalive.timeout) {
4014 storeAppendPrintf(e, " tcpkeepalive=%d,%d,%d", s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout);
4015 } else {
4016 storeAppendPrintf(e, " tcpkeepalive");
4017 }
4018 }
4019
4020 #if USE_OPENSSL
4021 if (s->flags.tunnelSslBumping)
4022 storeAppendPrintf(e, " ssl-bump");
4023 #endif
4024
4025 s->secure.dumpCfg(e, "tls-");
4026 }
4027
4028 static void
4029 dump_PortCfg(StoreEntry * e, const char *n, const AnyP::PortCfgPointer &s)
4030 {
4031 for (AnyP::PortCfgPointer p = s; p != NULL; p = p->next) {
4032 dump_generic_port(e, n, p);
4033 storeAppendPrintf(e, "\n");
4034 }
4035 }
4036
4037 void
4038 configFreeMemory(void)
4039 {
4040 free_all();
4041 Config.ssl_client.sslContext.reset();
4042 #if USE_OPENSSL
4043 Ssl::unloadSquidUntrusted();
4044 #endif
4045 }
4046
4047 void
4048 requirePathnameExists(const char *name, const char *path)
4049 {
4050
4051 struct stat sb;
4052 char pathbuf[BUFSIZ];
4053 assert(path != NULL);
4054
4055 if (Config.chroot_dir && (geteuid() == 0)) {
4056 snprintf(pathbuf, BUFSIZ, "%s/%s", Config.chroot_dir, path);
4057 path = pathbuf;
4058 }
4059
4060 if (stat(path, &sb) < 0) {
4061 int xerrno = errno;
4062 debugs(0, DBG_CRITICAL, (opt_parse_cfg_only?"FATAL: ":"ERROR: ") << name << " " << path << ": " << xstrerr(xerrno));
4063 // keep going to find more issues if we are only checking the config file with "-k parse"
4064 if (opt_parse_cfg_only)
4065 return;
4066 // this is fatal if it is found during startup or reconfigure
4067 if (opt_send_signal == -1 || opt_send_signal == SIGHUP)
4068 fatalf("%s %s: %s", name, path, xstrerr(xerrno));
4069 }
4070 }
4071
4072 #include "AccessLogEntry.h"
4073
4074 /**
4075 * We support several access_log configuration styles:
4076 *
4077 * #1: Deprecated ancient style without an explicit logging module:
4078 * access_log /var/log/access.log
4079 *
4080 * #2: The "none" logging module (i.e., no logging [of matching transactions]):
4081 * access_log none [acl ...]
4082 *
4083 * #3: Configurable logging module without named options:
4084 * Logformat or the first ACL name, whichever comes first, may not contain '='.
4085 * If no explicit logformat name is given, the first ACL name, if any,
4086 * should not be an existing logformat name or it will be treated as such.
4087 * access_log module:place [logformat_name] [acl ...]
4088 *
4089 * #4: Configurable logging module with name=value options such as logformat=x:
4090 * The first ACL name may not contain '='.
4091 * access_log module:place [option ...] [acl ...]
4092 *
4093 */
4094 static void
4095 parse_access_log(CustomLog ** logs)
4096 {
4097 const char *filename = ConfigParser::NextToken();
4098 if (!filename) {
4099 self_destruct();
4100 return;
4101 }
4102
4103 CustomLog *cl = (CustomLog *)xcalloc(1, sizeof(*cl));
4104
4105 cl->filename = xstrdup(filename);
4106 // default buffer size and fatal settings
4107 cl->bufferSize = 8*MAX_URL;
4108 cl->fatal = true;
4109
4110 if (strcmp(filename, "none") == 0) {
4111 cl->type = Log::Format::CLF_NONE;
4112 aclParseAclList(LegacyParser, &cl->aclList, filename);
4113 while (*logs)
4114 logs = &(*logs)->next;
4115 *logs = cl;
4116 return;
4117 }
4118
4119 cl->type = Log::Format::CLF_UNKNOWN;
4120 cl->rotateCount = -1; // default: use global logfile_rotate setting.
4121
4122 const char *token = ConfigParser::PeekAtToken();
4123 if (!token) { // style #1
4124 // no options to deal with
4125 } else if (!strchr(token, '=')) { // style #3
4126 // if logformat name is recognized,
4127 // pop the previewed token; Else it must be an ACL name
4128 if (setLogformat(cl, token, false))
4129 (void)ConfigParser::NextToken();
4130 } else { // style #4
4131 do {
4132 if (strncasecmp(token, "on-error=", 9) == 0) {
4133 if (strncasecmp(token+9, "die", 3) == 0) {
4134 cl->fatal = true;
4135 } else if (strncasecmp(token+9, "drop", 4) == 0) {
4136 cl->fatal = false;
4137 } else {
4138 debugs(3, DBG_CRITICAL, "Unknown value for on-error '" <<
4139 token << "' expected 'drop' or 'die'");
4140 xfree(cl->filename);
4141 xfree(cl);
4142 self_destruct();
4143 return;
4144 }
4145 } else if (strncasecmp(token, "buffer-size=", 12) == 0) {
4146 parseBytesOptionValue(&cl->bufferSize, B_BYTES_STR, token+12);
4147 } else if (strncasecmp(token, "rotate=", 7) == 0) {
4148 cl->rotateCount = xatoi(token + 7);
4149 } else if (strncasecmp(token, "logformat=", 10) == 0) {
4150 setLogformat(cl, token+10, true);
4151 } else if (!strchr(token, '=')) {
4152 // Do not pop the token; it must be an ACL name
4153 break; // done with name=value options, now to ACLs
4154 } else {
4155 debugs(3, DBG_CRITICAL, "Unknown access_log option " << token);
4156 xfree(cl->filename);
4157 xfree(cl);
4158 self_destruct();
4159 return;
4160 }
4161 // Pop the token, it was a valid "name=value" option
4162 (void)ConfigParser::NextToken();
4163 // Get next with preview ConfigParser::NextToken call.
4164 } while ((token = ConfigParser::PeekAtToken()) != NULL);
4165 }
4166
4167 // set format if it has not been specified explicitly
4168 if (cl->type == Log::Format::CLF_UNKNOWN)
4169 setLogformat(cl, "squid", true);
4170
4171 aclParseAclList(LegacyParser, &cl->aclList, cl->filename);
4172
4173 while (*logs)
4174 logs = &(*logs)->next;
4175
4176 *logs = cl;
4177 }
4178
4179 /// sets CustomLog::type and, if needed, CustomLog::lf
4180 /// returns false iff there is no named log format
4181 static bool
4182 setLogformat(CustomLog *cl, const char *logdef_name, const bool dieWhenMissing)
4183 {
4184 assert(cl);
4185 assert(logdef_name);
4186
4187 debugs(3, 9, "possible " << cl->filename << " logformat: " << logdef_name);
4188
4189 if (cl->type != Log::Format::CLF_UNKNOWN) {
4190 debugs(3, DBG_CRITICAL, "FATAL: Second logformat name in one access_log: " <<
4191 logdef_name << " " << cl->type << " ? " << Log::Format::CLF_NONE);
4192 self_destruct();
4193 return false;
4194 }
4195
4196 /* look for the definition pointer corresponding to this name */
4197 Format::Format *lf = Log::TheConfig.logformats;
4198
4199 while (lf != NULL) {
4200 debugs(3, 9, "Comparing against '" << lf->name << "'");
4201
4202 if (strcmp(lf->name, logdef_name) == 0)
4203 break;
4204
4205 lf = lf->next;
4206 }
4207
4208 if (lf != NULL) {
4209 cl->type = Log::Format::CLF_CUSTOM;
4210 cl->logFormat = lf;
4211 } else if (strcmp(logdef_name, "auto") == 0) {
4212 debugs(0, DBG_CRITICAL, "WARNING: Log format 'auto' no longer exists. Using 'squid' instead.");
4213 cl->type = Log::Format::CLF_SQUID;
4214 } else if (strcmp(logdef_name, "squid") == 0) {
4215 cl->type = Log::Format::CLF_SQUID;
4216 } else if (strcmp(logdef_name, "common") == 0) {
4217 cl->type = Log::Format::CLF_COMMON;
4218 } else if (strcmp(logdef_name, "combined") == 0) {
4219 cl->type = Log::Format::CLF_COMBINED;
4220 #if ICAP_CLIENT
4221 } else if (strcmp(logdef_name, "icap_squid") == 0) {
4222 cl->type = Log::Format::CLF_ICAP_SQUID;
4223 #endif
4224 } else if (strcmp(logdef_name, "useragent") == 0) {
4225 cl->type = Log::Format::CLF_USERAGENT;
4226 } else if (strcmp(logdef_name, "referrer") == 0) {
4227 cl->type = Log::Format::CLF_REFERER;
4228 } else if (dieWhenMissing) {
4229 debugs(3, DBG_CRITICAL, "FATAL: Log format '" << logdef_name << "' is not defined");
4230 self_destruct();
4231 return false;
4232 } else {
4233 return false;
4234 }
4235
4236 return true;
4237 }
4238
4239 static int
4240 check_null_access_log(CustomLog *customlog_definitions)
4241 {
4242 return customlog_definitions == NULL;
4243 }
4244
4245 static void
4246 dump_access_log(StoreEntry * entry, const char *name, CustomLog * logs)
4247 {
4248 CustomLog *log;
4249
4250 for (log = logs; log; log = log->next) {
4251 storeAppendPrintf(entry, "%s ", name);
4252
4253 switch (log->type) {
4254
4255 case Log::Format::CLF_CUSTOM:
4256 storeAppendPrintf(entry, "%s logformat=%s", log->filename, log->logFormat->name);
4257 break;
4258
4259 case Log::Format::CLF_NONE:
4260 storeAppendPrintf(entry, "logformat=none");
4261 break;
4262
4263 case Log::Format::CLF_SQUID:
4264 // this is the default, no need to add to the dump
4265 //storeAppendPrintf(entry, "%s logformat=squid", log->filename);
4266 break;
4267
4268 case Log::Format::CLF_COMBINED:
4269 storeAppendPrintf(entry, "%s logformat=combined", log->filename);
4270 break;
4271
4272 case Log::Format::CLF_COMMON:
4273 storeAppendPrintf(entry, "%s logformat=common", log->filename);
4274 break;
4275
4276 #if ICAP_CLIENT
4277 case Log::Format::CLF_ICAP_SQUID:
4278 storeAppendPrintf(entry, "%s logformat=icap_squid", log->filename);
4279 break;
4280 #endif
4281 case Log::Format::CLF_USERAGENT:
4282 storeAppendPrintf(entry, "%s logformat=useragent", log->filename);
4283 break;
4284
4285 case Log::Format::CLF_REFERER:
4286 storeAppendPrintf(entry, "%s logformat=referrer", log->filename);
4287 break;
4288
4289 case Log::Format::CLF_UNKNOWN:
4290 break;
4291 }
4292
4293 // default is on-error=die
4294 if (!log->fatal)
4295 storeAppendPrintf(entry, " on-error=drop");
4296
4297 // default: 64KB
4298 if (log->bufferSize != 64*1024)
4299 storeAppendPrintf(entry, " buffer-size=%" PRIuSIZE, log->bufferSize);
4300
4301 if (log->rotateCount >= 0)
4302 storeAppendPrintf(entry, " rotate=%d", log->rotateCount);
4303
4304 if (log->aclList)
4305 dump_acl_list(entry, log->aclList);
4306
4307 storeAppendPrintf(entry, "\n");
4308 }
4309 }
4310
4311 static void
4312 free_access_log(CustomLog ** definitions)
4313 {
4314 while (*definitions) {
4315 CustomLog *log = *definitions;
4316 *definitions = log->next;
4317
4318 log->logFormat = NULL;
4319 log->type = Log::Format::CLF_UNKNOWN;
4320
4321 if (log->aclList)
4322 aclDestroyAclList(&log->aclList);
4323
4324 safe_free(log->filename);
4325
4326 xfree(log);
4327 }
4328 }
4329
4330 #if HAVE_CPU_AFFINITY /* until somebody else needs this general code */
4331 /// parses list of integers form name=N1,N2,N3,...
4332 static bool
4333 parseNamedIntList(const char *data, const String &name, std::vector<int> &list)
4334 {
4335 if (data && (strncmp(data, name.rawBuf(), name.size()) == 0)) {
4336 data += name.size();
4337 if (*data == '=') {
4338 while (true) {
4339 ++data;
4340 int value = 0;
4341 if (!StringToInt(data, value, &data, 10))
4342 break;
4343 list.push_back(value);
4344 if (*data == '\0' || *data != ',')
4345 break;
4346 }
4347 }
4348 }
4349 return data && *data == '\0';
4350 }
4351 #endif
4352
4353 static void
4354 parse_CpuAffinityMap(CpuAffinityMap **const cpuAffinityMap)
4355 {
4356 #if !HAVE_CPU_AFFINITY
4357 debugs(3, DBG_CRITICAL, "FATAL: Squid built with no CPU affinity " <<
4358 "support, do not set 'cpu_affinity_map'");
4359 self_destruct();
4360
4361 #else /* HAVE_CPU_AFFINITY */
4362 if (!*cpuAffinityMap)
4363 *cpuAffinityMap = new CpuAffinityMap;
4364
4365 const char *const pToken = ConfigParser::NextToken();
4366 const char *const cToken = ConfigParser::NextToken();
4367 std::vector<int> processes, cores;
4368 if (!parseNamedIntList(pToken, "process_numbers", processes)) {
4369 debugs(3, DBG_CRITICAL, "FATAL: bad 'process_numbers' parameter " <<
4370 "in 'cpu_affinity_map'");
4371 self_destruct();
4372 } else if (!parseNamedIntList(cToken, "cores", cores)) {
4373 debugs(3, DBG_CRITICAL, "FATAL: bad 'cores' parameter in " <<
4374 "'cpu_affinity_map'");
4375 self_destruct();
4376 } else if (!(*cpuAffinityMap)->add(processes, cores)) {
4377 debugs(3, DBG_CRITICAL, "FATAL: bad 'cpu_affinity_map'; " <<
4378 "process_numbers and cores lists differ in length or " <<
4379 "contain numbers <= 0");
4380 self_destruct();
4381 }
4382 #endif
4383 }
4384
4385 static void
4386 dump_CpuAffinityMap(StoreEntry *const entry, const char *const name, const CpuAffinityMap *const cpuAffinityMap)
4387 {
4388 if (cpuAffinityMap) {
4389 storeAppendPrintf(entry, "%s process_numbers=", name);
4390 for (size_t i = 0; i < cpuAffinityMap->processes().size(); ++i) {
4391 storeAppendPrintf(entry, "%s%i", (i ? "," : ""),
4392 cpuAffinityMap->processes()[i]);
4393 }
4394 storeAppendPrintf(entry, " cores=");
4395 for (size_t i = 0; i < cpuAffinityMap->cores().size(); ++i) {
4396 storeAppendPrintf(entry, "%s%i", (i ? "," : ""),
4397 cpuAffinityMap->cores()[i]);
4398 }
4399 storeAppendPrintf(entry, "\n");
4400 }
4401 }
4402
4403 static void
4404 free_CpuAffinityMap(CpuAffinityMap **const cpuAffinityMap)
4405 {
4406 delete *cpuAffinityMap;
4407 *cpuAffinityMap = NULL;
4408 }
4409
4410 #if USE_ADAPTATION
4411
4412 static void
4413 parse_adaptation_service_set_type()
4414 {
4415 Adaptation::Config::ParseServiceSet();
4416 }
4417
4418 static void
4419 parse_adaptation_service_chain_type()
4420 {
4421 Adaptation::Config::ParseServiceChain();
4422 }
4423
4424 static void
4425 parse_adaptation_access_type()
4426 {
4427 Adaptation::Config::ParseAccess(LegacyParser);
4428 }
4429 #endif /* USE_ADAPTATION */
4430
4431 #if ICAP_CLIENT
4432
4433 static void
4434 parse_icap_service_type(Adaptation::Icap::Config * cfg)
4435 {
4436 cfg->parseService();
4437 }
4438
4439 static void
4440 free_icap_service_type(Adaptation::Icap::Config * cfg)
4441 {
4442 cfg->freeService();
4443 }
4444
4445 static void
4446 dump_icap_service_type(StoreEntry * entry, const char *name, const Adaptation::Icap::Config &cfg)
4447 {
4448 cfg.dumpService(entry, name);
4449 }
4450
4451 static void
4452 parse_icap_class_type()
4453 {
4454 debugs(93, DBG_CRITICAL, "WARNING: 'icap_class' is deprecated. " <<
4455 "Use 'adaptation_service_set' instead");
4456 Adaptation::Config::ParseServiceSet();
4457 }
4458
4459 static void
4460 parse_icap_access_type()
4461 {
4462 debugs(93, DBG_CRITICAL, "WARNING: 'icap_access' is deprecated. " <<
4463 "Use 'adaptation_access' instead");
4464 Adaptation::Config::ParseAccess(LegacyParser);
4465 }
4466
4467 #endif
4468
4469 #if USE_ECAP
4470
4471 static void
4472 parse_ecap_service_type(Adaptation::Ecap::Config * cfg)
4473 {
4474 cfg->parseService();
4475 }
4476
4477 static void
4478 free_ecap_service_type(Adaptation::Ecap::Config * cfg)
4479 {
4480 cfg->freeService();
4481 }
4482
4483 static void
4484 dump_ecap_service_type(StoreEntry * entry, const char *name, const Adaptation::Ecap::Config &cfg)
4485 {
4486 cfg.dumpService(entry, name);
4487 }
4488
4489 #endif /* USE_ECAP */
4490
4491 #if ICAP_CLIENT
4492 static void parse_icap_service_failure_limit(Adaptation::Icap::Config *cfg)
4493 {
4494 char *token;
4495 cfg->service_failure_limit = GetInteger();
4496
4497 if ((token = ConfigParser::NextToken()) == NULL)
4498 return;
4499
4500 if (strcmp(token,"in") != 0) {
4501 debugs(3, DBG_CRITICAL, "expecting 'in' on'" << config_input_line << "'");
4502 self_destruct();
4503 return;
4504 }
4505
4506 parse_time_t(&cfg->oldest_service_failure);
4507 }
4508
4509 static void dump_icap_service_failure_limit(StoreEntry *entry, const char *name, const Adaptation::Icap::Config &cfg)
4510 {
4511 storeAppendPrintf(entry, "%s %d", name, cfg.service_failure_limit);
4512 if (cfg.oldest_service_failure > 0) {
4513 storeAppendPrintf(entry, " in %d seconds", (int)cfg.oldest_service_failure);
4514 }
4515 storeAppendPrintf(entry, "\n");
4516 }
4517
4518 static void free_icap_service_failure_limit(Adaptation::Icap::Config *cfg)
4519 {
4520 cfg->oldest_service_failure = 0;
4521 cfg->service_failure_limit = 0;
4522 }
4523 #endif
4524
4525 #if USE_OPENSSL
4526 static void parse_sslproxy_cert_adapt(sslproxy_cert_adapt **cert_adapt)
4527 {
4528 char *al;
4529 sslproxy_cert_adapt *ca = (sslproxy_cert_adapt *) xcalloc(1, sizeof(sslproxy_cert_adapt));
4530 if ((al = ConfigParser::NextToken()) == NULL) {
4531 xfree(ca);
4532 self_destruct();
4533 return;
4534 }
4535
4536 const char *param;
4537 if ( char *s = strchr(al, '{')) {
4538 *s = '\0'; // terminate the al string
4539 ++s;
4540 param = s;
4541 s = strchr(s, '}');
4542 if (!s) {
4543 xfree(ca);
4544 self_destruct();
4545 return;
4546 }
4547 *s = '\0';
4548 } else
4549 param = NULL;
4550
4551 if (strcmp(al, Ssl::CertAdaptAlgorithmStr[Ssl::algSetValidAfter]) == 0) {
4552 ca->alg = Ssl::algSetValidAfter;
4553 ca->param = xstrdup("on");
4554 } else if (strcmp(al, Ssl::CertAdaptAlgorithmStr[Ssl::algSetValidBefore]) == 0) {
4555 ca->alg = Ssl::algSetValidBefore;
4556 ca->param = xstrdup("on");
4557 } else if (strcmp(al, Ssl::CertAdaptAlgorithmStr[Ssl::algSetCommonName]) == 0) {
4558 ca->alg = Ssl::algSetCommonName;
4559 if (param) {
4560 if (strlen(param) > 64) {
4561 debugs(3, DBG_CRITICAL, "FATAL: sslproxy_cert_adapt: setCommonName{" <<param << "} : using common name longer than 64 bytes is not supported");
4562 xfree(ca);
4563 self_destruct();
4564 return;
4565 }
4566 ca->param = xstrdup(param);
4567 }
4568 } else {
4569 debugs(3, DBG_CRITICAL, "FATAL: sslproxy_cert_adapt: unknown cert adaptation algorithm: " << al);
4570 xfree(ca);
4571 self_destruct();
4572 return;
4573 }
4574
4575 aclParseAclList(LegacyParser, &ca->aclList, al);
4576
4577 while (*cert_adapt)
4578 cert_adapt = &(*cert_adapt)->next;
4579
4580 *cert_adapt = ca;
4581 }
4582
4583 static void dump_sslproxy_cert_adapt(StoreEntry *entry, const char *name, sslproxy_cert_adapt *cert_adapt)
4584 {
4585 for (sslproxy_cert_adapt *ca = cert_adapt; ca != NULL; ca = ca->next) {
4586 storeAppendPrintf(entry, "%s ", name);
4587 storeAppendPrintf(entry, "%s{%s} ", Ssl::sslCertAdaptAlgoritm(ca->alg), ca->param);
4588 if (ca->aclList)
4589 dump_acl_list(entry, ca->aclList);
4590 storeAppendPrintf(entry, "\n");
4591 }
4592 }
4593
4594 static void free_sslproxy_cert_adapt(sslproxy_cert_adapt **cert_adapt)
4595 {
4596 while (*cert_adapt) {
4597 sslproxy_cert_adapt *ca = *cert_adapt;
4598 *cert_adapt = ca->next;
4599 safe_free(ca->param);
4600
4601 if (ca->aclList)
4602 aclDestroyAclList(&ca->aclList);
4603
4604 safe_free(ca);
4605 }
4606 }
4607
4608 static void parse_sslproxy_cert_sign(sslproxy_cert_sign **cert_sign)
4609 {
4610 char *al;
4611 sslproxy_cert_sign *cs = (sslproxy_cert_sign *) xcalloc(1, sizeof(sslproxy_cert_sign));
4612 if ((al = ConfigParser::NextToken()) == NULL) {
4613 xfree(cs);
4614 self_destruct();
4615 return;
4616 }
4617
4618 if (strcmp(al, Ssl::CertSignAlgorithmStr[Ssl::algSignTrusted]) == 0)
4619 cs->alg = Ssl::algSignTrusted;
4620 else if (strcmp(al, Ssl::CertSignAlgorithmStr[Ssl::algSignUntrusted]) == 0)
4621 cs->alg = Ssl::algSignUntrusted;
4622 else if (strcmp(al, Ssl::CertSignAlgorithmStr[Ssl::algSignSelf]) == 0)
4623 cs->alg = Ssl::algSignSelf;
4624 else {
4625 debugs(3, DBG_CRITICAL, "FATAL: sslproxy_cert_sign: unknown cert signing algorithm: " << al);
4626 xfree(cs);
4627 self_destruct();
4628 return;
4629 }
4630
4631 aclParseAclList(LegacyParser, &cs->aclList, al);
4632
4633 while (*cert_sign)
4634 cert_sign = &(*cert_sign)->next;
4635
4636 *cert_sign = cs;
4637 }
4638
4639 static void dump_sslproxy_cert_sign(StoreEntry *entry, const char *name, sslproxy_cert_sign *cert_sign)
4640 {
4641 sslproxy_cert_sign *cs;
4642 for (cs = cert_sign; cs != NULL; cs = cs->next) {
4643 storeAppendPrintf(entry, "%s ", name);
4644 storeAppendPrintf(entry, "%s ", Ssl::certSignAlgorithm(cs->alg));
4645 if (cs->aclList)
4646 dump_acl_list(entry, cs->aclList);
4647 storeAppendPrintf(entry, "\n");
4648 }
4649 }
4650
4651 static void free_sslproxy_cert_sign(sslproxy_cert_sign **cert_sign)
4652 {
4653 while (*cert_sign) {
4654 sslproxy_cert_sign *cs = *cert_sign;
4655 *cert_sign = cs->next;
4656
4657 if (cs->aclList)
4658 aclDestroyAclList(&cs->aclList);
4659
4660 safe_free(cs);
4661 }
4662 }
4663
4664 class sslBumpCfgRr: public ::RegisteredRunner
4665 {
4666 public:
4667 static Ssl::BumpMode lastDeprecatedRule;
4668 /* RegisteredRunner API */
4669 virtual void finalizeConfig();
4670 };
4671
4672 Ssl::BumpMode sslBumpCfgRr::lastDeprecatedRule = Ssl::bumpEnd;
4673
4674 RunnerRegistrationEntry(sslBumpCfgRr);
4675
4676 void
4677 sslBumpCfgRr::finalizeConfig()
4678 {
4679 if (lastDeprecatedRule != Ssl::bumpEnd) {
4680 assert( lastDeprecatedRule == Ssl::bumpClientFirst || lastDeprecatedRule == Ssl::bumpNone);
4681 static char buf[1024];
4682 if (lastDeprecatedRule == Ssl::bumpClientFirst) {
4683 strcpy(buf, "ssl_bump deny all");
4684 debugs(3, DBG_CRITICAL, "WARNING: auto-converting deprecated implicit "
4685 "\"ssl_bump deny all\" to \"ssl_bump none all\". New ssl_bump configurations "
4686 "must not use implicit rules. Update your ssl_bump rules.");
4687 } else {
4688 strcpy(buf, "ssl_bump allow all");
4689 debugs(3, DBG_CRITICAL, "SECURITY NOTICE: auto-converting deprecated implicit "
4690 "\"ssl_bump allow all\" to \"ssl_bump client-first all\" which is usually "
4691 "inferior to the newer server-first bumping mode. New ssl_bump"
4692 " configurations must not use implicit rules. Update your ssl_bump rules.");
4693 }
4694 parse_line(buf);
4695 }
4696 }
4697
4698 static void parse_sslproxy_ssl_bump(acl_access **ssl_bump)
4699 {
4700 typedef const char *BumpCfgStyle;
4701 BumpCfgStyle bcsNone = NULL;
4702 BumpCfgStyle bcsNew = "new client/server-first/none";
4703 BumpCfgStyle bcsOld = "deprecated allow/deny";
4704 static BumpCfgStyle bumpCfgStyleLast = bcsNone;
4705 BumpCfgStyle bumpCfgStyleNow = bcsNone;
4706 char *bm;
4707 if ((bm = ConfigParser::NextToken()) == NULL) {
4708 self_destruct();
4709 return;
4710 }
4711
4712 // if this is the first rule proccessed
4713 if (*ssl_bump == NULL) {
4714 bumpCfgStyleLast = bcsNone;
4715 sslBumpCfgRr::lastDeprecatedRule = Ssl::bumpEnd;
4716 }
4717
4718 auto action = Acl::Answer(ACCESS_ALLOWED);
4719
4720 if (strcmp(bm, Ssl::BumpModeStr[Ssl::bumpClientFirst]) == 0) {
4721 action.kind = Ssl::bumpClientFirst;
4722 bumpCfgStyleNow = bcsNew;
4723 } else if (strcmp(bm, Ssl::BumpModeStr[Ssl::bumpServerFirst]) == 0) {
4724 action.kind = Ssl::bumpServerFirst;
4725 bumpCfgStyleNow = bcsNew;
4726 } else if (strcmp(bm, Ssl::BumpModeStr[Ssl::bumpPeek]) == 0) {
4727 action.kind = Ssl::bumpPeek;
4728 bumpCfgStyleNow = bcsNew;
4729 } else if (strcmp(bm, Ssl::BumpModeStr[Ssl::bumpStare]) == 0) {
4730 action.kind = Ssl::bumpStare;
4731 bumpCfgStyleNow = bcsNew;
4732 } else if (strcmp(bm, Ssl::BumpModeStr[Ssl::bumpSplice]) == 0) {
4733 action.kind = Ssl::bumpSplice;
4734 bumpCfgStyleNow = bcsNew;
4735 } else if (strcmp(bm, Ssl::BumpModeStr[Ssl::bumpBump]) == 0) {
4736 action.kind = Ssl::bumpBump;
4737 bumpCfgStyleNow = bcsNew;
4738 } else if (strcmp(bm, Ssl::BumpModeStr[Ssl::bumpTerminate]) == 0) {
4739 action.kind = Ssl::bumpTerminate;
4740 bumpCfgStyleNow = bcsNew;
4741 } else if (strcmp(bm, Ssl::BumpModeStr[Ssl::bumpNone]) == 0) {
4742 action.kind = Ssl::bumpNone;
4743 bumpCfgStyleNow = bcsNew;
4744 } else if (strcmp(bm, "allow") == 0) {
4745 debugs(3, DBG_CRITICAL, "SECURITY NOTICE: auto-converting deprecated "
4746 "\"ssl_bump allow <acl>\" to \"ssl_bump client-first <acl>\" which "
4747 "is usually inferior to the newer server-first "
4748 "bumping mode. Update your ssl_bump rules.");
4749 action.kind = Ssl::bumpClientFirst;
4750 bumpCfgStyleNow = bcsOld;
4751 sslBumpCfgRr::lastDeprecatedRule = Ssl::bumpClientFirst;
4752 } else if (strcmp(bm, "deny") == 0) {
4753 debugs(3, DBG_CRITICAL, "WARNING: auto-converting deprecated "
4754 "\"ssl_bump deny <acl>\" to \"ssl_bump none <acl>\". Update "
4755 "your ssl_bump rules.");
4756 action.kind = Ssl::bumpNone;
4757 bumpCfgStyleNow = bcsOld;
4758 sslBumpCfgRr::lastDeprecatedRule = Ssl::bumpNone;
4759 } else {
4760 debugs(3, DBG_CRITICAL, "FATAL: unknown ssl_bump mode: " << bm);
4761 self_destruct();
4762 return;
4763 }
4764
4765 if (bumpCfgStyleLast != bcsNone && bumpCfgStyleNow != bumpCfgStyleLast) {
4766 debugs(3, DBG_CRITICAL, "FATAL: do not mix " << bumpCfgStyleNow << " actions with " <<
4767 bumpCfgStyleLast << " actions. Update your ssl_bump rules.");
4768 self_destruct();
4769 return;
4770 }
4771
4772 bumpCfgStyleLast = bumpCfgStyleNow;
4773
4774 // empty rule OK
4775 ParseAclWithAction(ssl_bump, action, "ssl_bump");
4776 }
4777
4778 static void dump_sslproxy_ssl_bump(StoreEntry *entry, const char *name, acl_access *ssl_bump)
4779 {
4780 if (ssl_bump)
4781 dump_SBufList(entry, ssl_bump->treeDump(name, [](const Acl::Answer &action) {
4782 return Ssl::BumpModeStr.at(action.kind);
4783 }));
4784 }
4785
4786 static void free_sslproxy_ssl_bump(acl_access **ssl_bump)
4787 {
4788 free_acl_access(ssl_bump);
4789 }
4790
4791 #endif
4792
4793 static void dump_HeaderWithAclList(StoreEntry * entry, const char *name, HeaderWithAclList *headers)
4794 {
4795 if (!headers)
4796 return;
4797
4798 for (HeaderWithAclList::iterator hwa = headers->begin(); hwa != headers->end(); ++hwa) {
4799 storeAppendPrintf(entry, "%s %s %s", name, hwa->fieldName.c_str(), hwa->fieldValue.c_str());
4800 if (hwa->aclList)
4801 dump_acl_list(entry, hwa->aclList);
4802 storeAppendPrintf(entry, "\n");
4803 }
4804 }
4805
4806 static void parse_HeaderWithAclList(HeaderWithAclList **headers)
4807 {
4808 char *fn;
4809 if (!*headers) {
4810 *headers = new HeaderWithAclList;
4811 }
4812 if ((fn = ConfigParser::NextToken()) == NULL) {
4813 self_destruct();
4814 return;
4815 }
4816 HeaderWithAcl hwa;
4817 hwa.fieldName = fn;
4818 hwa.fieldId = Http::HeaderLookupTable.lookup(hwa.fieldName).id;
4819 if (hwa.fieldId == Http::HdrType::BAD_HDR)
4820 hwa.fieldId = Http::HdrType::OTHER;
4821
4822 Format::Format *nlf = new ::Format::Format("hdrWithAcl");
4823 ConfigParser::EnableMacros();
4824 String buf = ConfigParser::NextQuotedToken();
4825 ConfigParser::DisableMacros();
4826 hwa.fieldValue = buf.termedBuf();
4827 hwa.quoted = ConfigParser::LastTokenWasQuoted();
4828 if (hwa.quoted) {
4829 if (!nlf->parse(hwa.fieldValue.c_str())) {
4830 self_destruct();
4831 return;
4832 }
4833 hwa.valueFormat = nlf;
4834 } else
4835 delete nlf;
4836 aclParseAclList(LegacyParser, &hwa.aclList, (hwa.fieldName + ':' + hwa.fieldValue).c_str());
4837 (*headers)->push_back(hwa);
4838 }
4839
4840 static void free_HeaderWithAclList(HeaderWithAclList **header)
4841 {
4842 if (!(*header))
4843 return;
4844
4845 for (HeaderWithAclList::iterator hwa = (*header)->begin(); hwa != (*header)->end(); ++hwa) {
4846 if (hwa->aclList)
4847 aclDestroyAclList(&hwa->aclList);
4848
4849 if (hwa->valueFormat) {
4850 delete hwa->valueFormat;
4851 hwa->valueFormat = NULL;
4852 }
4853 }
4854 delete *header;
4855 *header = NULL;
4856 }
4857
4858 static void parse_note(Notes *notes)
4859 {
4860 assert(notes);
4861 notes->parse(LegacyParser);
4862 }
4863
4864 static void dump_note(StoreEntry *entry, const char *name, Notes &notes)
4865 {
4866 notes.dump(entry, name);
4867 }
4868
4869 static void free_note(Notes *notes)
4870 {
4871 notes->clean();
4872 }
4873
4874 static bool FtpEspvDeprecated = false;
4875 static void parse_ftp_epsv(acl_access **ftp_epsv)
4876 {
4877 Acl::Answer ftpEpsvDeprecatedAction;
4878 bool ftpEpsvIsDeprecatedRule = false;
4879
4880 char *t = ConfigParser::PeekAtToken();
4881 if (!t) {
4882 self_destruct();
4883 return;
4884 }
4885
4886 if (!strcmp(t, "off")) {
4887 (void)ConfigParser::NextToken();
4888 ftpEpsvIsDeprecatedRule = true;
4889 ftpEpsvDeprecatedAction = Acl::Answer(ACCESS_DENIED);
4890 } else if (!strcmp(t, "on")) {
4891 (void)ConfigParser::NextToken();
4892 ftpEpsvIsDeprecatedRule = true;
4893 ftpEpsvDeprecatedAction = Acl::Answer(ACCESS_ALLOWED);
4894 }
4895
4896 // Check for mixing "ftp_epsv on|off" and "ftp_epsv allow|deny .." rules:
4897 // 1) if this line is "ftp_epsv allow|deny ..." and already exist rules of "ftp_epsv on|off"
4898 // 2) if this line is "ftp_epsv on|off" and already exist rules of "ftp_epsv allow|deny ..."
4899 // then abort
4900 if ((!ftpEpsvIsDeprecatedRule && FtpEspvDeprecated) ||
4901 (ftpEpsvIsDeprecatedRule && !FtpEspvDeprecated && *ftp_epsv != NULL)) {
4902 debugs(3, DBG_CRITICAL, "FATAL: do not mix \"ftp_epsv on|off\" cfg lines with \"ftp_epsv allow|deny ...\" cfg lines. Update your ftp_epsv rules.");
4903 self_destruct();
4904 return;
4905 }
4906
4907 if (ftpEpsvIsDeprecatedRule) {
4908 // overwrite previous ftp_epsv lines
4909 delete *ftp_epsv;
4910 *ftp_epsv = nullptr;
4911
4912 if (ftpEpsvDeprecatedAction == Acl::Answer(ACCESS_DENIED)) {
4913 if (ACL *a = ACL::FindByName("all"))
4914 ParseAclWithAction(ftp_epsv, ftpEpsvDeprecatedAction, "ftp_epsv", a);
4915 else {
4916 self_destruct();
4917 return;
4918 }
4919 }
4920 FtpEspvDeprecated = true;
4921 } else {
4922 aclParseAccessLine(cfg_directive, LegacyParser, ftp_epsv);
4923 }
4924 }
4925
4926 static void dump_ftp_epsv(StoreEntry *entry, const char *name, acl_access *ftp_epsv)
4927 {
4928 if (ftp_epsv)
4929 dump_SBufList(entry, ftp_epsv->treeDump(name, Acl::AllowOrDeny));
4930 }
4931
4932 static void free_ftp_epsv(acl_access **ftp_epsv)
4933 {
4934 free_acl_access(ftp_epsv);
4935 FtpEspvDeprecated = false;
4936 }
4937
4938 /// Like parseTimeLine() but does not require the timeunit to be specified.
4939 /// If missed, the default 'second' timeunit is assumed.
4940 static std::chrono::seconds
4941 ParseUrlRewriteTimeout()
4942 {
4943 const auto timeValueToken = ConfigParser::NextToken();
4944 if (!timeValueToken)
4945 throw TexcHere("cannot read a time value");
4946
4947 using Seconds = std::chrono::seconds;
4948
4949 const auto parsedTimeValue = xatof(timeValueToken);
4950
4951 if (parsedTimeValue == 0)
4952 return std::chrono::seconds::zero();
4953
4954 std::chrono::nanoseconds parsedUnitDuration;
4955
4956 const auto unitToken = ConfigParser::PeekAtToken();
4957 if (parseTimeUnit<Seconds>(unitToken, parsedUnitDuration))
4958 (void)ConfigParser::NextToken();
4959 else {
4960 const auto defaultParsed = parseTimeUnit<Seconds>(T_SECOND_STR, parsedUnitDuration);
4961 assert(defaultParsed);
4962 debugs(3, DBG_PARSE_NOTE(DBG_IMPORTANT), ConfigParser::CurrentLocation() <<
4963 ": WARNING: missing time unit, using deprecated default '" << T_SECOND_STR << "'");
4964 }
4965
4966 const auto nanoseconds = CheckTimeValue(parsedTimeValue, parsedUnitDuration);
4967
4968 return FromNanoseconds<Seconds>(nanoseconds, parsedTimeValue);
4969 }
4970
4971 static void
4972 parse_UrlHelperTimeout(SquidConfig::UrlHelperTimeout *config)
4973 {
4974 // TODO: do not allow optional timeunit (as the documentation prescribes)
4975 // and use parseTimeLine() instead.
4976 Config.Timeout.urlRewrite = ParseUrlRewriteTimeout().count();
4977
4978 char *key, *value;
4979 while(ConfigParser::NextKvPair(key, value)) {
4980 if (strcasecmp(key, "on_timeout") == 0) {
4981 if (strcasecmp(value, "bypass") == 0)
4982 config->action = toutActBypass;
4983 else if (strcasecmp(value, "fail") == 0)
4984 config->action = toutActFail;
4985 else if (strcasecmp(value, "retry") == 0)
4986 config->action = toutActRetry;
4987 else if (strcasecmp(value, "use_configured_response") == 0) {
4988 config->action = toutActUseConfiguredResponse;
4989 } else {
4990 debugs(3, DBG_CRITICAL, "FATAL: unsupported \"on_timeout\" action: " << value);
4991 self_destruct();
4992 return;
4993 }
4994 } else if (strcasecmp(key, "response") == 0) {
4995 config->response = xstrdup(value);
4996 } else {
4997 debugs(3, DBG_CRITICAL, "FATAL: unsupported option " << key);
4998 self_destruct();
4999 return;
5000 }
5001 }
5002
5003 if (config->action == toutActUseConfiguredResponse && !config->response) {
5004 debugs(3, DBG_CRITICAL, "FATAL: Expected 'response=' option after 'on_timeout=use_configured_response' option");
5005 self_destruct();
5006 }
5007
5008 if (config->action != toutActUseConfiguredResponse && config->response) {
5009 debugs(3, DBG_CRITICAL, "FATAL: 'response=' option is valid only when used with the 'on_timeout=use_configured_response' option");
5010 self_destruct();
5011 }
5012 }
5013
5014 static void
5015 dump_UrlHelperTimeout(StoreEntry *entry, const char *name, SquidConfig::UrlHelperTimeout &config)
5016 {
5017 const char *onTimedOutActions[] = {"bypass", "fail", "retry", "use_configured_response"};
5018 assert(config.action >= 0 && config.action <= toutActUseConfiguredResponse);
5019
5020 dump_time_t(entry, name, Config.Timeout.urlRewrite);
5021 storeAppendPrintf(entry, " on_timeout=%s", onTimedOutActions[config.action]);
5022
5023 if (config.response)
5024 storeAppendPrintf(entry, " response=\"%s\"", config.response);
5025
5026 storeAppendPrintf(entry, "\n");
5027 }
5028
5029 static void
5030 free_UrlHelperTimeout(SquidConfig::UrlHelperTimeout *config)
5031 {
5032 Config.Timeout.urlRewrite = 0;
5033 config->action = 0;
5034 safe_free(config->response);
5035 }
5036
5037 static void
5038 parse_configuration_includes_quoted_values(bool *)
5039 {
5040 int val = 0;
5041 parse_onoff(&val);
5042
5043 // If quoted values is set to on then enable new strict mode parsing
5044 if (val) {
5045 ConfigParser::RecognizeQuotedValues = true;
5046 ConfigParser::StrictMode = true;
5047 } else {
5048 ConfigParser::RecognizeQuotedValues = false;
5049 ConfigParser::StrictMode = false;
5050 }
5051 }
5052
5053 static void
5054 dump_configuration_includes_quoted_values(StoreEntry *const entry, const char *const name, bool)
5055 {
5056 int val = ConfigParser::RecognizeQuotedValues ? 1 : 0;
5057 dump_onoff(entry, name, val);
5058 }
5059
5060 static void
5061 free_configuration_includes_quoted_values(bool *)
5062 {
5063 ConfigParser::RecognizeQuotedValues = false;
5064 ConfigParser::StrictMode = false;
5065 }
5066
5067 static void
5068 parse_on_unsupported_protocol(acl_access **access)
5069 {
5070 char *tm;
5071 if ((tm = ConfigParser::NextToken()) == NULL) {
5072 self_destruct();
5073 return;
5074 }
5075
5076 auto action = Acl::Answer(ACCESS_ALLOWED);
5077 if (strcmp(tm, "tunnel") == 0)
5078 action.kind = 1;
5079 else if (strcmp(tm, "respond") == 0)
5080 action.kind = 2;
5081 else {
5082 debugs(3, DBG_CRITICAL, "FATAL: unknown on_unsupported_protocol mode: " << tm);
5083 self_destruct();
5084 return;
5085 }
5086
5087 // empty rule OK
5088 ParseAclWithAction(access, action, "on_unsupported_protocol");
5089 }
5090
5091 static void
5092 dump_on_unsupported_protocol(StoreEntry *entry, const char *name, acl_access *access)
5093 {
5094 static const std::vector<const char *> onErrorTunnelMode = {
5095 "none",
5096 "tunnel",
5097 "respond"
5098 };
5099 if (access) {
5100 SBufList lines = access->treeDump(name, [](const Acl::Answer &action) {
5101 return onErrorTunnelMode.at(action.kind);
5102 });
5103 dump_SBufList(entry, lines);
5104 }
5105 }
5106
5107 static void
5108 free_on_unsupported_protocol(acl_access **access)
5109 {
5110 free_acl_access(access);
5111 }
5112