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