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