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