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