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