]> git.ipfire.org Git - thirdparty/squid.git/blame - src/errorpage.cc
Cleanup: replace USE_SSL wrapper macro with USE_OPENSSL
[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"
602d9612 39#include "fde.h"
a0bc086f 40#include "ftp.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
955394ce 571ErrorState::ErrorState(err_type t, Http::StatusCode status, HttpRequest * req) :
913524f0
AJ
572 type(t),
573 page_id(t),
574 err_language(NULL),
575 httpStatus(status),
576#if USE_AUTH
577 auth_user_request (NULL),
578#endif
579 request(NULL),
580 url(NULL),
581 xerrno(0),
582 port(0),
583 dnsError(),
584 ttl(0),
585 src_addr(),
586 redirect_url(NULL),
587 callback(NULL),
588 callback_data(NULL),
589 request_hdrs(NULL),
129fe2a1 590 err_msg(NULL),
cb4f4424 591#if USE_OPENSSL
129fe2a1 592 detail(NULL),
913524f0 593#endif
129fe2a1 594 detailCode(ERR_DETAIL_NONE)
fe40a877 595{
913524f0
AJ
596 memset(&ftp, 0, sizeof(ftp));
597
4c9eadc2
FC
598 if (page_id >= ERR_MAX && ErrorDynamicPages[page_id - ERR_MAX]->page_redirect != Http::scNone)
599 httpStatus = ErrorDynamicPages[page_id - ERR_MAX]->page_redirect;
913524f0
AJ
600
601 if (req != NULL) {
b248c2a3
AJ
602 request = req;
603 HTTPMSGLOCK(request);
913524f0 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
1bfe9ade 637 entry->lock("errorAppendEntry");
3900307b 638 entry->buffer();
c70281f8 639 entry->replaceHttpReply( err->BuildHttpReply() );
3900307b 640 entry->flush();
528b2c61 641 entry->complete();
d88e3c49 642 entry->negativeCache();
643 entry->releaseRequest();
1bfe9ade 644 entry->unlock("errorAppendEntry");
913524f0 645 delete err;
fe40a877 646}
647
fe40a877 648void
e0d28505 649errorSend(const Comm::ConnectionPointer &conn, ErrorState * err)
fe40a877 650{
cb69b4c7 651 HttpReply *rep;
e0d28505
AJ
652 debugs(4, 3, HERE << conn << ", err=" << err);
653 assert(Comm::IsConnOpen(conn));
62e76326 654
c70281f8 655 rep = err->BuildHttpReply();
62e76326 656
ddbe383d 657 MemBuf *mb = rep->pack();
ec41b64c
AJ
658 AsyncCall::Pointer call = commCbCall(78, 5, "errorSendComplete",
659 CommIoCbPtrFun(&errorSendComplete, err));
b0388924 660 Comm::Write(conn, mb, call);
ddbe383d 661 delete mb;
62e76326 662
06a5ae20 663 delete rep;
fe40a877 664}
665
63be0a78 666/**
667 \ingroup ErrorPageAPI
fe40a877 668 *
63be0a78 669 * Called by commHandleWrite() after data has been written
670 * to the client socket.
fe40a877 671 *
63be0a78 672 \note If there is a callback, the callback is responsible for
b3802bdc 673 * closing the FD, otherwise we do it ourselves.
fe40a877 674 */
675static void
e0d28505 676errorSendComplete(const Comm::ConnectionPointer &conn, char *bufnotused, size_t size, comm_err_t errflag, int xerrno, void *data)
fe40a877 677{
e6ccf245 678 ErrorState *err = static_cast<ErrorState *>(data);
e0d28505 679 debugs(4, 3, HERE << conn << ", size=" << size);
62e76326 680
fe40a877 681 if (errflag != COMM_ERR_CLOSING) {
62e76326 682 if (err->callback) {
bf8fe701 683 debugs(4, 3, "errorSendComplete: callback");
e0d28505 684 err->callback(conn->fd, err->callback_data, size);
62e76326 685 } else {
bf8fe701 686 debugs(4, 3, "errorSendComplete: comm_close");
80463bb4 687 conn->close();
62e76326 688 }
fe40a877 689 }
62e76326 690
913524f0 691 delete err;
fe40a877 692}
693
913524f0 694ErrorState::~ErrorState()
6eb42cae 695{
913524f0
AJ
696 HTTPMSGUNLOCK(request);
697 safe_free(redirect_url);
698 safe_free(url);
699 safe_free(request_hdrs);
700 wordlistDestroy(&ftp.server_msg);
701 safe_free(ftp.request);
702 safe_free(ftp.reply);
2f1431ea 703#if USE_AUTH
913524f0 704 auth_user_request = NULL;
2f1431ea 705#endif
913524f0 706 safe_free(err_msg);
5bf33a09 707#if USE_ERR_LOCALES
913524f0 708 if (err_language != Config.errorDefaultLanguage)
5bf33a09 709#endif
913524f0 710 safe_free(err_language);
cb4f4424 711#if USE_OPENSSL
913524f0 712 delete detail;
4d16918e 713#endif
1e74c110 714}
8213067d 715
c70281f8
AJ
716int
717ErrorState::Dump(MemBuf * mb)
b5fb34f1 718{
032785bf 719 MemBuf str;
cc192b50 720 char ntoabuf[MAX_IPSTRLEN];
721
2fe7eff9 722 str.reset();
b5fb34f1 723 /* email subject line */
c70281f8 724 str.Printf("CacheErrorInfo - %s", errorPageName(type));
2fe7eff9 725 mb->Printf("?subject=%s", rfc1738_escape_part(str.buf));
726 str.reset();
b5fb34f1 727 /* email body */
2fe7eff9 728 str.Printf("CacheHost: %s\r\n", getMyHostname());
b5fb34f1 729 /* - Err Msgs */
c70281f8 730 str.Printf("ErrPage: %s\r\n", errorPageName(type));
62e76326 731
c70281f8
AJ
732 if (xerrno) {
733 str.Printf("Err: (%d) %s\r\n", xerrno, strerror(xerrno));
b5fb34f1 734 } else {
2fe7eff9 735 str.Printf("Err: [none]\r\n");
b5fb34f1 736 }
2f1431ea 737#if USE_AUTH
c70281f8
AJ
738 if (auth_user_request->denyMessage())
739 str.Printf("Auth ErrMsg: %s\r\n", auth_user_request->denyMessage());
2f1431ea 740#endif
3ff65596
AR
741 if (dnsError.size() > 0)
742 str.Printf("DNS ErrMsg: %s\r\n", dnsError.termedBuf());
62e76326 743
b5fb34f1 744 /* - TimeStamp */
2fe7eff9 745 str.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime));
62e76326 746
b5fb34f1 747 /* - IP stuff */
4dd643d5 748 str.Printf("ClientIP: %s\r\n", src_addr.toStr(ntoabuf,MAX_IPSTRLEN));
62e76326 749
b3802bdc 750 if (request && request->hier.host[0] != '\0') {
c70281f8 751 str.Printf("ServerIP: %s\r\n", request->hier.host);
b5fb34f1 752 }
62e76326 753
2fe7eff9 754 str.Printf("\r\n");
b5fb34f1 755 /* - HTTP stuff */
2fe7eff9 756 str.Printf("HTTP Request:\r\n");
62e76326 757
c70281f8 758 if (NULL != request) {
e053c141 759 Packer pck;
bb790702
FC
760 String urlpath_or_slash;
761
762 if (request->urlpath.size() != 0)
763 urlpath_or_slash = request->urlpath;
764 else
765 urlpath_or_slash = "/";
766
c9fd01b4 767 str.Printf("%s " SQUIDSTRINGPH " %s/%d.%d\n",
c70281f8 768 RequestMethodStr(request->method),
bb790702 769 SQUIDSTRINGPRINT(urlpath_or_slash),
c9fd01b4 770 AnyP::ProtocolType_str[request->http_ver.protocol],
c70281f8 771 request->http_ver.major, request->http_ver.minor);
e053c141
FC
772 packerToMemInit(&pck, &str);
773 request->header.packInto(&pck);
774 packerClean(&pck);
b5fb34f1 775 }
62e76326 776
2fe7eff9 777 str.Printf("\r\n");
b5fb34f1 778 /* - FTP stuff */
62e76326 779
c70281f8
AJ
780 if (ftp.request) {
781 str.Printf("FTP Request: %s\r\n", ftp.request);
a636cbbf 782 str.Printf("FTP Reply: %s\r\n", (ftp.reply? ftp.reply:"[none]"));
2fe7eff9 783 str.Printf("FTP Msg: ");
c70281f8 784 wordlistCat(ftp.server_msg, &str);
2fe7eff9 785 str.Printf("\r\n");
b5fb34f1 786 }
62e76326 787
2fe7eff9 788 str.Printf("\r\n");
789 mb->Printf("&body=%s", rfc1738_escape_part(str.buf));
790 str.clean();
b5fb34f1 791 return 0;
792}
793
63be0a78 794/// \ingroup ErrorPageInternal
2658f489 795#define CVT_BUF_SZ 512
fe40a877 796
c70281f8 797const char *
4d16918e 798ErrorState::Convert(char token, bool building_deny_info_url, bool allowRecursion)
8213067d 799{
032785bf 800 static MemBuf mb;
eeb423fb 801 const char *p = NULL; /* takes priority over mb if set */
10270faa 802 int do_quote = 1;
4ad8d23d 803 int no_urlescape = 0; /* if true then item is NOT to be further URL-encoded */
cc192b50 804 char ntoabuf[MAX_IPSTRLEN];
eeb423fb 805
2fe7eff9 806 mb.reset();
62e76326 807
9b312a19 808 switch (token) {
62e76326 809
523f44f5 810 case 'a':
2f1431ea 811#if USE_AUTH
a33a428a 812 if (request && request->auth_user_request != NULL)
c70281f8 813 p = request->auth_user_request->username();
523f44f5 814 if (!p)
2f1431ea 815#endif
523f44f5 816 p = "-";
523f44f5 817 break;
88d1e459
AJ
818
819 case 'b':
820 mb.Printf("%d", getMyPort());
821 break;
822
8f872bb6 823 case 'B':
1e98e28b 824 if (building_deny_info_url) break;
c70281f8 825 p = request ? ftpUrlWith2f(request) : "[no URL]";
62e76326 826 break;
827
42b51993 828 case 'c':
1e98e28b 829 if (building_deny_info_url) break;
c70281f8 830 p = errorPageName(type);
62e76326 831 break;
832
4d16918e
CT
833 case 'D':
834 if (!allowRecursion)
835 p = "%D"; // if recursion is not allowed, do not convert
cb4f4424 836#if USE_OPENSSL
4d16918e
CT
837 // currently only SSL error details implemented
838 else if (detail) {
02259ff8 839 detail->useRequest(request);
4d16918e 840 const String &errDetail = detail->toString();
b38b26cb 841 if (errDetail.size() > 0) {
8211c314
CT
842 MemBuf *detail_mb = ConvertText(errDetail.termedBuf(), false);
843 mb.append(detail_mb->content(), detail_mb->contentSize());
844 delete detail_mb;
845 do_quote = 0;
846 }
847 }
4d16918e 848#endif
8211c314 849 if (!mb.contentSize())
4d16918e
CT
850 mb.Printf("[No Error Detail]");
851 break;
852
042461c3 853 case 'e':
c70281f8 854 mb.Printf("%d", xerrno);
62e76326 855 break;
856
042461c3 857 case 'E':
c70281f8
AJ
858 if (xerrno)
859 mb.Printf("(%d) %s", xerrno, strerror(xerrno));
62e76326 860 else
2fe7eff9 861 mb.Printf("[No Error]");
62e76326 862 break;
863
fe40a877 864 case 'f':
1e98e28b 865 if (building_deny_info_url) break;
62e76326 866 /* FTP REQUEST LINE */
c70281f8
AJ
867 if (ftp.request)
868 p = ftp.request;
62e76326 869 else
870 p = "nothing";
62e76326 871 break;
872
fe40a877 873 case 'F':
1e98e28b 874 if (building_deny_info_url) break;
62e76326 875 /* FTP REPLY LINE */
c6b684dd 876 if (ftp.reply)
c70281f8 877 p = ftp.reply;
62e76326 878 else
879 p = "nothing";
62e76326 880 break;
881
7131112f 882 case 'g':
1e98e28b 883 if (building_deny_info_url) break;
a91d3505
AJ
884 /* FTP SERVER RESPONSE */
885 if (ftp.listing) {
0477a072
AJ
886 mb.append(ftp.listing->content(), ftp.listing->contentSize());
887 do_quote = 0;
a91d3505
AJ
888 } else if (ftp.server_msg) {
889 wordlistCat(ftp.server_msg, &mb);
0477a072 890 }
62e76326 891 break;
892
03d7b07f 893 case 'h':
2fe7eff9 894 mb.Printf("%s", getMyHostname());
62e76326 895 break;
896
fe40a877 897 case 'H':
c70281f8 898 if (request) {
b3802bdc 899 if (request->hier.host[0] != '\0') // if non-empty string.
c70281f8 900 p = request->hier.host;
beed27a2 901 else
c70281f8 902 p = request->GetHost();
1e98e28b 903 } else if (!building_deny_info_url)
beed27a2 904 p = "[unknown host]";
62e76326 905 break;
906
f787fb1e 907 case 'i':
4dd643d5 908 mb.Printf("%s", src_addr.toStr(ntoabuf,MAX_IPSTRLEN));
62e76326 909 break;
910
f787fb1e 911 case 'I':
72e4bea1 912 if (request && request->hier.tcpServer != NULL)
4dd643d5 913 p = request->hier.tcpServer->remote.toStr(ntoabuf,MAX_IPSTRLEN);
1e98e28b 914 else if (!building_deny_info_url)
62e76326 915 p = "[unknown]";
62e76326 916 break;
917
5b52cb6c 918 case 'l':
1e98e28b 919 if (building_deny_info_url) break;
0ae3294a 920 mb.append(error_stylesheet.content(), error_stylesheet.contentSize());
5b52cb6c
AJ
921 do_quote = 0;
922 break;
923
fe40a877 924 case 'L':
1e98e28b 925 if (building_deny_info_url) break;
62e76326 926 if (Config.errHtmlText) {
2fe7eff9 927 mb.Printf("%s", Config.errHtmlText);
62e76326 928 do_quote = 0;
1e98e28b 929 } else
62e76326 930 p = "[not available]";
62e76326 931 break;
932
066ed5c1 933 case 'm':
1e98e28b 934 if (building_deny_info_url) break;
2f1431ea 935#if USE_AUTH
c70281f8 936 p = auth_user_request->denyMessage("[not available]");
2f1431ea
AJ
937#else
938 p = "-";
939#endif
62e76326 940 break;
941
fe40a877 942 case 'M':
1e98e28b
AJ
943 if (request)
944 p = RequestMethodStr(request->method);
945 else if (!building_deny_info_url)
946 p= "[unknown method]";
62e76326 947 break;
948
4a972fa2 949 case 'o':
8c93a598 950 p = request ? request->extacl_message.termedBuf() : external_acl_message;
1e98e28b 951 if (!p && !building_deny_info_url)
d73b593b 952 p = "[not available]";
4a972fa2 953 break;
954
fe40a877 955 case 'p':
c70281f8
AJ
956 if (request) {
957 mb.Printf("%d", (int) request->port);
1e98e28b 958 } else if (!building_deny_info_url) {
62e76326 959 p = "[unknown port]";
960 }
62e76326 961 break;
962
fe40a877 963 case 'P':
e7aae06b 964 if (request) {
0c3d3f65 965 p = AnyP::ProtocolType_str[request->protocol];
1e98e28b 966 } else if (!building_deny_info_url) {
e7aae06b
A
967 p = "[unknown protocol]";
968 }
62e76326 969 break;
970
b5af8569 971 case 'R':
1e98e28b 972 if (building_deny_info_url) {
15b02e9a 973 p = (request->urlpath.size() != 0 ? request->urlpath.termedBuf() : "/");
2ce66c0f 974 no_urlescape = 1;
15b02e9a
AJ
975 break;
976 }
c70281f8 977 if (NULL != request) {
d5f8d05f 978 Packer pck;
bb790702
FC
979 String urlpath_or_slash;
980
981 if (request->urlpath.size() != 0)
982 urlpath_or_slash = request->urlpath;
983 else
984 urlpath_or_slash = "/";
985
c9fd01b4 986 mb.Printf("%s " SQUIDSTRINGPH " %s/%d.%d\n",
c70281f8 987 RequestMethodStr(request->method),
bb790702 988 SQUIDSTRINGPRINT(urlpath_or_slash),
c9fd01b4 989 AnyP::ProtocolType_str[request->http_ver.protocol],
c70281f8 990 request->http_ver.major, request->http_ver.minor);
d5f8d05f 991 packerToMemInit(&pck, &mb);
d8f6c79c 992 request->header.packInto(&pck, true); //hide authorization data
d5f8d05f 993 packerClean(&pck);
c70281f8
AJ
994 } else if (request_hdrs) {
995 p = request_hdrs;
62e76326 996 } else {
997 p = "[no request]";
998 }
62e76326 999 break;
1000
1d803566 1001 case 's':
15b02e9a 1002 /* for backward compat we make %s show the full URL. Drop this in some future release. */
1e98e28b 1003 if (building_deny_info_url) {
15b02e9a 1004 p = request ? urlCanonical(request) : url;
fa84c01d 1005 debugs(0, DBG_CRITICAL, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
05320519 1006 } else
15b02e9a 1007 p = visible_appname_string;
62e76326 1008 break;
1009
1d803566 1010 case 'S':
1e98e28b 1011 if (building_deny_info_url) {
4ad8d23d 1012 p = visible_appname_string;
e7aae06b
A
1013 break;
1014 }
62e76326 1015 /* signature may contain %-escapes, recursion */
c70281f8
AJ
1016 if (page_id != ERR_SQUID_SIGNATURE) {
1017 const int saved_id = page_id;
1018 page_id = ERR_SQUID_SIGNATURE;
1019 MemBuf *sign_mb = BuildContent();
2fe7eff9 1020 mb.Printf("%s", sign_mb->content());
1021 sign_mb->clean();
032785bf 1022 delete sign_mb;
c70281f8 1023 page_id = saved_id;
62e76326 1024 do_quote = 0;
1025 } else {
1026 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1027 p = "[%S]";
1028 }
62e76326 1029 break;
1030
fe40a877 1031 case 't':
20efa1c2 1032 mb.Printf("%s", Time::FormatHttpd(squid_curtime));
62e76326 1033 break;
1034
f8291f8f 1035 case 'T':
2fe7eff9 1036 mb.Printf("%s", mkrfc1123(squid_curtime));
62e76326 1037 break;
1038
fe40a877 1039 case 'U':
b3802bdc
AJ
1040 /* Using the fake-https version of canonical so error pages see https:// */
1041 /* even when the url-path cannot be shown as more than '*' */
e7aae06b
A
1042 if (request)
1043 p = urlCanonicalFakeHttps(request);
1044 else if (url)
1045 p = url;
1e98e28b 1046 else if (!building_deny_info_url)
e7aae06b 1047 p = "[no URL]";
62e76326 1048 break;
1049
76cdc28d 1050 case 'u':
1e98e28b
AJ
1051 if (request)
1052 p = urlCanonical(request);
1053 else if (url)
1054 p = url;
1055 else if (!building_deny_info_url)
1056 p = "[no URL]";
62e76326 1057 break;
1058
fe40a877 1059 case 'w':
62e76326 1060 if (Config.adminEmail)
2fe7eff9 1061 mb.Printf("%s", Config.adminEmail);
1e98e28b 1062 else if (!building_deny_info_url)
62e76326 1063 p = "[unknown]";
62e76326 1064 break;
1065
b5fb34f1 1066 case 'W':
1e98e28b 1067 if (building_deny_info_url) break;
62e76326 1068 if (Config.adminEmail && Config.onoff.emailErrData)
c70281f8 1069 Dump(&mb);
4ad8d23d 1070 no_urlescape = 1;
62e76326 1071 break;
1072
e4a8468d 1073 case 'x':
cb4f4424 1074#if USE_OPENSSL
e4a8468d
CT
1075 if (detail)
1076 mb.Printf("%s", detail->errorName());
0ab68838
CT
1077 else
1078#endif
1079 if (!building_deny_info_url)
1080 p = "[Unknown Error Code]";
e4a8468d
CT
1081 break;
1082
fe40a877 1083 case 'z':
1e98e28b 1084 if (building_deny_info_url) break;
3ff65596
AR
1085 if (dnsError.size() > 0)
1086 p = dnsError.termedBuf();
0477a072
AJ
1087 else if (ftp.cwd_msg)
1088 p = ftp.cwd_msg;
62e76326 1089 else
1090 p = "[unknown]";
62e76326 1091 break;
1092
43ae1d95 1093 case 'Z':
1e98e28b 1094 if (building_deny_info_url) break;
c70281f8
AJ
1095 if (err_msg)
1096 p = err_msg;
43ae1d95 1097 else
1098 p = "[unknown]";
43ae1d95 1099 break;
1100
e347f8e5 1101 case '%':
62e76326 1102 p = "%";
62e76326 1103 break;
1104
9b312a19 1105 default:
2fe7eff9 1106 mb.Printf("%%%c", token);
cbba2ba2 1107 do_quote = 0;
62e76326 1108 break;
9b312a19 1109 }
62e76326 1110
137ee196 1111 if (!p)
62e76326 1112 p = mb.buf; /* do not use mb after this assignment! */
1113
137ee196 1114 assert(p);
62e76326 1115
bf8fe701 1116 debugs(4, 3, "errorConvert: %%" << token << " --> '" << p << "'" );
62e76326 1117
10270faa 1118 if (do_quote)
62e76326 1119 p = html_quote(p);
1120
1e98e28b 1121 if (building_deny_info_url && !no_urlescape)
15b02e9a
AJ
1122 p = rfc1738_escape_part(p);
1123
9b312a19 1124 return p;
8213067d 1125}
e381a13d 1126
15b02e9a 1127void
70efcae0 1128ErrorState::DenyInfoLocation(const char *name, HttpRequest *aRequest, MemBuf &result)
15b02e9a
AJ
1129{
1130 char const *m = name;
1131 char const *p = m;
1132 char const *t;
1133
aed9a15b
AJ
1134 if (m[0] == '3')
1135 m += 4; // skip "3xx:"
1136
15b02e9a
AJ
1137 while ((p = strchr(m, '%'))) {
1138 result.append(m, p - m); /* copy */
4d16918e 1139 t = Convert(*++p, true, true); /* convert */
15b02e9a
AJ
1140 result.Printf("%s", t); /* copy */
1141 m = p + 1; /* advance */
1142 }
1143
1144 if (*m)
1145 result.Printf("%s", m); /* copy tail */
1146
1147 assert((size_t)result.contentSize() == strlen(result.content()));
1148}
1149
cb69b4c7 1150HttpReply *
c70281f8 1151ErrorState::BuildHttpReply()
cb69b4c7 1152{
06a5ae20 1153 HttpReply *rep = new HttpReply;
c70281f8 1154 const char *name = errorPageName(page_id);
cb69b4c7 1155 /* no LMT for error pages; error pages expire immediately */
62e76326 1156
d4d63422 1157 if (name[0] == '3' || (name[0] != '2' && name[0] != '4' && name[0] != '5' && strchr(name, ':'))) {
62e76326 1158 /* Redirection */
955394ce 1159 Http::StatusCode status = Http::scMovedTemporarily;
aed9a15b
AJ
1160 // Use configured 3xx reply status if set.
1161 if (name[0] == '3')
1162 status = httpStatus;
1163 else {
1164 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
526ed14e 1165 if (request->method != Http::METHOD_GET && request->method != Http::METHOD_HEAD && request->http_ver >= Http::ProtocolVersion(1,1))
955394ce 1166 status = Http::scTemporaryRedirect;
aed9a15b
AJ
1167 }
1168
ec80c740 1169 rep->setHeaders(status, NULL, "text/html;charset=utf-8", 0, 0, -1);
c44950c4 1170
c70281f8 1171 if (request) {
15b02e9a
AJ
1172 MemBuf redirect_location;
1173 redirect_location.init();
1174 DenyInfoLocation(name, request, redirect_location);
1175 httpHeaderPutStrf(&rep->header, HDR_LOCATION, "%s", redirect_location.content() );
c44950c4 1176 }
1177
c70281f8 1178 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%d %s", httpStatus, "Access Denied");
76cdc28d 1179 } else {
c70281f8 1180 MemBuf *content = BuildContent();
ec80c740 1181 rep->setHeaders(httpStatus, NULL, "text/html;charset=utf-8", content->contentSize(), 0, -1);
62e76326 1182 /*
1183 * include some information for downstream caches. Implicit
1184 * replaceable content. This isn't quite sufficient. xerrno is not
1185 * necessarily meaningful to another system, so we really should
1186 * expand it. Additionally, we should identify ourselves. Someone
1187 * might want to know. Someone _will_ want to know OTOH, the first
1188 * X-CACHE-MISS entry should tell us who.
1189 */
c70281f8 1190 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%s %d", name, xerrno);
ccb24616 1191
5bf33a09
AJ
1192#if USE_ERR_LOCALES
1193 /*
1194 * If error page auto-negotiate is enabled in any way, send the Vary.
1195 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1196 * We have even better reasons though:
1197 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1198 */
9e008dda 1199 if (!Config.errorDirectory) {
5bf33a09 1200 /* We 'negotiated' this ONLY from the Accept-Language. */
70d1b64c
AJ
1201 rep->header.delById(HDR_VARY);
1202 rep->header.putStr(HDR_VARY, "Accept-Language");
5bf33a09
AJ
1203 }
1204
1205 /* add the Content-Language header according to RFC section 14.12 */
9e008dda 1206 if (err_language) {
70d1b64c 1207 rep->header.putStr(HDR_CONTENT_LANGUAGE, err_language);
9e008dda 1208 } else
5bf33a09
AJ
1209#endif /* USE_ERROR_LOCALES */
1210 {
ccb24616 1211 /* default templates are in English */
5bf33a09 1212 /* language is known unless error_directory override used */
9e008dda 1213 if (!Config.errorDirectory)
70d1b64c 1214 rep->header.putStr(HDR_CONTENT_LANGUAGE, "en");
ccb24616
AJ
1215 }
1216
0521f8be 1217 rep->body.setMb(content);
032785bf 1218 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
76cdc28d 1219 }
62e76326 1220
7a957a93
AR
1221 // Make sure error codes get back to the client side for logging and
1222 // error tracking.
129fe2a1
CT
1223 if (request) {
1224 int edc = ERR_DETAIL_NONE; // error detail code
cb4f4424 1225#if USE_OPENSSL
129fe2a1
CT
1226 if (detail)
1227 edc = detail->errorNo();
1228 else
1229#endif
1230 if (detailCode)
1231 edc = detailCode;
1232 else
1233 edc = xerrno;
1234 request->detailError(type, edc);
1235 }
1236
cb69b4c7 1237 return rep;
1238}
1239
c70281f8
AJ
1240MemBuf *
1241ErrorState::BuildContent()
cb69b4c7 1242{
43000484 1243 const char *m = NULL;
43000484 1244
c70281f8 1245 assert(page_id > ERR_NONE && page_id < error_page_count);
43000484
AJ
1246
1247#if USE_ERR_LOCALES
8ff2520a 1248 ErrorPageFile *localeTmpl = NULL;
43000484
AJ
1249
1250 /** error_directory option in squid.conf overrides translations.
30b78ef1 1251 * Custom errors are always found either in error_directory or the templates directory.
43000484
AJ
1252 * Otherwise locate the Accept-Language header
1253 */
02259ff8
CT
1254 if (!Config.errorDirectory && page_id < ERR_MAX) {
1255 if (err_language && err_language != Config.errorDefaultLanguage)
1256 safe_free(err_language);
1257
8ff2520a 1258 localeTmpl = new ErrorPageFile(err_type_str[page_id], static_cast<err_type>(page_id));
02259ff8
CT
1259 if (localeTmpl->loadFor(request)) {
1260 m = localeTmpl->text();
1261 assert(localeTmpl->language());
1262 err_language = xstrdup(localeTmpl->language());
43000484
AJ
1263 }
1264 }
1265#endif /* USE_ERR_LOCALES */
1266
1267 /** \par
1268 * If client-specific error templates are not enabled or available.
1269 * fall back to the old style squid.conf settings.
1270 */
9e008dda 1271 if (!m) {
43000484 1272 m = error_text[page_id];
5bf33a09 1273#if USE_ERR_LOCALES
9e008dda 1274 if (!Config.errorDirectory)
5bf33a09
AJ
1275 err_language = Config.errorDefaultLanguage;
1276#endif
58d4b38b 1277 debugs(4, 2, HERE << "No existing error page language negotiated for " << errorPageName(page_id) << ". Using default error file.");
43000484
AJ
1278 }
1279
6551ae9d 1280 MemBuf *result = ConvertText(m, true);
960cb599 1281#if USE_ERR_LOCALES
02259ff8
CT
1282 if (localeTmpl)
1283 delete localeTmpl;
960cb599 1284#endif
6551ae9d 1285 return result;
4d16918e
CT
1286}
1287
1288MemBuf *ErrorState::ConvertText(const char *text, bool allowRecursion)
1289{
1290 MemBuf *content = new MemBuf;
1291 const char *p;
1292 const char *m = text;
1d803566 1293 assert(m);
43000484 1294 content->init();
62e76326 1295
cb69b4c7 1296 while ((p = strchr(m, '%'))) {
2fe7eff9 1297 content->append(m, p - m); /* copy */
4d16918e 1298 const char *t = Convert(*++p, false, allowRecursion); /* convert */
2fe7eff9 1299 content->Printf("%s", t); /* copy */
c70281f8 1300 m = p + 1; /* advance */
cb69b4c7 1301 }
62e76326 1302
1d803566 1303 if (*m)
2fe7eff9 1304 content->Printf("%s", m); /* copy tail */
62e76326 1305
857e4512
AJ
1306 content->terminate();
1307
032785bf 1308 assert((size_t)content->contentSize() == strlen(content->content()));
62e76326 1309
cb69b4c7 1310 return content;
1311}