]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/errorpage.cc
2 * Copyright (C) 1996-2018 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 04 Error Generation */
13 #include "clients/forward.h"
14 #include "comm/Connection.h"
15 #include "comm/Write.h"
16 #include "err_detail_type.h"
17 #include "errorpage.h"
20 #include "html_quote.h"
21 #include "HttpHeaderTools.h"
22 #include "HttpReply.h"
23 #include "HttpRequest.h"
25 #include "MemObject.h"
27 #include "SquidConfig.h"
32 #include "auth/UserRequest.h"
34 #include "SquidTime.h"
36 #include "ssl/ErrorDetailManager.h"
40 \defgroup ErrorPageInternal Error Page Internals
43 \section Abstract Abstract:
44 * These routines are used to generate error messages to be
45 * sent to clients. The error type is used to select between
46 * the various message formats. (formats are stored in the
47 * Config.errorDirectory)
50 #if !defined(DEFAULT_SQUID_ERROR_DIR)
51 /** Where to look for errors if config path fails.
52 \note Please use ./configure --datadir=/path instead of patching
54 #define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
57 /// \ingroup ErrorPageInternal
58 CBDATA_CLASS_INIT(ErrorState
);
62 /// \ingroup ErrorPageInternal
66 Http::StatusCode page_redirect
;
67 } ErrorDynamicPageInfo
;
69 /* local constant and vars */
72 \ingroup ErrorPageInternal
74 \note hard coded error messages are not appended with %S
75 * automagically to give you more control on the format
78 int type
; /* and page_id */
88 "<div id=\"footer\">\n"
89 "Generated %T by %h (%s)\n"
99 /// \ingroup ErrorPageInternal
100 static std::vector
<ErrorDynamicPageInfo
*> ErrorDynamicPages
;
102 /* local prototypes */
104 /// \ingroup ErrorPageInternal
105 static const int error_hard_text_count
= sizeof(error_hard_text
) / sizeof(*error_hard_text
);
107 /// \ingroup ErrorPageInternal
108 static char **error_text
= NULL
;
110 /// \ingroup ErrorPageInternal
111 static int error_page_count
= 0;
113 /// \ingroup ErrorPageInternal
114 static MemBuf error_stylesheet
;
116 static const char *errorFindHardText(err_type type
);
117 static ErrorDynamicPageInfo
*errorDynamicPageInfoCreate(int id
, const char *page_name
);
118 static void errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
);
119 static IOCB errorSendComplete
;
121 /// \ingroup ErrorPageInternal
122 /// manages an error page template
123 class ErrorPageFile
: public TemplateFile
126 ErrorPageFile(const char *name
, const err_type code
) : TemplateFile(name
,code
) {textBuf
.init();}
128 /// The template text data read from disk
129 const char *text() { return textBuf
.content(); }
132 /// stores the data read from disk to a local buffer
133 virtual bool parse(const char *buf
, int len
, bool) {
135 textBuf
.append(buf
, len
);
139 MemBuf textBuf
; ///< A buffer to store the error page
142 /// \ingroup ErrorPageInternal
143 err_type
&operator++ (err_type
&anErr
)
145 int tmp
= (int)anErr
;
146 anErr
= (err_type
)(++tmp
);
150 /// \ingroup ErrorPageInternal
151 int operator - (err_type
const &anErr
, err_type
const &anErr2
)
153 return (int)anErr
- (int)anErr2
;
157 errorInitialize(void)
161 error_page_count
= ERR_MAX
+ ErrorDynamicPages
.size();
162 error_text
= static_cast<char **>(xcalloc(error_page_count
, sizeof(char *)));
164 for (i
= ERR_NONE
, ++i
; i
< error_page_count
; ++i
) {
165 safe_free(error_text
[i
]);
167 if ((text
= errorFindHardText(i
))) {
169 * Index any hard-coded error text into defaults.
171 error_text
[i
] = xstrdup(text
);
173 } else if (i
< ERR_MAX
) {
175 * Index precompiled fixed template files from one of two sources:
176 * (a) default language translation directory (error_default_language)
177 * (b) admin specified custom directory (error_directory)
179 ErrorPageFile
errTmpl(err_type_str
[i
], i
);
180 error_text
[i
] = errTmpl
.loadDefault() ? xstrdup(errTmpl
.text()) : NULL
;
183 * Index any unknown file names used by deny_info.
185 ErrorDynamicPageInfo
*info
= ErrorDynamicPages
.at(i
- ERR_MAX
);
186 assert(info
&& info
->id
== i
&& info
->page_name
);
188 const char *pg
= info
->page_name
;
189 if (info
->page_redirect
!= Http::scNone
)
190 pg
= info
->page_name
+4;
192 if (strchr(pg
, ':') == NULL
) {
193 /** But only if they are not redirection URL. */
194 ErrorPageFile
errTmpl(pg
, ERR_MAX
);
195 error_text
[i
] = errTmpl
.loadDefault() ? xstrdup(errTmpl
.text()) : NULL
;
200 error_stylesheet
.reset();
202 // look for and load stylesheet into global MemBuf for it.
203 if (Config
.errorStylesheet
) {
204 ErrorPageFile
tmpl("StylesSheet", ERR_MAX
);
205 tmpl
.loadFromFile(Config
.errorStylesheet
);
206 error_stylesheet
.appendf("%s",tmpl
.text());
210 Ssl::errorDetailInitialize();
220 for (i
= ERR_NONE
+ 1; i
< error_page_count
; ++i
)
221 safe_free(error_text
[i
]);
223 safe_free(error_text
);
226 while (!ErrorDynamicPages
.empty()) {
227 errorDynamicPageInfoDestroy(ErrorDynamicPages
.back());
228 ErrorDynamicPages
.pop_back();
231 error_page_count
= 0;
234 Ssl::errorDetailClean();
238 /// \ingroup ErrorPageInternal
240 errorFindHardText(err_type type
)
244 for (i
= 0; i
< error_hard_text_count
; ++i
)
245 if (error_hard_text
[i
].type
== type
)
246 return error_hard_text
[i
].text
;
251 TemplateFile::TemplateFile(const char *name
, const err_type code
): silent(false), wasLoaded(false), templateName(name
), templateCode(code
)
257 TemplateFile::loadDefault()
259 if (loaded()) // already loaded?
262 /** test error_directory configured location */
263 if (Config
.errorDirectory
) {
264 char path
[MAXPATHLEN
];
265 snprintf(path
, sizeof(path
), "%s/%s", Config
.errorDirectory
, templateName
.termedBuf());
270 /** test error_default_language location */
271 if (!loaded() && Config
.errorDefaultLanguage
) {
272 if (!tryLoadTemplate(Config
.errorDefaultLanguage
)) {
273 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "Unable to load default error language files. Reset to backups.");
278 /* test default location if failed (templates == English translation base templates) */
280 tryLoadTemplate("templates");
283 /* giving up if failed */
285 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "WARNING: failed to find or read error text file " << templateName
);
286 parse("Internal Error: Missing Template ", 33, '\0');
287 parse(templateName
.termedBuf(), templateName
.size(), '\0');
294 TemplateFile::tryLoadTemplate(const char *lang
)
298 char path
[MAXPATHLEN
];
299 /* TODO: prep the directory path string to prevent snprintf ... */
300 snprintf(path
, sizeof(path
), "%s/%s/%s",
301 DEFAULT_SQUID_ERROR_DIR
, lang
, templateName
.termedBuf());
302 path
[MAXPATHLEN
-1] = '\0';
304 if (loadFromFile(path
))
308 if ( strlen(lang
) == 2) {
309 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
310 /* use first result. */
311 debugs(4,2, HERE
<< "wildcard fallback errors not coded yet.");
319 TemplateFile::loadFromFile(const char *path
)
325 if (loaded()) // already loaded?
328 fd
= file_open(path
, O_RDONLY
| O_TEXT
);
331 /* with dynamic locale negotiation we may see some failures before a success. */
332 if (!silent
&& templateCode
< TCP_RESET
) {
334 debugs(4, DBG_CRITICAL
, "ERROR: loading file '" << path
<< "': " << xstrerr(xerrno
));
340 while ((len
= FD_READ_METHOD(fd
, buf
, sizeof(buf
))) > 0) {
341 if (!parse(buf
, len
, false)) {
342 debugs(4, DBG_CRITICAL
, "ERROR: parsing error in template file: " << path
);
351 debugs(4, DBG_CRITICAL
, MYNAME
<< "ERROR: failed to fully read: '" << path
<< "': " << xstrerr(xerrno
));
360 bool strHdrAcptLangGetItem(const String
&hdr
, char *lang
, int langLen
, size_t &pos
)
362 while (pos
< hdr
.size()) {
364 /* skip any initial whitespace. */
365 while (pos
< hdr
.size() && xisspace(hdr
[pos
]))
369 * Header value format:
370 * - sequence of whitespace delimited tags
371 * - each tag may suffix with ';'.* which we can ignore.
372 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
373 * with preference given to an exact match.
375 bool invalid_byte
= false;
377 while (pos
< hdr
.size() && hdr
[pos
] != ';' && hdr
[pos
] != ',' && !xisspace(hdr
[pos
]) && dt
< (lang
+ (langLen
-1)) ) {
379 #if USE_HTTP_VIOLATIONS
380 // if accepting violations we may as well accept some broken browsers
381 // which may send us the right code, wrong ISO formatting.
386 *dt
= xtolower(hdr
[pos
]);
387 // valid codes only contain A-Z, hyphen (-) and *
388 if (*dt
!= '-' && *dt
!= '*' && (*dt
< 'a' || *dt
> 'z') )
391 ++dt
; // move to next destination byte.
395 *dt
= '\0'; // nul-terminated the filename content string before system use.
397 // if we terminated the tag on garbage or ';' we need to skip to the next ',' or end of header.
398 while (pos
< hdr
.size() && hdr
[pos
] != ',')
401 if (pos
< hdr
.size() && hdr
[pos
] == ',')
404 debugs(4, 9, "STATE: lang=" << lang
<< ", pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
406 /* if we found anything we might use, try it. */
407 if (*lang
!= '\0' && !invalid_byte
)
414 TemplateFile::loadFor(const HttpRequest
*request
)
419 if (loaded()) // already loaded?
422 if (!request
|| !request
->header
.getList(Http::HdrType::ACCEPT_LANGUAGE
, &hdr
))
426 size_t pos
= 0; // current parsing position in header string
428 debugs(4, 6, HERE
<< "Testing Header: '" << hdr
<< "'");
430 while ( strHdrAcptLangGetItem(hdr
, lang
, 256, pos
) ) {
432 /* wildcard uses the configured default language */
433 if (lang
[0] == '*' && lang
[1] == '\0') {
434 debugs(4, 6, HERE
<< "Found language '" << lang
<< "'. Using configured default.");
438 debugs(4, 6, HERE
<< "Found language '" << lang
<< "', testing for available template");
440 if (tryLoadTemplate(lang
)) {
441 /* store the language we found for the Content-Language reply header */
444 } else if (Config
.errorLogMissingLanguages
) {
445 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << lang
);
453 /// \ingroup ErrorPageInternal
454 static ErrorDynamicPageInfo
*
455 errorDynamicPageInfoCreate(int id
, const char *page_name
)
457 ErrorDynamicPageInfo
*info
= new ErrorDynamicPageInfo
;
459 info
->page_name
= xstrdup(page_name
);
460 info
->page_redirect
= static_cast<Http::StatusCode
>(atoi(page_name
));
462 /* WARNING on redirection status:
463 * 2xx are permitted, but not documented officially.
464 * - might be useful for serving static files (PAC etc) in special cases
465 * 3xx require a URL suitable for Location: header.
466 * - the current design does not allow for a Location: URI as well as a local file template
467 * although this possibility is explicitly permitted in the specs.
468 * 4xx-5xx require a local file template.
469 * - sending Location: on these codes with no body is invalid by the specs.
470 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
471 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
473 if (info
->page_redirect
== Http::scNone
)
474 ; // special case okay.
475 else if (info
->page_redirect
< 200 || info
->page_redirect
> 599) {
477 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
479 } else if ( /* >= 200 && */ info
->page_redirect
< 300 && strchr(&(page_name
[4]), ':')) {
480 // 2xx require a local template file
481 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
483 } else if (info
->page_redirect
>= 300 && info
->page_redirect
<= 399 && !strchr(&(page_name
[4]), ':')) {
484 // 3xx require an absolute URL
485 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a URL on '" << page_name
<< "'");
487 } else if (info
->page_redirect
>= 400 /* && <= 599 */ && strchr(&(page_name
[4]), ':')) {
488 // 4xx/5xx require a local template file
489 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
497 /// \ingroup ErrorPageInternal
499 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
)
502 safe_free(info
->page_name
);
506 /// \ingroup ErrorPageInternal
508 errorPageId(const char *page_name
)
510 for (int i
= 0; i
< ERR_MAX
; ++i
) {
511 if (strcmp(err_type_str
[i
], page_name
) == 0)
515 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); ++j
) {
516 if (strcmp(ErrorDynamicPages
[j
]->page_name
, page_name
) == 0)
524 errorReservePageId(const char *page_name
)
526 ErrorDynamicPageInfo
*info
;
527 int id
= errorPageId(page_name
);
529 if (id
== ERR_NONE
) {
530 info
= errorDynamicPageInfoCreate(ERR_MAX
+ ErrorDynamicPages
.size(), page_name
);
531 ErrorDynamicPages
.push_back(info
);
538 /// \ingroup ErrorPageInternal
540 errorPageName(int pageId
)
542 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
543 return err_type_str
[pageId
];
545 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
546 return ErrorDynamicPages
[pageId
- ERR_MAX
]->page_name
;
548 return "ERR_UNKNOWN"; /* should not happen */
552 ErrorState::NewForwarding(err_type type
, HttpRequestPointer
&request
)
554 const Http::StatusCode status
= (request
&& request
->flags
.needValidation
) ?
555 Http::scGatewayTimeout
: Http::scServiceUnavailable
;
556 return new ErrorState(type
, status
, request
.getRaw());
559 ErrorState::ErrorState(err_type t
, Http::StatusCode status
, HttpRequest
* req
) :
565 if (page_id
>= ERR_MAX
&& ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
!= Http::scNone
)
566 httpStatus
= ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
;
570 src_addr
= req
->client_addr
;
575 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
577 assert(entry
->mem_obj
!= NULL
);
578 assert (entry
->isEmpty());
579 debugs(4, 4, "Creating an error page for entry " << entry
<<
580 " with errorstate " << err
<<
581 " page id " << err
->page_id
);
583 if (entry
->store_status
!= STORE_PENDING
) {
584 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
586 * If the entry is not STORE_PENDING, then no clients
587 * care about it, and we don't need to generate an
590 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
591 assert(entry
->mem_obj
->nclients
== 0);
596 if (err
->page_id
== TCP_RESET
) {
598 debugs(4, 2, "RSTing this reply");
599 err
->request
->flags
.resetTcp
= true;
603 entry
->storeErrorResponse(err
->BuildHttpReply());
608 errorSend(const Comm::ConnectionPointer
&conn
, ErrorState
* err
)
610 debugs(4, 3, conn
<< ", err=" << err
);
611 assert(Comm::IsConnOpen(conn
));
613 HttpReplyPointer
rep(err
->BuildHttpReply());
615 MemBuf
*mb
= rep
->pack();
616 AsyncCall::Pointer call
= commCbCall(78, 5, "errorSendComplete",
617 CommIoCbPtrFun(&errorSendComplete
, err
));
618 Comm::Write(conn
, mb
, call
);
623 \ingroup ErrorPageAPI
625 * Called by commHandleWrite() after data has been written
626 * to the client socket.
628 \note If there is a callback, the callback is responsible for
629 * closing the FD, otherwise we do it ourselves.
632 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *, size_t size
, Comm::Flag errflag
, int, void *data
)
634 ErrorState
*err
= static_cast<ErrorState
*>(data
);
635 debugs(4, 3, HERE
<< conn
<< ", size=" << size
);
637 if (errflag
!= Comm::ERR_CLOSING
) {
639 debugs(4, 3, "errorSendComplete: callback");
640 err
->callback(conn
->fd
, err
->callback_data
, size
);
642 debugs(4, 3, "errorSendComplete: comm_close");
650 ErrorState::~ErrorState()
652 safe_free(redirect_url
);
654 safe_free(request_hdrs
);
655 wordlistDestroy(&ftp
.server_msg
);
656 safe_free(ftp
.request
);
657 safe_free(ftp
.reply
);
660 if (err_language
!= Config
.errorDefaultLanguage
)
662 safe_free(err_language
);
669 ErrorState::Dump(MemBuf
* mb
)
672 char ntoabuf
[MAX_IPSTRLEN
];
675 /* email subject line */
676 str
.appendf("CacheErrorInfo - %s", errorPageName(type
));
677 mb
->appendf("?subject=%s", rfc1738_escape_part(str
.buf
));
680 str
.appendf("CacheHost: %s\r\n", getMyHostname());
682 str
.appendf("ErrPage: %s\r\n", errorPageName(type
));
685 str
.appendf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
687 str
.append("Err: [none]\r\n", 13);
690 if (auth_user_request
.getRaw() && auth_user_request
->denyMessage())
691 str
.appendf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
693 if (dnsError
.size() > 0)
694 str
.appendf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
697 str
.appendf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
700 str
.appendf("ClientIP: %s\r\n", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
702 if (request
&& request
->hier
.host
[0] != '\0') {
703 str
.appendf("ServerIP: %s\r\n", request
->hier
.host
);
706 str
.append("\r\n", 2);
708 str
.append("HTTP Request:\r\n", 15);
710 str
.appendf(SQUIDSBUFPH
" " SQUIDSBUFPH
" %s/%d.%d\n",
711 SQUIDSBUFPRINT(request
->method
.image()),
712 SQUIDSBUFPRINT(request
->url
.path()),
713 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
714 request
->http_ver
.major
, request
->http_ver
.minor
);
715 request
->header
.packInto(&str
);
718 str
.append("\r\n", 2);
722 str
.appendf("FTP Request: %s\r\n", ftp
.request
);
723 str
.appendf("FTP Reply: %s\r\n", (ftp
.reply
? ftp
.reply
:"[none]"));
724 str
.append("FTP Msg: ", 9);
725 wordlistCat(ftp
.server_msg
, &str
);
726 str
.append("\r\n", 2);
729 str
.append("\r\n", 2);
730 mb
->appendf("&body=%s", rfc1738_escape_part(str
.buf
));
735 /// \ingroup ErrorPageInternal
736 #define CVT_BUF_SZ 512
739 ErrorState::Convert(char token
, bool building_deny_info_url
, bool allowRecursion
)
742 const char *p
= NULL
; /* takes priority over mb if set */
744 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
745 char ntoabuf
[MAX_IPSTRLEN
];
753 if (request
&& request
->auth_user_request
)
754 p
= request
->auth_user_request
->username();
761 // TODO: When/if we get ALE here, pass it as well
762 if (const auto addr
= FindListeningPortAddress(request
.getRaw(), nullptr))
763 mb
.appendf("%s", addr
->toStr(ntoabuf
, MAX_IPSTRLEN
));
769 mb
.appendf("%u", getMyPort());
773 if (building_deny_info_url
) break;
775 const SBuf
&tmp
= Ftp::UrlWith2f(request
.getRaw());
776 mb
.append(tmp
.rawContent(), tmp
.length());
782 if (building_deny_info_url
) break;
783 p
= errorPageName(type
);
788 p
= "%D"; // if recursion is not allowed, do not convert
790 // currently only SSL error details implemented
792 detail
->useRequest(request
.getRaw());
793 const String
&errDetail
= detail
->toString();
794 if (errDetail
.size() > 0) {
795 MemBuf
*detail_mb
= ConvertText(errDetail
.termedBuf(), false);
796 mb
.append(detail_mb
->content(), detail_mb
->contentSize());
802 if (!mb
.contentSize())
803 mb
.append("[No Error Detail]", 17);
807 mb
.appendf("%d", xerrno
);
812 mb
.appendf("(%d) %s", xerrno
, strerror(xerrno
));
814 mb
.append("[No Error]", 10);
818 if (building_deny_info_url
) break;
819 /* FTP REQUEST LINE */
827 if (building_deny_info_url
) break;
836 if (building_deny_info_url
) break;
837 /* FTP SERVER RESPONSE */
839 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
841 } else if (ftp
.server_msg
) {
842 wordlistCat(ftp
.server_msg
, &mb
);
847 mb
.appendf("%s", getMyHostname());
852 if (request
->hier
.host
[0] != '\0') // if non-empty string.
853 p
= request
->hier
.host
;
855 p
= request
->url
.host();
856 } else if (!building_deny_info_url
)
857 p
= "[unknown host]";
861 mb
.appendf("%s", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
865 if (request
&& request
->hier
.tcpServer
)
866 p
= request
->hier
.tcpServer
->remote
.toStr(ntoabuf
,MAX_IPSTRLEN
);
867 else if (!building_deny_info_url
)
872 if (building_deny_info_url
) break;
873 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
878 if (building_deny_info_url
) break;
879 if (Config
.errHtmlText
) {
880 mb
.appendf("%s", Config
.errHtmlText
);
883 p
= "[not available]";
887 if (building_deny_info_url
) break;
889 if (auth_user_request
.getRaw())
890 p
= auth_user_request
->denyMessage("[not available]");
892 p
= "[not available]";
900 const SBuf
&m
= request
->method
.image();
901 mb
.append(m
.rawContent(), m
.length());
902 } else if (!building_deny_info_url
)
903 p
= "[unknown method]";
907 if (!building_deny_info_url
)
910 p
= request
? request
->extacl_message
.termedBuf() : external_acl_message
;
911 if (!p
&& !building_deny_info_url
)
912 p
= "[not available]";
917 mb
.appendf("%u", request
->url
.port());
918 } else if (!building_deny_info_url
) {
919 p
= "[unknown port]";
925 const SBuf
&m
= request
->url
.getScheme().image();
926 mb
.append(m
.rawContent(), m
.length());
927 } else if (!building_deny_info_url
) {
928 p
= "[unknown protocol]";
933 if (building_deny_info_url
) {
934 if (request
!= NULL
) {
935 const SBuf
&tmp
= request
->url
.path();
936 mb
.append(tmp
.rawContent(), tmp
.length());
943 mb
.appendf(SQUIDSBUFPH
" " SQUIDSBUFPH
" %s/%d.%d\n",
944 SQUIDSBUFPRINT(request
->method
.image()),
945 SQUIDSBUFPRINT(request
->url
.path()),
946 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
947 request
->http_ver
.major
, request
->http_ver
.minor
);
948 request
->header
.packInto(&mb
, true); //hide authorization data
949 } else if (request_hdrs
) {
957 /* for backward compat we make %s show the full URL. Drop this in some future release. */
958 if (building_deny_info_url
) {
960 const SBuf
&tmp
= request
->effectiveRequestUri();
961 mb
.append(tmp
.rawContent(), tmp
.length());
964 debugs(0, DBG_CRITICAL
, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
966 p
= visible_appname_string
;
970 if (building_deny_info_url
) {
971 p
= visible_appname_string
;
974 /* signature may contain %-escapes, recursion */
975 if (page_id
!= ERR_SQUID_SIGNATURE
) {
976 const int saved_id
= page_id
;
977 page_id
= ERR_SQUID_SIGNATURE
;
978 MemBuf
*sign_mb
= BuildContent();
979 mb
.append(sign_mb
->content(), sign_mb
->contentSize());
985 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
991 mb
.appendf("%s", Time::FormatHttpd(squid_curtime
));
995 mb
.appendf("%s", mkrfc1123(squid_curtime
));
999 /* Using the fake-https version of absolute-URI so error pages see https:// */
1000 /* even when the url-path cannot be shown as more than '*' */
1002 p
= urlCanonicalFakeHttps(request
.getRaw());
1005 else if (!building_deny_info_url
)
1011 const SBuf
&tmp
= request
->effectiveRequestUri();
1012 mb
.append(tmp
.rawContent(), tmp
.length());
1015 else if (!building_deny_info_url
)
1020 if (Config
.adminEmail
)
1021 mb
.appendf("%s", Config
.adminEmail
);
1022 else if (!building_deny_info_url
)
1027 if (building_deny_info_url
) break;
1028 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
1036 mb
.appendf("%s", detail
->errorName());
1039 if (!building_deny_info_url
)
1040 p
= "[Unknown Error Code]";
1044 if (building_deny_info_url
) break;
1045 if (dnsError
.size() > 0)
1046 p
= dnsError
.termedBuf();
1047 else if (ftp
.cwd_msg
)
1054 if (building_deny_info_url
) break;
1066 mb
.appendf("%%%c", token
);
1072 p
= mb
.buf
; /* do not use mb after this assignment! */
1076 debugs(4, 3, "errorConvert: %%" << token
<< " --> '" << p
<< "'" );
1081 if (building_deny_info_url
&& !no_urlescape
)
1082 p
= rfc1738_escape_part(p
);
1088 ErrorState::DenyInfoLocation(const char *name
, HttpRequest
*, MemBuf
&result
)
1090 char const *m
= name
;
1095 m
+= 4; // skip "3xx:"
1097 while ((p
= strchr(m
, '%'))) {
1098 result
.append(m
, p
- m
); /* copy */
1099 t
= Convert(*++p
, true, true); /* convert */
1100 result
.appendf("%s", t
); /* copy */
1101 m
= p
+ 1; /* advance */
1105 result
.appendf("%s", m
); /* copy tail */
1107 assert((size_t)result
.contentSize() == strlen(result
.content()));
1111 ErrorState::BuildHttpReply()
1113 HttpReply
*rep
= new HttpReply
;
1114 const char *name
= errorPageName(page_id
);
1115 /* no LMT for error pages; error pages expire immediately */
1117 if (name
[0] == '3' || (name
[0] != '2' && name
[0] != '4' && name
[0] != '5' && strchr(name
, ':'))) {
1119 Http::StatusCode status
= Http::scFound
;
1120 // Use configured 3xx reply status if set.
1122 status
= httpStatus
;
1124 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1125 if (request
&& request
->method
!= Http::METHOD_GET
&& request
->method
!= Http::METHOD_HEAD
&& request
->http_ver
>= Http::ProtocolVersion(1,1))
1126 status
= Http::scTemporaryRedirect
;
1129 rep
->setHeaders(status
, NULL
, "text/html;charset=utf-8", 0, 0, -1);
1132 MemBuf redirect_location
;
1133 redirect_location
.init();
1134 DenyInfoLocation(name
, request
.getRaw(), redirect_location
);
1135 httpHeaderPutStrf(&rep
->header
, Http::HdrType::LOCATION
, "%s", redirect_location
.content() );
1138 httpHeaderPutStrf(&rep
->header
, Http::HdrType::X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
1140 MemBuf
*content
= BuildContent();
1141 rep
->setHeaders(httpStatus
, NULL
, "text/html;charset=utf-8", content
->contentSize(), 0, -1);
1143 * include some information for downstream caches. Implicit
1144 * replaceable content. This isn't quite sufficient. xerrno is not
1145 * necessarily meaningful to another system, so we really should
1146 * expand it. Additionally, we should identify ourselves. Someone
1147 * might want to know. Someone _will_ want to know OTOH, the first
1148 * X-CACHE-MISS entry should tell us who.
1150 httpHeaderPutStrf(&rep
->header
, Http::HdrType::X_SQUID_ERROR
, "%s %d", name
, xerrno
);
1154 * If error page auto-negotiate is enabled in any way, send the Vary.
1155 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1156 * We have even better reasons though:
1157 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1159 if (!Config
.errorDirectory
) {
1160 /* We 'negotiated' this ONLY from the Accept-Language. */
1161 rep
->header
.delById(Http::HdrType::VARY
);
1162 rep
->header
.putStr(Http::HdrType::VARY
, "Accept-Language");
1165 /* add the Content-Language header according to RFC section 14.12 */
1167 rep
->header
.putStr(Http::HdrType::CONTENT_LANGUAGE
, err_language
);
1169 #endif /* USE_ERROR_LOCALES */
1171 /* default templates are in English */
1172 /* language is known unless error_directory override used */
1173 if (!Config
.errorDirectory
)
1174 rep
->header
.putStr(Http::HdrType::CONTENT_LANGUAGE
, "en");
1177 rep
->body
.setMb(content
);
1178 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1181 // Make sure error codes get back to the client side for logging and
1184 int edc
= ERR_DETAIL_NONE
; // error detail code
1187 edc
= detail
->errorNo();
1194 request
->detailError(type
, edc
);
1201 ErrorState::BuildContent()
1203 const char *m
= NULL
;
1205 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
1208 ErrorPageFile
*localeTmpl
= NULL
;
1210 /** error_directory option in squid.conf overrides translations.
1211 * Custom errors are always found either in error_directory or the templates directory.
1212 * Otherwise locate the Accept-Language header
1214 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
) {
1215 if (err_language
&& err_language
!= Config
.errorDefaultLanguage
)
1216 safe_free(err_language
);
1218 localeTmpl
= new ErrorPageFile(err_type_str
[page_id
], static_cast<err_type
>(page_id
));
1219 if (localeTmpl
->loadFor(request
.getRaw())) {
1220 m
= localeTmpl
->text();
1221 assert(localeTmpl
->language());
1222 err_language
= xstrdup(localeTmpl
->language());
1225 #endif /* USE_ERR_LOCALES */
1228 * If client-specific error templates are not enabled or available.
1229 * fall back to the old style squid.conf settings.
1232 m
= error_text
[page_id
];
1234 if (!Config
.errorDirectory
)
1235 err_language
= Config
.errorDefaultLanguage
;
1237 debugs(4, 2, HERE
<< "No existing error page language negotiated for " << errorPageName(page_id
) << ". Using default error file.");
1240 MemBuf
*result
= ConvertText(m
, true);
1248 MemBuf
*ErrorState::ConvertText(const char *text
, bool allowRecursion
)
1250 MemBuf
*content
= new MemBuf
;
1252 const char *m
= text
;
1256 while ((p
= strchr(m
, '%'))) {
1257 content
->append(m
, p
- m
); /* copy */
1258 const char *t
= Convert(*++p
, false, allowRecursion
); /* convert */
1259 content
->appendf("%s", t
); /* copy */
1260 m
= p
+ 1; /* advance */
1264 content
->appendf("%s", m
); /* copy tail */
1266 content
->terminate();
1268 assert((size_t)content
->contentSize() == strlen(content
->content()));