2 * Copyright (C) 1996-2022 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 */
12 #include "AccessLogEntry.h"
14 #include "clients/forward.h"
15 #include "comm/Connection.h"
16 #include "comm/Write.h"
17 #include "error/Detail.h"
18 #include "error/SysErrorDetail.h"
19 #include "errorpage.h"
21 #include "format/Format.h"
23 #include "html_quote.h"
24 #include "HttpHeaderTools.h"
25 #include "HttpReply.h"
26 #include "HttpRequest.h"
28 #include "MemObject.h"
30 #include "sbuf/Stream.h"
31 #include "SquidConfig.h"
32 #include "SquidTime.h"
37 #include "auth/UserRequest.h"
40 #include "ssl/ErrorDetailManager.h"
44 \defgroup ErrorPageInternal Error Page Internals
47 \section ErrorPagesAbstract Abstract:
48 * These routines are used to generate error messages to be
49 * sent to clients. The error type is used to select between
50 * the various message formats. (formats are stored in the
51 * Config.errorDirectory)
54 #if !defined(DEFAULT_SQUID_ERROR_DIR)
55 /** Where to look for errors if config path fails.
56 \note Please use ./configure --datadir=/path instead of patching
58 #define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
61 /// \ingroup ErrorPageInternal
62 CBDATA_CLASS_INIT(ErrorState
);
64 const SBuf
ErrorState::LogformatMagic("@Squid{");
68 /// an error page created from admin-configurable metadata (e.g. deny_info)
69 class ErrorDynamicPageInfo
{
71 ErrorDynamicPageInfo(const int anId
, const char *aName
, const SBuf
&aCfgLocation
);
72 ~ErrorDynamicPageInfo() { xfree(page_name
); }
74 /// error_text[] index for response body (unused in redirection responses)
77 /// Primary deny_info parameter:
78 /// * May start with an HTTP status code.
79 /// * Either a well-known error page name, a filename, or a redirect URL.
82 /// admin-configured HTTP Location header value for redirection responses
85 /// admin-configured name for the error page template (custom or standard)
88 /// deny_info directive position in squid.conf (for reporting)
91 // XXX: Misnamed. Not just for redirects.
92 /// admin-configured HTTP status code
93 Http::StatusCode page_redirect
;
96 // no copying of any kind
97 ErrorDynamicPageInfo(ErrorDynamicPageInfo
&&) = delete;
100 namespace ErrorPage
{
102 /// state and parameters shared by several ErrorState::compile*() methods
106 SBuf output
; ///< compilation result
107 const char *input
= nullptr; ///< template bytes that need to be compiled
108 bool building_deny_info_url
= false; ///< whether we compile deny_info URI
109 bool allowRecursion
= false; ///< whether top-level compile() calls are OK
112 /// pretty-prints error page/deny_info building error
113 class BuildErrorPrinter
116 BuildErrorPrinter(const SBuf
&anInputLocation
, int aPage
, const char *aMsg
, const char *aNear
): inputLocation(anInputLocation
), page_id(aPage
), msg(aMsg
), near(aNear
) {}
118 /// reports error details (for admin-visible exceptions and debugging)
119 std::ostream
&print(std::ostream
&) const;
121 /// print() helper to report where the error was found
122 std::ostream
&printLocation(std::ostream
&os
) const;
124 /* saved constructor parameters */
125 const SBuf
&inputLocation
;
131 static inline std::ostream
&
132 operator <<(std::ostream
&os
, const BuildErrorPrinter
&context
)
134 return context
.print(os
);
137 static const char *IsDenyInfoUri(const int page_id
);
139 static void ImportStaticErrorText(const int page_id
, const char *text
, const SBuf
&inputLocation
);
140 static void ValidateStaticError(const int page_id
, const SBuf
&inputLocation
);
142 } // namespace ErrorPage
144 /* local constant and vars */
147 \ingroup ErrorPageInternal
149 \note hard coded error messages are not appended with %S
150 * automagically to give you more control on the format
152 static const struct {
153 int type
; /* and page_id */
157 error_hard_text
[] = {
163 "<div id=\"footer\">\n"
164 "Generated %T by %h (%s)\n"
174 "unexpected client disconnect"
177 ERR_SECURE_ACCEPT_FAIL
,
181 ERR_REQUEST_START_TIMEOUT
,
182 "request start timedout"
190 /// \ingroup ErrorPageInternal
191 static std::vector
<ErrorDynamicPageInfo
*> ErrorDynamicPages
;
193 /* local prototypes */
195 /// \ingroup ErrorPageInternal
196 static const int error_hard_text_count
= sizeof(error_hard_text
) / sizeof(*error_hard_text
);
198 /// \ingroup ErrorPageInternal
199 static char **error_text
= NULL
;
201 /// \ingroup ErrorPageInternal
202 static int error_page_count
= 0;
204 /// \ingroup ErrorPageInternal
205 static MemBuf error_stylesheet
;
207 static const char *errorFindHardText(err_type type
);
208 static IOCB errorSendComplete
;
210 /// \ingroup ErrorPageInternal
211 /// manages an error page template
212 class ErrorPageFile
: public TemplateFile
215 ErrorPageFile(const char *name
, const err_type code
) : TemplateFile(name
, code
) {}
217 /// The template text data read from disk
218 const char *text() { return template_
.c_str(); }
221 virtual void setDefault() override
{
222 template_
= "Internal Error: Missing Template ";
223 template_
.append(templateName
.termedBuf());
227 /// \ingroup ErrorPageInternal
229 operator++ (err_type
&anErr
)
231 int tmp
= (int)anErr
;
232 anErr
= (err_type
)(++tmp
);
236 /// \ingroup ErrorPageInternal
238 operator -(err_type
const &anErr
, err_type
const &anErr2
)
240 return (int)anErr
- (int)anErr2
;
243 /// \return deny_info URL if the given page is a deny_info page with a URL
244 /// \return nullptr otherwise
246 ErrorPage::IsDenyInfoUri(const int page_id
)
248 if (ERR_MAX
<= page_id
&& page_id
< error_page_count
)
249 return ErrorDynamicPages
.at(page_id
- ERR_MAX
)->uri
; // may be nil
254 errorInitialize(void)
256 using ErrorPage::ImportStaticErrorText
;
260 error_page_count
= ERR_MAX
+ ErrorDynamicPages
.size();
261 error_text
= static_cast<char **>(xcalloc(error_page_count
, sizeof(char *)));
263 for (i
= ERR_NONE
, ++i
; i
< error_page_count
; ++i
) {
264 safe_free(error_text
[i
]);
266 if ((text
= errorFindHardText(i
))) {
268 * Index any hard-coded error text into defaults.
270 static const SBuf
builtIn("built-in");
271 ImportStaticErrorText(i
, text
, builtIn
);
273 } else if (i
< ERR_MAX
) {
275 * Index precompiled fixed template files from one of two sources:
276 * (a) default language translation directory (error_default_language)
277 * (b) admin specified custom directory (error_directory)
279 ErrorPageFile
errTmpl(err_type_str
[i
], i
);
280 errTmpl
.loadDefault();
281 ImportStaticErrorText(i
, errTmpl
.text(), errTmpl
.filename
);
284 * Index any unknown file names used by deny_info.
286 ErrorDynamicPageInfo
*info
= ErrorDynamicPages
.at(i
- ERR_MAX
);
287 assert(info
&& info
->id
== i
&& info
->page_name
);
289 if (info
->filename
) {
290 /** But only if they are not redirection URL. */
291 ErrorPageFile
errTmpl(info
->filename
, ERR_MAX
);
292 errTmpl
.loadDefault();
293 ImportStaticErrorText(i
, errTmpl
.text(), errTmpl
.filename
);
296 ErrorPage::ValidateStaticError(i
, info
->cfgLocation
);
301 error_stylesheet
.reset();
303 // look for and load stylesheet into global MemBuf for it.
304 if (Config
.errorStylesheet
) {
305 ErrorPageFile
tmpl("StylesSheet", ERR_MAX
);
306 tmpl
.loadFromFile(Config
.errorStylesheet
);
307 error_stylesheet
.appendf("%s",tmpl
.text());
311 Ssl::errorDetailInitialize();
321 for (i
= ERR_NONE
+ 1; i
< error_page_count
; ++i
)
322 safe_free(error_text
[i
]);
324 safe_free(error_text
);
327 while (!ErrorDynamicPages
.empty()) {
328 delete ErrorDynamicPages
.back();
329 ErrorDynamicPages
.pop_back();
332 error_page_count
= 0;
335 Ssl::errorDetailClean();
339 /// \ingroup ErrorPageInternal
341 errorFindHardText(err_type type
)
345 for (i
= 0; i
< error_hard_text_count
; ++i
)
346 if (error_hard_text
[i
].type
== type
)
347 return error_hard_text
[i
].text
;
352 TemplateFile::TemplateFile(const char *name
, const err_type code
): silent(false), wasLoaded(false), templateName(name
), templateCode(code
)
358 TemplateFile::loadDefault()
360 if (loaded()) // already loaded?
363 /** test error_directory configured location */
364 if (Config
.errorDirectory
) {
365 char path
[MAXPATHLEN
];
366 snprintf(path
, sizeof(path
), "%s/%s", Config
.errorDirectory
, templateName
.termedBuf());
371 /** test error_default_language location */
372 if (!loaded() && Config
.errorDefaultLanguage
) {
373 if (!tryLoadTemplate(Config
.errorDefaultLanguage
)) {
374 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "ERROR: Unable to load default error language files. Reset to backups.");
379 /* test default location if failed (templates == English translation base templates) */
381 tryLoadTemplate("templates");
384 /* giving up if failed */
386 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "WARNING: failed to find or read error text file " << templateName
);
394 TemplateFile::tryLoadTemplate(const char *lang
)
398 char path
[MAXPATHLEN
];
399 /* TODO: prep the directory path string to prevent snprintf ... */
400 snprintf(path
, sizeof(path
), "%s/%s/%s",
401 DEFAULT_SQUID_ERROR_DIR
, lang
, templateName
.termedBuf());
402 path
[MAXPATHLEN
-1] = '\0';
404 if (loadFromFile(path
))
408 if ( strlen(lang
) == 2) {
409 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
410 /* use first result. */
411 debugs(4,2, "wildcard fallback errors not coded yet.");
419 TemplateFile::loadFromFile(const char *path
)
425 if (loaded()) // already loaded?
428 fd
= file_open(path
, O_RDONLY
| O_TEXT
);
431 /* with dynamic locale negotiation we may see some failures before a success. */
432 if (!silent
&& templateCode
< TCP_RESET
) {
434 debugs(4, DBG_CRITICAL
, "ERROR: loading file '" << path
<< "': " << xstrerr(xerrno
));
441 while ((len
= FD_READ_METHOD(fd
, buf
, sizeof(buf
))) > 0) {
442 template_
.append(buf
, len
);
448 debugs(4, DBG_CRITICAL
, MYNAME
<< "ERROR: failed to fully read: '" << path
<< "': " << xstrerr(xerrno
));
455 filename
= SBuf(path
);
458 debugs(4, DBG_CRITICAL
, "ERROR: parsing error in template file: " << path
);
467 bool strHdrAcptLangGetItem(const String
&hdr
, char *lang
, int langLen
, size_t &pos
)
469 while (pos
< hdr
.size()) {
471 /* skip any initial whitespace. */
472 while (pos
< hdr
.size() && xisspace(hdr
[pos
]))
476 * Header value format:
477 * - sequence of whitespace delimited tags
478 * - each tag may suffix with ';'.* which we can ignore.
479 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
480 * with preference given to an exact match.
482 bool invalid_byte
= false;
484 while (pos
< hdr
.size() && hdr
[pos
] != ';' && hdr
[pos
] != ',' && !xisspace(hdr
[pos
]) && dt
< (lang
+ (langLen
-1)) ) {
486 #if USE_HTTP_VIOLATIONS
487 // if accepting violations we may as well accept some broken browsers
488 // which may send us the right code, wrong ISO formatting.
493 *dt
= xtolower(hdr
[pos
]);
494 // valid codes only contain A-Z, hyphen (-) and *
495 if (*dt
!= '-' && *dt
!= '*' && (*dt
< 'a' || *dt
> 'z') )
498 ++dt
; // move to next destination byte.
502 *dt
= '\0'; // nul-terminated the filename content string before system use.
504 // if we terminated the tag on garbage or ';' we need to skip to the next ',' or end of header.
505 while (pos
< hdr
.size() && hdr
[pos
] != ',')
508 if (pos
< hdr
.size() && hdr
[pos
] == ',')
511 debugs(4, 9, "STATE: lang=" << lang
<< ", pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
513 /* if we found anything we might use, try it. */
514 if (*lang
!= '\0' && !invalid_byte
)
521 TemplateFile::loadFor(const HttpRequest
*request
)
526 if (loaded()) // already loaded?
529 if (!request
|| !request
->header
.getList(Http::HdrType::ACCEPT_LANGUAGE
, &hdr
))
533 size_t pos
= 0; // current parsing position in header string
535 debugs(4, 6, "Testing Header: '" << hdr
<< "'");
537 while ( strHdrAcptLangGetItem(hdr
, lang
, 256, pos
) ) {
539 /* wildcard uses the configured default language */
540 if (lang
[0] == '*' && lang
[1] == '\0') {
541 debugs(4, 6, "Found language '" << lang
<< "'. Using configured default.");
545 debugs(4, 6, "Found language '" << lang
<< "', testing for available template");
547 if (tryLoadTemplate(lang
)) {
548 /* store the language we found for the Content-Language reply header */
551 } else if (Config
.errorLogMissingLanguages
) {
552 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << lang
);
562 ErrorDynamicPageInfo::ErrorDynamicPageInfo(const int anId
, const char *aName
, const SBuf
&aCfgLocation
):
564 page_name(xstrdup(aName
)),
567 cfgLocation(aCfgLocation
),
568 page_redirect(static_cast<Http::StatusCode
>(atoi(page_name
)))
570 const char *filenameOrUri
= nullptr;
571 if (xisdigit(*page_name
)) {
572 if (const char *statusCodeEnd
= strchr(page_name
, ':'))
573 filenameOrUri
= statusCodeEnd
+ 1;
575 assert(!page_redirect
);
576 filenameOrUri
= page_name
;
579 // Guessed uri, filename, or both values may be nil or malformed.
580 // They are validated later.
581 if (!page_redirect
) {
582 if (filenameOrUri
&& strchr(filenameOrUri
, ':')) // looks like a URL
585 filename
= filenameOrUri
;
587 else if (page_redirect
/100 == 3) {
588 // redirects imply a URL
591 // non-redirects imply an error page name
592 filename
= filenameOrUri
;
595 const auto info
= this; // source code change reduction hack
596 // TODO: Move and refactor to avoid self_destruct()s in reconfigure.
598 /* WARNING on redirection status:
599 * 2xx are permitted, but not documented officially.
600 * - might be useful for serving static files (PAC etc) in special cases
601 * 3xx require a URL suitable for Location: header.
602 * - the current design does not allow for a Location: URI as well as a local file template
603 * although this possibility is explicitly permitted in the specs.
604 * 4xx-5xx require a local file template.
605 * - sending Location: on these codes with no body is invalid by the specs.
606 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
607 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
609 if (info
->page_redirect
== Http::scNone
)
610 ; // special case okay.
611 else if (info
->page_redirect
< 200 || info
->page_redirect
> 599) {
613 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
615 } else if ( /* >= 200 && */ info
->page_redirect
< 300 && strchr(&(page_name
[4]), ':')) {
616 // 2xx require a local template file
617 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
619 } else if (info
->page_redirect
>= 300 && info
->page_redirect
<= 399 && !strchr(&(page_name
[4]), ':')) {
620 // 3xx require an absolute URL
621 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a URL on '" << page_name
<< "'");
623 } else if (info
->page_redirect
>= 400 /* && <= 599 */ && strchr(&(page_name
[4]), ':')) {
624 // 4xx/5xx require a local template file
625 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
631 /// \ingroup ErrorPageInternal
633 errorPageId(const char *page_name
)
635 for (int i
= 0; i
< ERR_MAX
; ++i
) {
636 if (strcmp(err_type_str
[i
], page_name
) == 0)
640 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); ++j
) {
641 if (strcmp(ErrorDynamicPages
[j
]->page_name
, page_name
) == 0)
649 errorReservePageId(const char *page_name
, const SBuf
&cfgLocation
)
651 int id
= errorPageId(page_name
);
653 if (id
== ERR_NONE
) {
654 id
= ERR_MAX
+ ErrorDynamicPages
.size();
655 const auto info
= new ErrorDynamicPageInfo(id
, page_name
, cfgLocation
);
656 ErrorDynamicPages
.push_back(info
);
662 /// \ingroup ErrorPageInternal
664 errorPageName(int pageId
)
666 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
667 return err_type_str
[pageId
];
669 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
670 return ErrorDynamicPages
[pageId
- ERR_MAX
]->page_name
;
672 return "ERR_UNKNOWN"; /* should not happen */
676 ErrorState::NewForwarding(err_type type
, HttpRequestPointer
&request
, const AccessLogEntry::Pointer
&ale
)
678 const Http::StatusCode status
= (request
&& request
->flags
.needValidation
) ?
679 Http::scGatewayTimeout
: Http::scServiceUnavailable
;
680 return new ErrorState(type
, status
, request
.getRaw(), ale
);
683 ErrorState::ErrorState(err_type t
) :
690 ErrorState::ErrorState(err_type t
, Http::StatusCode status
, HttpRequest
* req
, const AccessLogEntry::Pointer
&anAle
) :
693 if (page_id
>= ERR_MAX
&& ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
!= Http::scNone
)
694 httpStatus
= ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
;
700 src_addr
= req
->client_addr
;
706 ErrorState::ErrorState(HttpRequest
* req
, HttpReply
*errorReply
) :
707 ErrorState(ERR_RELAY_REMOTE
)
710 response_
= errorReply
;
711 httpStatus
= errorReply
->sline
.status();
715 src_addr
= req
->client_addr
;
720 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
722 assert(entry
->mem_obj
!= NULL
);
723 assert (entry
->isEmpty());
724 debugs(4, 4, "storing " << err
<< " in " << *entry
);
726 if (entry
->store_status
!= STORE_PENDING
) {
727 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
729 * If the entry is not STORE_PENDING, then no clients
730 * care about it, and we don't need to generate an
733 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
734 assert(entry
->mem_obj
->nclients
== 0);
739 if (err
->page_id
== TCP_RESET
) {
741 debugs(4, 2, "RSTing this reply");
742 err
->request
->flags
.resetTcp
= true;
746 entry
->storeErrorResponse(err
->BuildHttpReply());
751 errorSend(const Comm::ConnectionPointer
&conn
, ErrorState
* err
)
753 debugs(4, 3, conn
<< ", err=" << err
);
754 assert(Comm::IsConnOpen(conn
));
756 HttpReplyPointer
rep(err
->BuildHttpReply());
758 MemBuf
*mb
= rep
->pack();
759 AsyncCall::Pointer call
= commCbCall(78, 5, "errorSendComplete",
760 CommIoCbPtrFun(&errorSendComplete
, err
));
761 Comm::Write(conn
, mb
, call
);
766 \ingroup ErrorPageAPI
768 * Called by commHandleWrite() after data has been written
769 * to the client socket.
771 \note If there is a callback, the callback is responsible for
772 * closing the FD, otherwise we do it ourselves.
775 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *, size_t size
, Comm::Flag errflag
, int, void *data
)
777 ErrorState
*err
= static_cast<ErrorState
*>(data
);
778 debugs(4, 3, conn
<< ", size=" << size
);
780 if (errflag
!= Comm::ERR_CLOSING
) {
782 debugs(4, 3, "errorSendComplete: callback");
783 err
->callback(conn
->fd
, err
->callback_data
, size
);
785 debugs(4, 3, "errorSendComplete: comm_close");
793 ErrorState::~ErrorState()
795 safe_free(redirect_url
);
797 safe_free(request_hdrs
);
798 wordlistDestroy(&ftp
.server_msg
);
799 safe_free(ftp
.request
);
800 safe_free(ftp
.reply
);
803 if (err_language
!= Config
.errorDefaultLanguage
)
805 safe_free(err_language
);
809 ErrorState::Dump(MemBuf
* mb
)
812 char ntoabuf
[MAX_IPSTRLEN
];
815 /* email subject line */
816 str
.appendf("CacheErrorInfo - %s", errorPageName(type
));
817 mb
->appendf("?subject=%s", rfc1738_escape_part(str
.buf
));
820 str
.appendf("CacheHost: %s\r\n", getMyHostname());
822 str
.appendf("ErrPage: %s\r\n", errorPageName(type
));
825 str
.appendf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
827 str
.append("Err: [none]\r\n", 13);
830 if (auth_user_request
.getRaw() && auth_user_request
->denyMessage())
831 str
.appendf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
833 if (dnsError
.size() > 0)
834 str
.appendf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
837 str
.appendf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
840 str
.appendf("ClientIP: %s\r\n", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
842 if (request
&& request
->hier
.host
[0] != '\0') {
843 str
.appendf("ServerIP: %s\r\n", request
->hier
.host
);
846 str
.append("\r\n", 2);
848 str
.append("HTTP Request:\r\n", 15);
850 str
.appendf(SQUIDSBUFPH
" " SQUIDSBUFPH
" %s/%d.%d\n",
851 SQUIDSBUFPRINT(request
->method
.image()),
852 SQUIDSBUFPRINT(request
->url
.path()),
853 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
854 request
->http_ver
.major
, request
->http_ver
.minor
);
855 request
->header
.packInto(&str
);
858 str
.append("\r\n", 2);
862 str
.appendf("FTP Request: %s\r\n", ftp
.request
);
863 str
.appendf("FTP Reply: %s\r\n", (ftp
.reply
? ftp
.reply
:"[none]"));
864 str
.append("FTP Msg: ", 9);
865 wordlistCat(ftp
.server_msg
, &str
);
866 str
.append("\r\n", 2);
869 str
.append("\r\n", 2);
870 mb
->appendf("&body=%s", rfc1738_escape_part(str
.buf
));
875 /// \ingroup ErrorPageInternal
876 #define CVT_BUF_SZ 512
879 ErrorState::compileLogformatCode(Build
&build
)
881 assert(LogformatMagic
.cmp(build
.input
, LogformatMagic
.length()) == 0);
884 const auto logformat
= build
.input
+ LogformatMagic
.length();
886 // Logformat supports undocumented "external" encoding specifications
887 // like [%>h] or "%<a". To preserve the possibility of extending
888 // @Squid{} syntax to non-logformat sequences, we require logformat
889 // sequences to start with '%'. This restriction does not limit
890 // logformat quoting abilities. TODO: Deprecate "external" encoding?
891 if (*logformat
!= '%')
892 throw TexcHere("logformat expressions that do not start with % are not supported");
894 static MemBuf result
;
896 const auto logformatLen
= Format::AssembleOne(logformat
, result
, ale
);
897 assert(logformatLen
> 0);
898 const auto closure
= logformat
+ logformatLen
;
900 throw TexcHere("Missing closing brace (})");
901 build
.output
.append(result
.content(), result
.contentSize());
902 build
.input
= closure
+ 1;
905 noteBuildError("Bad @Squid{logformat} sequence", build
.input
);
908 // we cannot recover reliably so stop interpreting the rest of input
909 const auto remainingSize
= strlen(build
.input
);
910 build
.output
.append(build
.input
, remainingSize
);
911 build
.input
+= remainingSize
;
915 ErrorState::compileLegacyCode(Build
&build
)
918 const char *p
= NULL
; /* takes priority over mb if set */
920 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
921 char ntoabuf
[MAX_IPSTRLEN
];
925 const auto &building_deny_info_url
= build
.building_deny_info_url
; // a change reduction hack
927 const auto letter
= build
.input
[1];
933 if (request
&& request
->auth_user_request
)
934 p
= request
->auth_user_request
->username();
941 // TODO: When/if we get ALE here, pass it as well
942 if (const auto addr
= FindListeningPortAddress(request
.getRaw(), nullptr))
943 mb
.appendf("%s", addr
->toStr(ntoabuf
, MAX_IPSTRLEN
));
949 mb
.appendf("%u", getMyPort());
953 if (building_deny_info_url
) break;
955 const SBuf
&tmp
= Ftp::UrlWith2f(request
.getRaw());
956 mb
.append(tmp
.rawContent(), tmp
.length());
962 if (building_deny_info_url
) break;
963 p
= errorPageName(type
);
967 if (!build
.allowRecursion
)
968 p
= "%D"; // if recursion is not allowed, do not convert
970 auto rawDetail
= detail
->verbose(request
);
971 // XXX: Performance regression. c_str() reallocates
972 const auto compiledDetail
= compileBody(rawDetail
.c_str(), false);
973 mb
.append(compiledDetail
.rawContent(), compiledDetail
.length());
976 if (!mb
.contentSize())
977 mb
.append("[No Error Detail]", 17);
981 mb
.appendf("%d", xerrno
);
986 mb
.appendf("(%d) %s", xerrno
, strerror(xerrno
));
988 mb
.append("[No Error]", 10);
992 if (building_deny_info_url
) break;
993 /* FTP REQUEST LINE */
1001 if (building_deny_info_url
) break;
1002 /* FTP REPLY LINE */
1010 if (building_deny_info_url
) break;
1011 /* FTP SERVER RESPONSE */
1013 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
1015 } else if (ftp
.server_msg
) {
1016 wordlistCat(ftp
.server_msg
, &mb
);
1021 mb
.appendf("%s", getMyHostname());
1026 if (request
->hier
.host
[0] != '\0') // if non-empty string.
1027 p
= request
->hier
.host
;
1029 p
= request
->url
.host();
1030 } else if (!building_deny_info_url
)
1031 p
= "[unknown host]";
1035 mb
.appendf("%s", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
1039 if (request
&& request
->hier
.tcpServer
)
1040 p
= request
->hier
.tcpServer
->remote
.toStr(ntoabuf
,MAX_IPSTRLEN
);
1041 else if (!building_deny_info_url
)
1046 if (building_deny_info_url
) break;
1047 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
1052 if (building_deny_info_url
) break;
1053 if (Config
.errHtmlText
) {
1054 mb
.appendf("%s", Config
.errHtmlText
);
1057 p
= "[not available]";
1061 if (building_deny_info_url
) break;
1063 if (auth_user_request
.getRaw())
1064 p
= auth_user_request
->denyMessage("[not available]");
1066 p
= "[not available]";
1074 const SBuf
&m
= request
->method
.image();
1075 mb
.append(m
.rawContent(), m
.length());
1076 } else if (!building_deny_info_url
)
1077 p
= "[unknown method]";
1081 if (!building_deny_info_url
)
1083 /* [[fallthrough]] */
1085 p
= request
? request
->extacl_message
.termedBuf() : external_acl_message
;
1086 if (!p
&& !building_deny_info_url
)
1087 p
= "[not available]";
1092 mb
.appendf("%u", request
->url
.port());
1093 } else if (!building_deny_info_url
) {
1094 p
= "[unknown port]";
1100 const SBuf
&m
= request
->url
.getScheme().image();
1101 mb
.append(m
.rawContent(), m
.length());
1102 } else if (!building_deny_info_url
) {
1103 p
= "[unknown protocol]";
1108 if (building_deny_info_url
) {
1109 if (request
!= NULL
) {
1110 const SBuf
&tmp
= request
->url
.path();
1111 mb
.append(tmp
.rawContent(), tmp
.length());
1118 mb
.appendf(SQUIDSBUFPH
" " SQUIDSBUFPH
" %s/%d.%d\n",
1119 SQUIDSBUFPRINT(request
->method
.image()),
1120 SQUIDSBUFPRINT(request
->url
.path()),
1121 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
1122 request
->http_ver
.major
, request
->http_ver
.minor
);
1123 request
->header
.packInto(&mb
, true); //hide authorization data
1124 } else if (request_hdrs
) {
1132 /* for backward compat we make %s show the full URL. Drop this in some future release. */
1133 if (building_deny_info_url
) {
1135 const SBuf
&tmp
= request
->effectiveRequestUri();
1136 mb
.append(tmp
.rawContent(), tmp
.length());
1139 debugs(0, DBG_CRITICAL
, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
1141 p
= visible_appname_string
;
1145 if (building_deny_info_url
) {
1146 p
= visible_appname_string
;
1149 /* signature may contain %-escapes, recursion */
1150 if (page_id
!= ERR_SQUID_SIGNATURE
) {
1151 const int saved_id
= page_id
;
1152 page_id
= ERR_SQUID_SIGNATURE
;
1153 const auto signature
= buildBody();
1154 mb
.append(signature
.rawContent(), signature
.length());
1158 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1164 mb
.appendf("%s", Time::FormatHttpd(squid_curtime
));
1168 mb
.appendf("%s", mkrfc1123(squid_curtime
));
1172 /* Using the fake-https version of absolute-URI so error pages see https:// */
1173 /* even when the url-path cannot be shown as more than '*' */
1175 p
= urlCanonicalFakeHttps(request
.getRaw());
1178 else if (!building_deny_info_url
)
1184 const SBuf
&tmp
= request
->effectiveRequestUri();
1185 mb
.append(tmp
.rawContent(), tmp
.length());
1188 else if (!building_deny_info_url
)
1193 if (Config
.adminEmail
)
1194 mb
.appendf("%s", Config
.adminEmail
);
1195 else if (!building_deny_info_url
)
1200 if (building_deny_info_url
) break;
1201 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
1208 const auto brief
= detail
->brief();
1209 mb
.append(brief
.rawContent(), brief
.length());
1210 } else if (!building_deny_info_url
) {
1211 p
= "[Unknown Error Code]";
1216 if (building_deny_info_url
) break;
1217 if (dnsError
.size() > 0)
1218 p
= dnsError
.termedBuf();
1219 else if (ftp
.cwd_msg
)
1226 if (building_deny_info_url
) break;
1238 if (building_deny_info_url
)
1239 bypassBuildErrorXXX("Unsupported deny_info %code", build
.input
);
1240 else if (letter
!= ';')
1241 bypassBuildErrorXXX("Unsupported error page %code", build
.input
);
1242 // else too many "font-size: 100%;" template errors to report
1244 mb
.append(build
.input
, 2);
1250 p
= mb
.buf
; /* do not use mb after this assignment! */
1254 debugs(4, 3, "%" << letter
<< " --> '" << p
<< "'" );
1259 if (building_deny_info_url
&& !no_urlescape
)
1260 p
= rfc1738_escape_part(p
);
1262 // TODO: Optimize by replacing mb with direct build.output usage.
1263 build
.output
.append(p
, strlen(p
));
1268 ErrorState::validate()
1270 if (const auto urlTemplate
= ErrorPage::IsDenyInfoUri(page_id
)) {
1271 (void)compile(urlTemplate
, true, true);
1273 assert(page_id
> ERR_NONE
);
1274 assert(page_id
< error_page_count
);
1275 (void)compileBody(error_text
[page_id
], true);
1280 ErrorState::BuildHttpReply()
1283 return response_
.getRaw();
1285 HttpReply
*rep
= new HttpReply
;
1286 const char *name
= errorPageName(page_id
);
1287 /* no LMT for error pages; error pages expire immediately */
1289 if (const auto urlTemplate
= ErrorPage::IsDenyInfoUri(page_id
)) {
1291 Http::StatusCode status
= Http::scFound
;
1292 // Use configured 3xx reply status if set.
1294 status
= httpStatus
;
1296 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1297 if (request
&& request
->method
!= Http::METHOD_GET
&& request
->method
!= Http::METHOD_HEAD
&& request
->http_ver
>= Http::ProtocolVersion(1,1))
1298 status
= Http::scTemporaryRedirect
;
1301 rep
->setHeaders(status
, NULL
, "text/html;charset=utf-8", 0, 0, -1);
1304 auto location
= compile(urlTemplate
, true, true);
1305 rep
->header
.putStr(Http::HdrType::LOCATION
, location
.c_str());
1308 httpHeaderPutStrf(&rep
->header
, Http::HdrType::X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
1310 const auto body
= buildBody();
1311 rep
->setHeaders(httpStatus
, NULL
, "text/html;charset=utf-8", body
.length(), 0, -1);
1313 * include some information for downstream caches. Implicit
1314 * replaceable content. This isn't quite sufficient. xerrno is not
1315 * necessarily meaningful to another system, so we really should
1316 * expand it. Additionally, we should identify ourselves. Someone
1317 * might want to know. Someone _will_ want to know OTOH, the first
1318 * X-CACHE-MISS entry should tell us who.
1320 httpHeaderPutStrf(&rep
->header
, Http::HdrType::X_SQUID_ERROR
, "%s %d", name
, xerrno
);
1324 * If error page auto-negotiate is enabled in any way, send the Vary.
1325 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1326 * We have even better reasons though:
1327 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1329 if (!Config
.errorDirectory
) {
1330 /* We 'negotiated' this ONLY from the Accept-Language. */
1331 rep
->header
.delById(Http::HdrType::VARY
);
1332 rep
->header
.putStr(Http::HdrType::VARY
, "Accept-Language");
1335 /* add the Content-Language header according to RFC section 14.12 */
1337 rep
->header
.putStr(Http::HdrType::CONTENT_LANGUAGE
, err_language
);
1339 #endif /* USE_ERROR_LOCALES */
1341 /* default templates are in English */
1342 /* language is known unless error_directory override used */
1343 if (!Config
.errorDirectory
)
1344 rep
->header
.putStr(Http::HdrType::CONTENT_LANGUAGE
, "en");
1347 rep
->body
.set(body
);
1350 // Make sure error codes get back to the client side for logging and
1354 request
->detailError(type
, detail
);
1356 request
->detailError(type
, SysErrorDetail::NewIfAny(xerrno
));
1363 ErrorState::buildBody()
1365 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
1368 /** error_directory option in squid.conf overrides translations.
1369 * Custom errors are always found either in error_directory or the templates directory.
1370 * Otherwise locate the Accept-Language header
1372 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
) {
1373 if (err_language
&& err_language
!= Config
.errorDefaultLanguage
)
1374 safe_free(err_language
);
1376 ErrorPageFile
localeTmpl(err_type_str
[page_id
], static_cast<err_type
>(page_id
));
1377 if (localeTmpl
.loadFor(request
.getRaw())) {
1378 inputLocation
= localeTmpl
.filename
;
1379 assert(localeTmpl
.language());
1380 err_language
= xstrdup(localeTmpl
.language());
1381 return compileBody(localeTmpl
.text(), true);
1384 #endif /* USE_ERR_LOCALES */
1387 * If client-specific error templates are not enabled or available.
1388 * fall back to the old style squid.conf settings.
1391 if (!Config
.errorDirectory
)
1392 err_language
= Config
.errorDefaultLanguage
;
1394 debugs(4, 2, "No existing error page language negotiated for " << this << ". Using default error file.");
1395 return compileBody(error_text
[page_id
], true);
1399 ErrorState::compileBody(const char *input
, bool allowRecursion
)
1401 return compile(input
, false, allowRecursion
);
1405 ErrorState::compile(const char *input
, bool building_deny_info_url
, bool allowRecursion
)
1410 build
.building_deny_info_url
= building_deny_info_url
;
1411 build
.allowRecursion
= allowRecursion
;
1412 build
.input
= input
;
1414 auto blockStart
= build
.input
;
1415 while (const auto letter
= *build
.input
) {
1416 if (letter
== '%') {
1417 build
.output
.append(blockStart
, build
.input
- blockStart
);
1418 compileLegacyCode(build
);
1419 blockStart
= build
.input
;
1421 else if (letter
== '@' && LogformatMagic
.cmp(build
.input
, LogformatMagic
.length()) == 0) {
1422 build
.output
.append(blockStart
, build
.input
- blockStart
);
1423 compileLogformatCode(build
);
1424 blockStart
= build
.input
;
1429 build
.output
.append(blockStart
, build
.input
- blockStart
);
1430 return build
.output
;
1433 /// react to a compile() error
1434 /// \param msg description of what went wrong
1435 /// \param near approximate start of the problematic input
1436 /// \param forceBypass whether detection of this error was introduced late,
1437 /// after old configurations containing this error could have been
1438 /// successfully validated and deployed (i.e. the admin may not be
1439 /// able to fix this newly detected but old problem quickly)
1441 ErrorState::noteBuildError_(const char *msg
, const char *near
, const bool forceBypass
)
1443 using ErrorPage::BuildErrorPrinter
;
1444 const auto runtime
= !starting_up
;
1445 if (runtime
|| forceBypass
) {
1446 // swallow this problem because the admin may not be (and/or the page
1447 // building code is not) ready to handle throwing consequences
1449 static unsigned int seenErrors
= 0;
1452 const auto debugLevel
=
1453 (seenErrors
> 100) ? DBG_DATA
:
1454 (starting_up
|| reconfiguring
) ? DBG_CRITICAL
:
1455 3; // most other errors have been reported as configuration errors
1457 // Error fatality depends on the error context: Reconfiguration errors
1458 // are, like startup ones, DBG_CRITICAL but will never become FATAL.
1459 if (starting_up
&& seenErrors
<= 10)
1460 debugs(4, debugLevel
, "WARNING: The following configuration error will be fatal in future Squid versions");
1462 debugs(4, debugLevel
, "ERROR: " << BuildErrorPrinter(inputLocation
, page_id
, msg
, near
));
1464 throw TexcHere(ToSBuf(BuildErrorPrinter(inputLocation
, page_id
, msg
, near
)));
1468 /* ErrorPage::BuildErrorPrinter */
1471 ErrorPage::BuildErrorPrinter::printLocation(std::ostream
&os
) const {
1472 if (!inputLocation
.isEmpty())
1473 return os
<< inputLocation
;
1475 if (page_id
< ERR_NONE
|| page_id
>= error_page_count
)
1476 return os
<< "[error page " << page_id
<< "]"; // should not happen
1478 if (page_id
< ERR_MAX
)
1479 return os
<< err_type_str
[page_id
];
1481 return os
<< "deny_info " << ErrorDynamicPages
.at(page_id
- ERR_MAX
)->page_name
;
1485 ErrorPage::BuildErrorPrinter::print(std::ostream
&os
) const {
1486 printLocation(os
) << ": " << msg
<< " near ";
1488 // TODO: Add support for prefix printing to Raw
1489 const size_t maxContextLength
= 15; // plus "..."
1490 if (strlen(near
) > maxContextLength
) {
1491 os
.write(near
, maxContextLength
);
1497 // XXX: We should not be converting (inner) exception to text if we are
1498 // going to throw again. See "add arbitrary (re)thrower-supplied details"
1499 // TODO in TextException.h for a long-term in-catcher solution.
1500 if (std::current_exception())
1501 os
<< "\n additional info: " << CurrentException
;
1506 /// add error page template to the global index
1508 ErrorPage::ImportStaticErrorText(const int page_id
, const char *text
, const SBuf
&inputLocation
)
1510 assert(!error_text
[page_id
]);
1511 error_text
[page_id
] = xstrdup(text
);
1512 ValidateStaticError(page_id
, inputLocation
);
1515 /// validate static error page
1517 ErrorPage::ValidateStaticError(const int page_id
, const SBuf
&inputLocation
)
1519 // Supplying nil ALE pointer limits validation to logformat %code
1520 // recognition by Format::Token::parse(). This is probably desirable
1521 // because actual %code assembly is slow and should not affect validation
1522 // when our ALE cannot have any real data (this code is not associated
1523 // with any real transaction).
1524 ErrorState
anErr(err_type(page_id
), Http::scNone
, nullptr, nullptr);
1525 anErr
.inputLocation
= inputLocation
;
1530 operator <<(std::ostream
&os
, const ErrorState
*err
)
1533 os
<< errorPageName(err
->page_id
);