]> git.ipfire.org Git - thirdparty/squid.git/blame - src/errorpage.cc
SourceFormat Enforcement
[thirdparty/squid.git] / src / errorpage.cc
CommitLineData
30a4f2a8 1/*
f6e9a3ee 2 * Copyright (C) 1996-2019 The Squid Software Foundation and contributors
e25c139f 3 *
bbc27441
AJ
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.
30a4f2a8 7 */
bbc27441
AJ
8
9/* DEBUG: section 04 Error Generation */
10
f7f3304a 11#include "squid.h"
8a01b99e 12#include "cache_cf.h"
92ae4c86 13#include "clients/forward.h"
e0d28505 14#include "comm/Connection.h"
ec41b64c 15#include "comm/Write.h"
582c2af2 16#include "err_detail_type.h"
aa839030 17#include "errorpage.h"
602d9612 18#include "fde.h"
b3f7fd88 19#include "fs_io.h"
25f98340 20#include "html_quote.h"
a5bac1d2 21#include "HttpHeaderTools.h"
528b2c61 22#include "HttpReply.h"
23#include "HttpRequest.h"
0eb49b6d 24#include "MemBuf.h"
602d9612 25#include "MemObject.h"
1fa9b1a7 26#include "rfc1738.h"
4d5904f7 27#include "SquidConfig.h"
602d9612
A
28#include "Store.h"
29#include "tools.h"
d295d770 30#include "wordlist.h"
4e540555
FC
31#if USE_AUTH
32#include "auth/UserRequest.h"
33#endif
34#include "SquidTime.h"
cb4f4424 35#if USE_OPENSSL
4e540555
FC
36#include "ssl/ErrorDetailManager.h"
37#endif
02922e76 38
63be0a78 39/**
40 \defgroup ErrorPageInternal Error Page Internals
41 \ingroup ErrorPageAPI
42 *
f439fbd2 43 \section ErrorPagesAbstract Abstract:
63be0a78 44 * These routines are used to generate error messages to be
45 * sent to clients. The error type is used to select between
46 * the various message formats. (formats are stored in the
47 * Config.errorDirectory)
48 */
49
605f2c3e 50#if !defined(DEFAULT_SQUID_ERROR_DIR)
43000484
AJ
51/** Where to look for errors if config path fails.
52 \note Please use ./configure --datadir=/path instead of patching
53 */
54#define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
55#endif
56
63be0a78 57/// \ingroup ErrorPageInternal
aa839030 58CBDATA_CLASS_INIT(ErrorState);
59
02922e76 60/* local types */
61
63be0a78 62/// \ingroup ErrorPageInternal
9e008dda 63typedef struct {
02922e76 64 int id;
65 char *page_name;
955394ce 66 Http::StatusCode page_redirect;
2fadd50d 67} ErrorDynamicPageInfo;
02922e76 68
69/* local constant and vars */
70
63be0a78 71/**
cfdb8f88 72 \ingroup ErrorPageInternal
63be0a78 73 *
74 \note hard coded error messages are not appended with %S
75 * automagically to give you more control on the format
1d803566 76 */
9e008dda 77static const struct {
f53969cc 78 int type; /* and page_id */
2ac76861 79 const char *text;
62e76326 80}
81
82error_hard_text[] = {
83
9e008dda
AJ
84 {
85 ERR_SQUID_SIGNATURE,
86 "\n<br>\n"
87 "<hr>\n"
88 "<div id=\"footer\">\n"
89 "Generated %T by %h (%s)\n"
90 "</div>\n"
91 "</body></html>\n"
92 },
93 {
94 TCP_RESET,
95 "reset"
96 }
97};
02922e76 98
63be0a78 99/// \ingroup ErrorPageInternal
c8ea3cc0 100static std::vector<ErrorDynamicPageInfo *> ErrorDynamicPages;
02922e76 101
102/* local prototypes */
103
63be0a78 104/// \ingroup ErrorPageInternal
2ac76861 105static const int error_hard_text_count = sizeof(error_hard_text) / sizeof(*error_hard_text);
63be0a78 106
107/// \ingroup ErrorPageInternal
02922e76 108static char **error_text = NULL;
63be0a78 109
110/// \ingroup ErrorPageInternal
02922e76 111static int error_page_count = 0;
9b312a19 112
5b52cb6c 113/// \ingroup ErrorPageInternal
0ae3294a 114static MemBuf error_stylesheet;
5b52cb6c 115
1d803566 116static const char *errorFindHardText(err_type type);
c68e9c6b 117static ErrorDynamicPageInfo *errorDynamicPageInfoCreate(int id, const char *page_name);
118static void errorDynamicPageInfoDestroy(ErrorDynamicPageInfo * info);
2b663917 119static IOCB errorSendComplete;
1e74c110 120
02259ff8
CT
121/// \ingroup ErrorPageInternal
122/// manages an error page template
dc49061a
A
123class ErrorPageFile: public TemplateFile
124{
02259ff8 125public:
ced8def3 126 ErrorPageFile(const char *name, const err_type code) : TemplateFile(name,code) {textBuf.init();}
02259ff8
CT
127
128 /// The template text data read from disk
129 const char *text() { return textBuf.content(); }
130
131private:
132 /// stores the data read from disk to a local buffer
ced8def3 133 virtual bool parse(const char *buf, int len, bool) {
02259ff8
CT
134 if (len)
135 textBuf.append(buf, len);
136 return true;
137 }
138
139 MemBuf textBuf; ///< A buffer to store the error page
140};
e6ccf245 141
63be0a78 142/// \ingroup ErrorPageInternal
e6ccf245 143err_type &operator++ (err_type &anErr)
144{
1f1ae50a 145 int tmp = (int)anErr;
146 anErr = (err_type)(++tmp);
e6ccf245 147 return anErr;
148}
4ff59fc7 149
63be0a78 150/// \ingroup ErrorPageInternal
62e76326 151int operator - (err_type const &anErr, err_type const &anErr2)
152{
4ff59fc7 153 return (int)anErr - (int)anErr2;
154}
155
b8d8561b 156void
0673c0ba 157errorInitialize(void)
fa966b74 158{
728da2ee 159 err_type i;
1d803566 160 const char *text;
4ff59fc7 161 error_page_count = ERR_MAX + ErrorDynamicPages.size();
e6ccf245 162 error_text = static_cast<char **>(xcalloc(error_page_count, sizeof(char *)));
62e76326 163
e6ccf245 164 for (i = ERR_NONE, ++i; i < error_page_count; ++i) {
62e76326 165 safe_free(error_text[i]);
62e76326 166
43000484
AJ
167 if ((text = errorFindHardText(i))) {
168 /**\par
169 * Index any hard-coded error text into defaults.
170 */
62e76326 171 error_text[i] = xstrdup(text);
43000484
AJ
172
173 } else if (i < ERR_MAX) {
174 /**\par
175 * Index precompiled fixed template files from one of two sources:
176 * (a) default language translation directory (error_default_language)
177 * (b) admin specified custom directory (error_directory)
178 */
8ff2520a 179 ErrorPageFile errTmpl(err_type_str[i], i);
02259ff8 180 error_text[i] = errTmpl.loadDefault() ? xstrdup(errTmpl.text()) : NULL;
62e76326 181 } else {
43000484
AJ
182 /** \par
183 * Index any unknown file names used by deny_info.
184 */
e6334d92 185 ErrorDynamicPageInfo *info = ErrorDynamicPages.at(i - ERR_MAX);
62e76326 186 assert(info && info->id == i && info->page_name);
187
aed9a15b 188 const char *pg = info->page_name;
955394ce 189 if (info->page_redirect != Http::scNone)
aed9a15b
AJ
190 pg = info->page_name +4;
191
192 if (strchr(pg, ':') == NULL) {
43000484 193 /** But only if they are not redirection URL. */
8ff2520a 194 ErrorPageFile errTmpl(pg, ERR_MAX);
02259ff8 195 error_text[i] = errTmpl.loadDefault() ? xstrdup(errTmpl.text()) : NULL;
62e76326 196 }
197 }
1d803566 198 }
5b52cb6c 199
0ae3294a
AJ
200 error_stylesheet.reset();
201
5b52cb6c 202 // look for and load stylesheet into global MemBuf for it.
9e008dda 203 if (Config.errorStylesheet) {
8ff2520a 204 ErrorPageFile tmpl("StylesSheet", ERR_MAX);
02259ff8 205 tmpl.loadFromFile(Config.errorStylesheet);
4391cd15 206 error_stylesheet.appendf("%s",tmpl.text());
5b52cb6c 207 }
02259ff8 208
cb4f4424 209#if USE_OPENSSL
02259ff8 210 Ssl::errorDetailInitialize();
c259af96 211#endif
1d803566 212}
213
c68e9c6b 214void
215errorClean(void)
216{
217 if (error_text) {
62e76326 218 int i;
219
95dc7ff4 220 for (i = ERR_NONE + 1; i < error_page_count; ++i)
62e76326 221 safe_free(error_text[i]);
222
223 safe_free(error_text);
c68e9c6b 224 }
62e76326 225
385acf91 226 while (!ErrorDynamicPages.empty()) {
38c22baf
FC
227 errorDynamicPageInfoDestroy(ErrorDynamicPages.back());
228 ErrorDynamicPages.pop_back();
229 }
62e76326 230
c68e9c6b 231 error_page_count = 0;
02259ff8 232
cb4f4424 233#if USE_OPENSSL
02259ff8 234 Ssl::errorDetailClean();
c259af96 235#endif
c68e9c6b 236}
237
63be0a78 238/// \ingroup ErrorPageInternal
1d803566 239static const char *
240errorFindHardText(err_type type)
241{
242 int i;
62e76326 243
95dc7ff4 244 for (i = 0; i < error_hard_text_count; ++i)
62e76326 245 if (error_hard_text[i].type == type)
246 return error_hard_text[i].text;
247
1d803566 248 return NULL;
249}
250
8ff2520a 251TemplateFile::TemplateFile(const char *name, const err_type code): silent(false), wasLoaded(false), templateName(name), templateCode(code)
1d803566 252{
02259ff8
CT
253 assert(name);
254}
255
256bool
257TemplateFile::loadDefault()
258{
259 if (loaded()) // already loaded?
260 return true;
43000484
AJ
261
262 /** test error_directory configured location */
02259ff8
CT
263 if (Config.errorDirectory) {
264 char path[MAXPATHLEN];
265 snprintf(path, sizeof(path), "%s/%s", Config.errorDirectory, templateName.termedBuf());
266 loadFromFile(path);
267 }
43000484
AJ
268
269#if USE_ERR_LOCALES
270 /** test error_default_language location */
02259ff8
CT
271 if (!loaded() && Config.errorDefaultLanguage) {
272 if (!tryLoadTemplate(Config.errorDefaultLanguage)) {
8ff2520a 273 debugs(1, (templateCode < TCP_RESET ? DBG_CRITICAL : 3), "Unable to load default error language files. Reset to backups.");
43000484
AJ
274 }
275 }
276#endif
62e76326 277
43000484 278 /* test default location if failed (templates == English translation base templates) */
02259ff8
CT
279 if (!loaded()) {
280 tryLoadTemplate("templates");
5bf33a09 281 }
62e76326 282
1d803566 283 /* giving up if failed */
b073fc4b 284 if (!loaded()) {
8ff2520a 285 debugs(1, (templateCode < TCP_RESET ? DBG_CRITICAL : 3), "WARNING: failed to find or read error text file " << templateName);
b073fc4b
AJ
286 parse("Internal Error: Missing Template ", 33, '\0');
287 parse(templateName.termedBuf(), templateName.size(), '\0');
288 }
62e76326 289
02259ff8 290 return true;
1d803566 291}
292
02259ff8
CT
293bool
294TemplateFile::tryLoadTemplate(const char *lang)
1d803566 295{
02259ff8
CT
296 assert(lang);
297
9b312a19 298 char path[MAXPATHLEN];
02259ff8
CT
299 /* TODO: prep the directory path string to prevent snprintf ... */
300 snprintf(path, sizeof(path), "%s/%s/%s",
301 DEFAULT_SQUID_ERROR_DIR, lang, templateName.termedBuf());
302 path[MAXPATHLEN-1] = '\0';
303
304 if (loadFromFile(path))
305 return true;
306
307#if HAVE_GLOB
308 if ( strlen(lang) == 2) {
309 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
310 /* use first result. */
311 debugs(4,2, HERE << "wildcard fallback errors not coded yet.");
312 }
313#endif
314
315 return false;
316}
317
318bool
319TemplateFile::loadFromFile(const char *path)
320{
321 int fd;
e8f6c5c7 322 char buf[4096];
e8f6c5c7 323 ssize_t len;
1d803566 324
02259ff8
CT
325 if (loaded()) // already loaded?
326 return true;
45308e4d 327
c4aefe96 328 fd = file_open(path, O_RDONLY | O_TEXT);
e8f6c5c7 329
330 if (fd < 0) {
43000484 331 /* with dynamic locale negotiation we may see some failures before a success. */
b69e9ffa
AJ
332 if (!silent && templateCode < TCP_RESET) {
333 int xerrno = errno;
ec1c5408 334 debugs(4, DBG_CRITICAL, "ERROR: loading file '" << path << "': " << xstrerr(xerrno));
b69e9ffa 335 }
02259ff8
CT
336 wasLoaded = false;
337 return wasLoaded;
1d803566 338 }
62e76326 339
9e008dda 340 while ((len = FD_READ_METHOD(fd, buf, sizeof(buf))) > 0) {
02259ff8 341 if (!parse(buf, len, false)) {
ec1c5408 342 debugs(4, DBG_CRITICAL, "ERROR: parsing error in template file: " << path);
02259ff8
CT
343 wasLoaded = false;
344 return wasLoaded;
345 }
e8f6c5c7 346 }
02259ff8 347 parse(buf, 0, true);
62e76326 348
e8f6c5c7 349 if (len < 0) {
b69e9ffa
AJ
350 int xerrno = errno;
351 debugs(4, DBG_CRITICAL, MYNAME << "ERROR: failed to fully read: '" << path << "': " << xstrerr(xerrno));
1e74c110 352 }
62e76326 353
1d803566 354 file_close(fd);
e8f6c5c7 355
02259ff8
CT
356 wasLoaded = true;
357 return wasLoaded;
358}
359
360bool strHdrAcptLangGetItem(const String &hdr, char *lang, int langLen, size_t &pos)
361{
dc49061a 362 while (pos < hdr.size()) {
02259ff8 363
a32e7644
AJ
364 /* skip any initial whitespace. */
365 while (pos < hdr.size() && xisspace(hdr[pos]))
366 ++pos;
62e76326 367
02259ff8
CT
368 /*
369 * Header value format:
370 * - sequence of whitespace delimited tags
371 * - each tag may suffix with ';'.* which we can ignore.
372 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
373 * with preference given to an exact match.
374 */
375 bool invalid_byte = false;
3d4c0e37 376 char *dt = lang;
02259ff8
CT
377 while (pos < hdr.size() && hdr[pos] != ';' && hdr[pos] != ',' && !xisspace(hdr[pos]) && dt < (lang + (langLen -1)) ) {
378 if (!invalid_byte) {
379#if USE_HTTP_VIOLATIONS
380 // if accepting violations we may as well accept some broken browsers
381 // which may send us the right code, wrong ISO formatting.
382 if (hdr[pos] == '_')
383 *dt = '-';
384 else
385#endif
386 *dt = xtolower(hdr[pos]);
387 // valid codes only contain A-Z, hyphen (-) and *
388 if (*dt != '-' && *dt != '*' && (*dt < 'a' || *dt > 'z') )
389 invalid_byte = true;
390 else
95dc7ff4 391 ++dt; // move to next destination byte.
02259ff8 392 }
95dc7ff4 393 ++pos;
02259ff8 394 }
a38ec4b1 395 *dt = '\0'; // nul-terminated the filename content string before system use.
62e76326 396
a32e7644
AJ
397 // if we terminated the tag on garbage or ';' we need to skip to the next ',' or end of header.
398 while (pos < hdr.size() && hdr[pos] != ',')
399 ++pos;
400
401 if (pos < hdr.size() && hdr[pos] == ',')
402 ++pos;
403
3d4c0e37 404 debugs(4, 9, "STATE: lang=" << lang << ", pos=" << pos << ", buf='" << ((pos < hdr.size()) ? hdr.substr(pos,hdr.size()) : "") << "'");
02259ff8
CT
405
406 /* if we found anything we might use, try it. */
407 if (*lang != '\0' && !invalid_byte)
408 return true;
409 }
410 return false;
411}
412
413bool
b248c2a3 414TemplateFile::loadFor(const HttpRequest *request)
02259ff8
CT
415{
416 String hdr;
417
cf0a0bdf 418#if USE_ERR_LOCALES
02259ff8
CT
419 if (loaded()) // already loaded?
420 return true;
421
4c7c97f3 422 if (!request || !request->header.getList(Http::HdrType::ACCEPT_LANGUAGE, &hdr))
02259ff8
CT
423 return false;
424
425 char lang[256];
426 size_t pos = 0; // current parsing position in header string
427
428 debugs(4, 6, HERE << "Testing Header: '" << hdr << "'");
429
430 while ( strHdrAcptLangGetItem(hdr, lang, 256, pos) ) {
431
432 /* wildcard uses the configured default language */
433 if (lang[0] == '*' && lang[1] == '\0') {
434 debugs(4, 6, HERE << "Found language '" << lang << "'. Using configured default.");
435 return false;
436 }
437
438 debugs(4, 6, HERE << "Found language '" << lang << "', testing for available template");
439
440 if (tryLoadTemplate(lang)) {
441 /* store the language we found for the Content-Language reply header */
442 errLanguage = lang;
443 break;
444 } else if (Config.errorLogMissingLanguages) {
445 debugs(4, DBG_IMPORTANT, "WARNING: Error Pages Missing Language: " << lang);
446 }
447 }
cf0a0bdf 448#endif
02259ff8
CT
449
450 return loaded();
6eb42cae 451}
452
63be0a78 453/// \ingroup ErrorPageInternal
02922e76 454static ErrorDynamicPageInfo *
455errorDynamicPageInfoCreate(int id, const char *page_name)
456{
4ff59fc7 457 ErrorDynamicPageInfo *info = new ErrorDynamicPageInfo;
02922e76 458 info->id = id;
459 info->page_name = xstrdup(page_name);
955394ce 460 info->page_redirect = static_cast<Http::StatusCode>(atoi(page_name));
aed9a15b
AJ
461
462 /* WARNING on redirection status:
463 * 2xx are permitted, but not documented officially.
464 * - might be useful for serving static files (PAC etc) in special cases
465 * 3xx require a URL suitable for Location: header.
466 * - the current design does not allow for a Location: URI as well as a local file template
467 * although this possibility is explicitly permitted in the specs.
468 * 4xx-5xx require a local file template.
469 * - sending Location: on these codes with no body is invalid by the specs.
470 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
471 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
472 */
955394ce 473 if (info->page_redirect == Http::scNone)
aed9a15b
AJ
474 ; // special case okay.
475 else if (info->page_redirect < 200 || info->page_redirect > 599) {
476 // out of range
477 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " is not valid on '" << page_name << "'");
478 self_destruct();
479 } else if ( /* >= 200 && */ info->page_redirect < 300 && strchr(&(page_name[4]), ':')) {
480 // 2xx require a local template file
0ff52055 481 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " requires a template on '" << page_name << "'");
aed9a15b 482 self_destruct();
0ff52055 483 } else if (info->page_redirect >= 300 && info->page_redirect <= 399 && !strchr(&(page_name[4]), ':')) {
aed9a15b 484 // 3xx require an absolute URL
0ff52055 485 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " requires a URL on '" << page_name << "'");
aed9a15b
AJ
486 self_destruct();
487 } else if (info->page_redirect >= 400 /* && <= 599 */ && strchr(&(page_name[4]), ':')) {
488 // 4xx/5xx require a local template file
0ff52055 489 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " requires a template on '" << page_name << "'");
aed9a15b
AJ
490 self_destruct();
491 }
492 // else okay.
493
02922e76 494 return info;
495}
496
63be0a78 497/// \ingroup ErrorPageInternal
02922e76 498static void
1afe05c5 499errorDynamicPageInfoDestroy(ErrorDynamicPageInfo * info)
02922e76 500{
501 assert(info);
c70281f8 502 safe_free(info->page_name);
4ff59fc7 503 delete info;
02922e76 504}
505
63be0a78 506/// \ingroup ErrorPageInternal
76cdc28d 507static int
508errorPageId(const char *page_name)
509{
95dc7ff4 510 for (int i = 0; i < ERR_MAX; ++i) {
62e76326 511 if (strcmp(err_type_str[i], page_name) == 0)
512 return i;
76cdc28d 513 }
62e76326 514
95dc7ff4 515 for (size_t j = 0; j < ErrorDynamicPages.size(); ++j) {
4c9eadc2 516 if (strcmp(ErrorDynamicPages[j]->page_name, page_name) == 0)
190154cf 517 return j + ERR_MAX;
76cdc28d 518 }
62e76326 519
76cdc28d 520 return ERR_NONE;
521}
522
e6ccf245 523err_type
02922e76 524errorReservePageId(const char *page_name)
525{
76cdc28d 526 ErrorDynamicPageInfo *info;
527 int id = errorPageId(page_name);
62e76326 528
76cdc28d 529 if (id == ERR_NONE) {
62e76326 530 info = errorDynamicPageInfoCreate(ERR_MAX + ErrorDynamicPages.size(), page_name);
531 ErrorDynamicPages.push_back(info);
532 id = info->id;
76cdc28d 533 }
62e76326 534
e6ccf245 535 return (err_type)id;
02922e76 536}
537
63be0a78 538/// \ingroup ErrorPageInternal
64b66b76 539const char *
c68e9c6b 540errorPageName(int pageId)
53ad48e6 541{
f53969cc 542 if (pageId >= ERR_NONE && pageId < ERR_MAX) /* common case */
62e76326 543 return err_type_str[pageId];
544
4ff59fc7 545 if (pageId >= ERR_MAX && pageId - ERR_MAX < (ssize_t)ErrorDynamicPages.size())
4c9eadc2 546 return ErrorDynamicPages[pageId - ERR_MAX]->page_name;
62e76326 547
f53969cc 548 return "ERR_UNKNOWN"; /* should not happen */
53ad48e6 549}
550
a23223bf 551ErrorState *
4c7c97f3 552ErrorState::NewForwarding(err_type type, HttpRequestPointer &request)
a23223bf 553{
4c7c97f3 554 const Http::StatusCode status = (request && request->flags.needValidation) ?
e2849af8 555 Http::scGatewayTimeout : Http::scServiceUnavailable;
4c7c97f3 556 return new ErrorState(type, status, request.getRaw());
a23223bf
CT
557}
558
955394ce 559ErrorState::ErrorState(err_type t, Http::StatusCode status, HttpRequest * req) :
f53969cc
SM
560 type(t),
561 page_id(t),
f53969cc 562 httpStatus(status),
fc94fd66 563 callback(nullptr)
fe40a877 564{
4c9eadc2
FC
565 if (page_id >= ERR_MAX && ErrorDynamicPages[page_id - ERR_MAX]->page_redirect != Http::scNone)
566 httpStatus = ErrorDynamicPages[page_id - ERR_MAX]->page_redirect;
913524f0 567
fc94fd66 568 if (req) {
b248c2a3 569 request = req;
913524f0 570 src_addr = req->client_addr;
2cc81f1f 571 }
fe40a877 572}
573
fe40a877 574void
575errorAppendEntry(StoreEntry * entry, ErrorState * err)
576{
e4a67a80 577 assert(entry->mem_obj != NULL);
528b2c61 578 assert (entry->isEmpty());
0b86805b 579 debugs(4, 4, "Creating an error page for entry " << entry <<
580 " with errorstate " << err <<
581 " page id " << err->page_id);
62e76326 582
1ea80e98 583 if (entry->store_status != STORE_PENDING) {
0b86805b 584 debugs(4, 2, "Skipping error page due to store_status: " << entry->store_status);
62e76326 585 /*
586 * If the entry is not STORE_PENDING, then no clients
587 * care about it, and we don't need to generate an
588 * error message
589 */
590 assert(EBIT_TEST(entry->flags, ENTRY_ABORTED));
6ea35247 591 assert(entry->mem_obj->nclients == 0);
913524f0 592 delete err;
62e76326 593 return;
1ea80e98 594 }
62e76326 595
76cdc28d 596 if (err->page_id == TCP_RESET) {
62e76326 597 if (err->request) {
bf8fe701 598 debugs(4, 2, "RSTing this reply");
e857372a 599 err->request->flags.resetTcp = true;
62e76326 600 }
98264874 601 }
62e76326 602
eacfca83 603 entry->storeErrorResponse(err->BuildHttpReply());
913524f0 604 delete err;
fe40a877 605}
606
fe40a877 607void
e0d28505 608errorSend(const Comm::ConnectionPointer &conn, ErrorState * err)
fe40a877 609{
4c7c97f3 610 debugs(4, 3, conn << ", err=" << err);
e0d28505 611 assert(Comm::IsConnOpen(conn));
62e76326 612
4c7c97f3 613 HttpReplyPointer rep(err->BuildHttpReply());
62e76326 614
ddbe383d 615 MemBuf *mb = rep->pack();
ec41b64c
AJ
616 AsyncCall::Pointer call = commCbCall(78, 5, "errorSendComplete",
617 CommIoCbPtrFun(&errorSendComplete, err));
b0388924 618 Comm::Write(conn, mb, call);
ddbe383d 619 delete mb;
fe40a877 620}
621
63be0a78 622/**
623 \ingroup ErrorPageAPI
fe40a877 624 *
63be0a78 625 * Called by commHandleWrite() after data has been written
626 * to the client socket.
fe40a877 627 *
63be0a78 628 \note If there is a callback, the callback is responsible for
b3802bdc 629 * closing the FD, otherwise we do it ourselves.
fe40a877 630 */
631static void
ced8def3 632errorSendComplete(const Comm::ConnectionPointer &conn, char *, size_t size, Comm::Flag errflag, int, void *data)
fe40a877 633{
e6ccf245 634 ErrorState *err = static_cast<ErrorState *>(data);
e0d28505 635 debugs(4, 3, HERE << conn << ", size=" << size);
62e76326 636
c8407295 637 if (errflag != Comm::ERR_CLOSING) {
62e76326 638 if (err->callback) {
bf8fe701 639 debugs(4, 3, "errorSendComplete: callback");
e0d28505 640 err->callback(conn->fd, err->callback_data, size);
62e76326 641 } else {
bf8fe701 642 debugs(4, 3, "errorSendComplete: comm_close");
80463bb4 643 conn->close();
62e76326 644 }
fe40a877 645 }
62e76326 646
913524f0 647 delete err;
fe40a877 648}
649
913524f0 650ErrorState::~ErrorState()
6eb42cae 651{
913524f0
AJ
652 safe_free(redirect_url);
653 safe_free(url);
654 safe_free(request_hdrs);
655 wordlistDestroy(&ftp.server_msg);
656 safe_free(ftp.request);
657 safe_free(ftp.reply);
913524f0 658 safe_free(err_msg);
5bf33a09 659#if USE_ERR_LOCALES
913524f0 660 if (err_language != Config.errorDefaultLanguage)
5bf33a09 661#endif
913524f0 662 safe_free(err_language);
cb4f4424 663#if USE_OPENSSL
913524f0 664 delete detail;
4d16918e 665#endif
1e74c110 666}
8213067d 667
c70281f8
AJ
668int
669ErrorState::Dump(MemBuf * mb)
b5fb34f1 670{
032785bf 671 MemBuf str;
cc192b50 672 char ntoabuf[MAX_IPSTRLEN];
673
2fe7eff9 674 str.reset();
b5fb34f1 675 /* email subject line */
4391cd15
AJ
676 str.appendf("CacheErrorInfo - %s", errorPageName(type));
677 mb->appendf("?subject=%s", rfc1738_escape_part(str.buf));
2fe7eff9 678 str.reset();
b5fb34f1 679 /* email body */
4391cd15 680 str.appendf("CacheHost: %s\r\n", getMyHostname());
b5fb34f1 681 /* - Err Msgs */
4391cd15 682 str.appendf("ErrPage: %s\r\n", errorPageName(type));
62e76326 683
c70281f8 684 if (xerrno) {
4391cd15 685 str.appendf("Err: (%d) %s\r\n", xerrno, strerror(xerrno));
b5fb34f1 686 } else {
4391cd15 687 str.append("Err: [none]\r\n", 13);
b5fb34f1 688 }
2f1431ea 689#if USE_AUTH
98340a7b 690 if (auth_user_request.getRaw() && auth_user_request->denyMessage())
4391cd15 691 str.appendf("Auth ErrMsg: %s\r\n", auth_user_request->denyMessage());
2f1431ea 692#endif
3ff65596 693 if (dnsError.size() > 0)
4391cd15 694 str.appendf("DNS ErrMsg: %s\r\n", dnsError.termedBuf());
62e76326 695
b5fb34f1 696 /* - TimeStamp */
4391cd15 697 str.appendf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime));
62e76326 698
b5fb34f1 699 /* - IP stuff */
4391cd15 700 str.appendf("ClientIP: %s\r\n", src_addr.toStr(ntoabuf,MAX_IPSTRLEN));
62e76326 701
b3802bdc 702 if (request && request->hier.host[0] != '\0') {
4391cd15 703 str.appendf("ServerIP: %s\r\n", request->hier.host);
b5fb34f1 704 }
62e76326 705
4391cd15 706 str.append("\r\n", 2);
b5fb34f1 707 /* - HTTP stuff */
4391cd15 708 str.append("HTTP Request:\r\n", 15);
51b5dcf5
AJ
709 if (request) {
710 str.appendf(SQUIDSBUFPH " " SQUIDSBUFPH " %s/%d.%d\n",
4391cd15 711 SQUIDSBUFPRINT(request->method.image()),
51b5dcf5 712 SQUIDSBUFPRINT(request->url.path()),
4391cd15
AJ
713 AnyP::ProtocolType_str[request->http_ver.protocol],
714 request->http_ver.major, request->http_ver.minor);
10201568 715 request->header.packInto(&str);
b5fb34f1 716 }
62e76326 717
4391cd15 718 str.append("\r\n", 2);
b5fb34f1 719 /* - FTP stuff */
62e76326 720
c70281f8 721 if (ftp.request) {
4391cd15
AJ
722 str.appendf("FTP Request: %s\r\n", ftp.request);
723 str.appendf("FTP Reply: %s\r\n", (ftp.reply? ftp.reply:"[none]"));
724 str.append("FTP Msg: ", 9);
c70281f8 725 wordlistCat(ftp.server_msg, &str);
4391cd15 726 str.append("\r\n", 2);
b5fb34f1 727 }
62e76326 728
4391cd15
AJ
729 str.append("\r\n", 2);
730 mb->appendf("&body=%s", rfc1738_escape_part(str.buf));
2fe7eff9 731 str.clean();
b5fb34f1 732 return 0;
733}
734
63be0a78 735/// \ingroup ErrorPageInternal
2658f489 736#define CVT_BUF_SZ 512
fe40a877 737
c70281f8 738const char *
4d16918e 739ErrorState::Convert(char token, bool building_deny_info_url, bool allowRecursion)
8213067d 740{
032785bf 741 static MemBuf mb;
f53969cc 742 const char *p = NULL; /* takes priority over mb if set */
10270faa 743 int do_quote = 1;
4ad8d23d 744 int no_urlescape = 0; /* if true then item is NOT to be further URL-encoded */
cc192b50 745 char ntoabuf[MAX_IPSTRLEN];
eeb423fb 746
2fe7eff9 747 mb.reset();
62e76326 748
9b312a19 749 switch (token) {
62e76326 750
523f44f5 751 case 'a':
2f1431ea 752#if USE_AUTH
4c7c97f3 753 if (request && request->auth_user_request)
c70281f8 754 p = request->auth_user_request->username();
523f44f5 755 if (!p)
2f1431ea 756#endif
523f44f5 757 p = "-";
523f44f5 758 break;
88d1e459 759
ea35939b
A
760 case 'A':
761 // TODO: When/if we get ALE here, pass it as well
762 if (const auto addr = FindListeningPortAddress(request.getRaw(), nullptr))
763 mb.appendf("%s", addr->toStr(ntoabuf, MAX_IPSTRLEN));
764 else
765 p = "-";
766 break;
767
88d1e459 768 case 'b':
4391cd15 769 mb.appendf("%u", getMyPort());
88d1e459
AJ
770 break;
771
8f872bb6 772 case 'B':
1e98e28b 773 if (building_deny_info_url) break;
851feda6 774 if (request) {
4c7c97f3 775 const SBuf &tmp = Ftp::UrlWith2f(request.getRaw());
851feda6
AJ
776 mb.append(tmp.rawContent(), tmp.length());
777 } else
778 p = "[no URL]";
62e76326 779 break;
780
42b51993 781 case 'c':
1e98e28b 782 if (building_deny_info_url) break;
c70281f8 783 p = errorPageName(type);
62e76326 784 break;
785
4d16918e
CT
786 case 'D':
787 if (!allowRecursion)
788 p = "%D"; // if recursion is not allowed, do not convert
cb4f4424 789#if USE_OPENSSL
4d16918e
CT
790 // currently only SSL error details implemented
791 else if (detail) {
4c7c97f3 792 detail->useRequest(request.getRaw());
4d16918e 793 const String &errDetail = detail->toString();
b38b26cb 794 if (errDetail.size() > 0) {
8211c314
CT
795 MemBuf *detail_mb = ConvertText(errDetail.termedBuf(), false);
796 mb.append(detail_mb->content(), detail_mb->contentSize());
797 delete detail_mb;
798 do_quote = 0;
799 }
800 }
4d16918e 801#endif
8211c314 802 if (!mb.contentSize())
4391cd15 803 mb.append("[No Error Detail]", 17);
4d16918e
CT
804 break;
805
042461c3 806 case 'e':
4391cd15 807 mb.appendf("%d", xerrno);
62e76326 808 break;
809
042461c3 810 case 'E':
c70281f8 811 if (xerrno)
4391cd15 812 mb.appendf("(%d) %s", xerrno, strerror(xerrno));
62e76326 813 else
4391cd15 814 mb.append("[No Error]", 10);
62e76326 815 break;
816
fe40a877 817 case 'f':
1e98e28b 818 if (building_deny_info_url) break;
62e76326 819 /* FTP REQUEST LINE */
c70281f8
AJ
820 if (ftp.request)
821 p = ftp.request;
62e76326 822 else
823 p = "nothing";
62e76326 824 break;
825
fe40a877 826 case 'F':
1e98e28b 827 if (building_deny_info_url) break;
62e76326 828 /* FTP REPLY LINE */
c6b684dd 829 if (ftp.reply)
c70281f8 830 p = ftp.reply;
62e76326 831 else
832 p = "nothing";
62e76326 833 break;
834
7131112f 835 case 'g':
1e98e28b 836 if (building_deny_info_url) break;
a91d3505
AJ
837 /* FTP SERVER RESPONSE */
838 if (ftp.listing) {
0477a072
AJ
839 mb.append(ftp.listing->content(), ftp.listing->contentSize());
840 do_quote = 0;
a91d3505
AJ
841 } else if (ftp.server_msg) {
842 wordlistCat(ftp.server_msg, &mb);
0477a072 843 }
62e76326 844 break;
845
03d7b07f 846 case 'h':
4391cd15 847 mb.appendf("%s", getMyHostname());
62e76326 848 break;
849
fe40a877 850 case 'H':
c70281f8 851 if (request) {
b3802bdc 852 if (request->hier.host[0] != '\0') // if non-empty string.
c70281f8 853 p = request->hier.host;
beed27a2 854 else
5c51bffb 855 p = request->url.host();
1e98e28b 856 } else if (!building_deny_info_url)
beed27a2 857 p = "[unknown host]";
62e76326 858 break;
859
f787fb1e 860 case 'i':
4391cd15 861 mb.appendf("%s", src_addr.toStr(ntoabuf,MAX_IPSTRLEN));
62e76326 862 break;
863
f787fb1e 864 case 'I':
4c7c97f3 865 if (request && request->hier.tcpServer)
4dd643d5 866 p = request->hier.tcpServer->remote.toStr(ntoabuf,MAX_IPSTRLEN);
1e98e28b 867 else if (!building_deny_info_url)
62e76326 868 p = "[unknown]";
62e76326 869 break;
870
5b52cb6c 871 case 'l':
1e98e28b 872 if (building_deny_info_url) break;
0ae3294a 873 mb.append(error_stylesheet.content(), error_stylesheet.contentSize());
5b52cb6c
AJ
874 do_quote = 0;
875 break;
876
fe40a877 877 case 'L':
1e98e28b 878 if (building_deny_info_url) break;
62e76326 879 if (Config.errHtmlText) {
4391cd15 880 mb.appendf("%s", Config.errHtmlText);
62e76326 881 do_quote = 0;
1e98e28b 882 } else
62e76326 883 p = "[not available]";
62e76326 884 break;
885
066ed5c1 886 case 'm':
1e98e28b 887 if (building_deny_info_url) break;
2f1431ea 888#if USE_AUTH
52ba2948
CT
889 if (auth_user_request.getRaw())
890 p = auth_user_request->denyMessage("[not available]");
891 else
892 p = "[not available]";
2f1431ea
AJ
893#else
894 p = "-";
895#endif
62e76326 896 break;
897
fe40a877 898 case 'M':
7f06a3d8 899 if (request) {
e2849af8
A
900 const SBuf &m = request->method.image();
901 mb.append(m.rawContent(), m.length());
7f06a3d8
AJ
902 } else if (!building_deny_info_url)
903 p = "[unknown method]";
62e76326 904 break;
905
05dbf66c 906 case 'O':
f3bd9c5e
AJ
907 if (!building_deny_info_url)
908 do_quote = 0;
4a972fa2 909 case 'o':
8c93a598 910 p = request ? request->extacl_message.termedBuf() : external_acl_message;
1e98e28b 911 if (!p && !building_deny_info_url)
d73b593b 912 p = "[not available]";
4a972fa2 913 break;
914
fe40a877 915 case 'p':
c70281f8 916 if (request) {
5c51bffb 917 mb.appendf("%u", request->url.port());
1e98e28b 918 } else if (!building_deny_info_url) {
62e76326 919 p = "[unknown port]";
920 }
62e76326 921 break;
922
fe40a877 923 case 'P':
e7aae06b 924 if (request) {
d31d59d8
AJ
925 const SBuf &m = request->url.getScheme().image();
926 mb.append(m.rawContent(), m.length());
1e98e28b 927 } else if (!building_deny_info_url) {
e7aae06b
A
928 p = "[unknown protocol]";
929 }
62e76326 930 break;
931
b5af8569 932 case 'R':
1e98e28b 933 if (building_deny_info_url) {
1b091aec 934 if (request != NULL) {
b2b6c9f4
AJ
935 const SBuf &tmp = request->url.path();
936 mb.append(tmp.rawContent(), tmp.length());
1b091aec
CT
937 no_urlescape = 1;
938 } else
939 p = "[no request]";
15b02e9a
AJ
940 break;
941 }
4c7c97f3 942 if (request) {
51b5dcf5 943 mb.appendf(SQUIDSBUFPH " " SQUIDSBUFPH " %s/%d.%d\n",
4391cd15 944 SQUIDSBUFPRINT(request->method.image()),
51b5dcf5 945 SQUIDSBUFPRINT(request->url.path()),
4391cd15
AJ
946 AnyP::ProtocolType_str[request->http_ver.protocol],
947 request->http_ver.major, request->http_ver.minor);
10201568 948 request->header.packInto(&mb, true); //hide authorization data
c70281f8
AJ
949 } else if (request_hdrs) {
950 p = request_hdrs;
62e76326 951 } else {
952 p = "[no request]";
953 }
62e76326 954 break;
955
1d803566 956 case 's':
15b02e9a 957 /* for backward compat we make %s show the full URL. Drop this in some future release. */
1e98e28b 958 if (building_deny_info_url) {
851feda6
AJ
959 if (request) {
960 const SBuf &tmp = request->effectiveRequestUri();
961 mb.append(tmp.rawContent(), tmp.length());
962 } else
963 p = url;
fa84c01d 964 debugs(0, DBG_CRITICAL, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
05320519 965 } else
15b02e9a 966 p = visible_appname_string;
62e76326 967 break;
968
1d803566 969 case 'S':
1e98e28b 970 if (building_deny_info_url) {
4ad8d23d 971 p = visible_appname_string;
e7aae06b
A
972 break;
973 }
62e76326 974 /* signature may contain %-escapes, recursion */
c70281f8
AJ
975 if (page_id != ERR_SQUID_SIGNATURE) {
976 const int saved_id = page_id;
977 page_id = ERR_SQUID_SIGNATURE;
978 MemBuf *sign_mb = BuildContent();
4391cd15 979 mb.append(sign_mb->content(), sign_mb->contentSize());
2fe7eff9 980 sign_mb->clean();
032785bf 981 delete sign_mb;
c70281f8 982 page_id = saved_id;
62e76326 983 do_quote = 0;
984 } else {
985 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
986 p = "[%S]";
987 }
62e76326 988 break;
989
fe40a877 990 case 't':
4391cd15 991 mb.appendf("%s", Time::FormatHttpd(squid_curtime));
62e76326 992 break;
993
f8291f8f 994 case 'T':
4391cd15 995 mb.appendf("%s", mkrfc1123(squid_curtime));
62e76326 996 break;
997
fe40a877 998 case 'U':
851feda6 999 /* Using the fake-https version of absolute-URI so error pages see https:// */
b3802bdc 1000 /* even when the url-path cannot be shown as more than '*' */
e7aae06b 1001 if (request)
4c7c97f3 1002 p = urlCanonicalFakeHttps(request.getRaw());
e7aae06b
A
1003 else if (url)
1004 p = url;
1e98e28b 1005 else if (!building_deny_info_url)
e7aae06b 1006 p = "[no URL]";
62e76326 1007 break;
1008
76cdc28d 1009 case 'u':
851feda6
AJ
1010 if (request) {
1011 const SBuf &tmp = request->effectiveRequestUri();
1012 mb.append(tmp.rawContent(), tmp.length());
1013 } else if (url)
1e98e28b
AJ
1014 p = url;
1015 else if (!building_deny_info_url)
1016 p = "[no URL]";
62e76326 1017 break;
1018
fe40a877 1019 case 'w':
62e76326 1020 if (Config.adminEmail)
4391cd15 1021 mb.appendf("%s", Config.adminEmail);
1e98e28b 1022 else if (!building_deny_info_url)
62e76326 1023 p = "[unknown]";
62e76326 1024 break;
1025
b5fb34f1 1026 case 'W':
1e98e28b 1027 if (building_deny_info_url) break;
62e76326 1028 if (Config.adminEmail && Config.onoff.emailErrData)
c70281f8 1029 Dump(&mb);
4ad8d23d 1030 no_urlescape = 1;
62e76326 1031 break;
1032
e4a8468d 1033 case 'x':
cb4f4424 1034#if USE_OPENSSL
e4a8468d 1035 if (detail)
4391cd15 1036 mb.appendf("%s", detail->errorName());
0ab68838
CT
1037 else
1038#endif
1039 if (!building_deny_info_url)
1040 p = "[Unknown Error Code]";
e4a8468d
CT
1041 break;
1042
fe40a877 1043 case 'z':
1e98e28b 1044 if (building_deny_info_url) break;
3ff65596
AR
1045 if (dnsError.size() > 0)
1046 p = dnsError.termedBuf();
0477a072
AJ
1047 else if (ftp.cwd_msg)
1048 p = ftp.cwd_msg;
62e76326 1049 else
1050 p = "[unknown]";
62e76326 1051 break;
1052
43ae1d95 1053 case 'Z':
1e98e28b 1054 if (building_deny_info_url) break;
c70281f8
AJ
1055 if (err_msg)
1056 p = err_msg;
43ae1d95 1057 else
1058 p = "[unknown]";
43ae1d95 1059 break;
1060
e347f8e5 1061 case '%':
62e76326 1062 p = "%";
62e76326 1063 break;
1064
9b312a19 1065 default:
4391cd15 1066 mb.appendf("%%%c", token);
cbba2ba2 1067 do_quote = 0;
62e76326 1068 break;
9b312a19 1069 }
62e76326 1070
137ee196 1071 if (!p)
f53969cc 1072 p = mb.buf; /* do not use mb after this assignment! */
62e76326 1073
137ee196 1074 assert(p);
62e76326 1075
bf8fe701 1076 debugs(4, 3, "errorConvert: %%" << token << " --> '" << p << "'" );
62e76326 1077
10270faa 1078 if (do_quote)
62e76326 1079 p = html_quote(p);
1080
1e98e28b 1081 if (building_deny_info_url && !no_urlescape)
15b02e9a
AJ
1082 p = rfc1738_escape_part(p);
1083
9b312a19 1084 return p;
8213067d 1085}
e381a13d 1086
15b02e9a 1087void
ced8def3 1088ErrorState::DenyInfoLocation(const char *name, HttpRequest *, MemBuf &result)
15b02e9a
AJ
1089{
1090 char const *m = name;
1091 char const *p = m;
1092 char const *t;
1093
aed9a15b
AJ
1094 if (m[0] == '3')
1095 m += 4; // skip "3xx:"
1096
15b02e9a
AJ
1097 while ((p = strchr(m, '%'))) {
1098 result.append(m, p - m); /* copy */
4d16918e 1099 t = Convert(*++p, true, true); /* convert */
4391cd15 1100 result.appendf("%s", t); /* copy */
15b02e9a
AJ
1101 m = p + 1; /* advance */
1102 }
1103
1104 if (*m)
4391cd15 1105 result.appendf("%s", m); /* copy tail */
15b02e9a
AJ
1106
1107 assert((size_t)result.contentSize() == strlen(result.content()));
1108}
1109
cb69b4c7 1110HttpReply *
c70281f8 1111ErrorState::BuildHttpReply()
cb69b4c7 1112{
06a5ae20 1113 HttpReply *rep = new HttpReply;
c70281f8 1114 const char *name = errorPageName(page_id);
cb69b4c7 1115 /* no LMT for error pages; error pages expire immediately */
62e76326 1116
d4d63422 1117 if (name[0] == '3' || (name[0] != '2' && name[0] != '4' && name[0] != '5' && strchr(name, ':'))) {
62e76326 1118 /* Redirection */
f11c8e2f 1119 Http::StatusCode status = Http::scFound;
aed9a15b
AJ
1120 // Use configured 3xx reply status if set.
1121 if (name[0] == '3')
1122 status = httpStatus;
1123 else {
1124 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
4c7c97f3 1125 if (request && request->method != Http::METHOD_GET && request->method != Http::METHOD_HEAD && request->http_ver >= Http::ProtocolVersion(1,1))
955394ce 1126 status = Http::scTemporaryRedirect;
aed9a15b
AJ
1127 }
1128
ec80c740 1129 rep->setHeaders(status, NULL, "text/html;charset=utf-8", 0, 0, -1);
c44950c4 1130
c70281f8 1131 if (request) {
15b02e9a
AJ
1132 MemBuf redirect_location;
1133 redirect_location.init();
4c7c97f3 1134 DenyInfoLocation(name, request.getRaw(), redirect_location);
789217a2 1135 httpHeaderPutStrf(&rep->header, Http::HdrType::LOCATION, "%s", redirect_location.content() );
c44950c4 1136 }
1137
789217a2 1138 httpHeaderPutStrf(&rep->header, Http::HdrType::X_SQUID_ERROR, "%d %s", httpStatus, "Access Denied");
76cdc28d 1139 } else {
c70281f8 1140 MemBuf *content = BuildContent();
ec80c740 1141 rep->setHeaders(httpStatus, NULL, "text/html;charset=utf-8", content->contentSize(), 0, -1);
62e76326 1142 /*
1143 * include some information for downstream caches. Implicit
1144 * replaceable content. This isn't quite sufficient. xerrno is not
1145 * necessarily meaningful to another system, so we really should
1146 * expand it. Additionally, we should identify ourselves. Someone
1147 * might want to know. Someone _will_ want to know OTOH, the first
1148 * X-CACHE-MISS entry should tell us who.
1149 */
789217a2 1150 httpHeaderPutStrf(&rep->header, Http::HdrType::X_SQUID_ERROR, "%s %d", name, xerrno);
ccb24616 1151
5bf33a09
AJ
1152#if USE_ERR_LOCALES
1153 /*
1154 * If error page auto-negotiate is enabled in any way, send the Vary.
1155 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1156 * We have even better reasons though:
1157 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1158 */
9e008dda 1159 if (!Config.errorDirectory) {
5bf33a09 1160 /* We 'negotiated' this ONLY from the Accept-Language. */
789217a2
FC
1161 rep->header.delById(Http::HdrType::VARY);
1162 rep->header.putStr(Http::HdrType::VARY, "Accept-Language");
5bf33a09
AJ
1163 }
1164
1165 /* add the Content-Language header according to RFC section 14.12 */
9e008dda 1166 if (err_language) {
789217a2 1167 rep->header.putStr(Http::HdrType::CONTENT_LANGUAGE, err_language);
9e008dda 1168 } else
5bf33a09
AJ
1169#endif /* USE_ERROR_LOCALES */
1170 {
ccb24616 1171 /* default templates are in English */
5bf33a09 1172 /* language is known unless error_directory override used */
9e008dda 1173 if (!Config.errorDirectory)
789217a2 1174 rep->header.putStr(Http::HdrType::CONTENT_LANGUAGE, "en");
ccb24616
AJ
1175 }
1176
0521f8be 1177 rep->body.setMb(content);
032785bf 1178 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
76cdc28d 1179 }
62e76326 1180
7a957a93
AR
1181 // Make sure error codes get back to the client side for logging and
1182 // error tracking.
129fe2a1
CT
1183 if (request) {
1184 int edc = ERR_DETAIL_NONE; // error detail code
cb4f4424 1185#if USE_OPENSSL
129fe2a1
CT
1186 if (detail)
1187 edc = detail->errorNo();
1188 else
1189#endif
1190 if (detailCode)
1191 edc = detailCode;
1192 else
1193 edc = xerrno;
1194 request->detailError(type, edc);
1195 }
1196
cb69b4c7 1197 return rep;
1198}
1199
c70281f8
AJ
1200MemBuf *
1201ErrorState::BuildContent()
cb69b4c7 1202{
43000484 1203 const char *m = NULL;
43000484 1204
c70281f8 1205 assert(page_id > ERR_NONE && page_id < error_page_count);
43000484
AJ
1206
1207#if USE_ERR_LOCALES
8ff2520a 1208 ErrorPageFile *localeTmpl = NULL;
43000484
AJ
1209
1210 /** error_directory option in squid.conf overrides translations.
30b78ef1 1211 * Custom errors are always found either in error_directory or the templates directory.
43000484
AJ
1212 * Otherwise locate the Accept-Language header
1213 */
02259ff8
CT
1214 if (!Config.errorDirectory && page_id < ERR_MAX) {
1215 if (err_language && err_language != Config.errorDefaultLanguage)
1216 safe_free(err_language);
1217
8ff2520a 1218 localeTmpl = new ErrorPageFile(err_type_str[page_id], static_cast<err_type>(page_id));
4c7c97f3 1219 if (localeTmpl->loadFor(request.getRaw())) {
02259ff8
CT
1220 m = localeTmpl->text();
1221 assert(localeTmpl->language());
1222 err_language = xstrdup(localeTmpl->language());
43000484
AJ
1223 }
1224 }
1225#endif /* USE_ERR_LOCALES */
1226
1227 /** \par
1228 * If client-specific error templates are not enabled or available.
1229 * fall back to the old style squid.conf settings.
1230 */
9e008dda 1231 if (!m) {
43000484 1232 m = error_text[page_id];
5bf33a09 1233#if USE_ERR_LOCALES
9e008dda 1234 if (!Config.errorDirectory)
5bf33a09
AJ
1235 err_language = Config.errorDefaultLanguage;
1236#endif
58d4b38b 1237 debugs(4, 2, HERE << "No existing error page language negotiated for " << errorPageName(page_id) << ". Using default error file.");
43000484
AJ
1238 }
1239
6551ae9d 1240 MemBuf *result = ConvertText(m, true);
960cb599 1241#if USE_ERR_LOCALES
02259ff8
CT
1242 if (localeTmpl)
1243 delete localeTmpl;
960cb599 1244#endif
6551ae9d 1245 return result;
4d16918e
CT
1246}
1247
1248MemBuf *ErrorState::ConvertText(const char *text, bool allowRecursion)
1249{
1250 MemBuf *content = new MemBuf;
1251 const char *p;
1252 const char *m = text;
1d803566 1253 assert(m);
43000484 1254 content->init();
62e76326 1255
cb69b4c7 1256 while ((p = strchr(m, '%'))) {
f53969cc
SM
1257 content->append(m, p - m); /* copy */
1258 const char *t = Convert(*++p, false, allowRecursion); /* convert */
4391cd15 1259 content->appendf("%s", t); /* copy */
f53969cc 1260 m = p + 1; /* advance */
cb69b4c7 1261 }
62e76326 1262
1d803566 1263 if (*m)
4391cd15 1264 content->appendf("%s", m); /* copy tail */
62e76326 1265
857e4512
AJ
1266 content->terminate();
1267
032785bf 1268 assert((size_t)content->contentSize() == strlen(content->content()));
62e76326 1269
cb69b4c7 1270 return content;
1271}
f53969cc 1272