2 * Copyright (C) 1996-2020 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 "err_detail_type.h"
18 #include "errorpage.h"
20 #include "format/Format.h"
22 #include "html_quote.h"
23 #include "HttpHeaderTools.h"
24 #include "HttpReply.h"
25 #include "HttpRequest.h"
27 #include "MemObject.h"
29 #include "sbuf/Stream.h"
30 #include "SquidConfig.h"
31 #include "SquidTime.h"
36 #include "auth/UserRequest.h"
39 #include "ssl/ErrorDetailManager.h"
43 \defgroup ErrorPageInternal Error Page Internals
46 \section ErrorPagesAbstract Abstract:
47 * These routines are used to generate error messages to be
48 * sent to clients. The error type is used to select between
49 * the various message formats. (formats are stored in the
50 * Config.errorDirectory)
53 #if !defined(DEFAULT_SQUID_ERROR_DIR)
54 /** Where to look for errors if config path fails.
55 \note Please use ./configure --datadir=/path instead of patching
57 #define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
60 /// \ingroup ErrorPageInternal
61 CBDATA_CLASS_INIT(ErrorState
);
63 const SBuf
ErrorState::LogformatMagic("@Squid{");
67 /// an error page created from admin-configurable metadata (e.g. deny_info)
68 class ErrorDynamicPageInfo
{
70 ErrorDynamicPageInfo(const int anId
, const char *aName
, const SBuf
&aCfgLocation
);
71 ~ErrorDynamicPageInfo() { xfree(page_name
); }
73 /// error_text[] index for response body (unused in redirection responses)
76 /// Primary deny_info parameter:
77 /// * May start with an HTTP status code.
78 /// * Either a well-known error page name, a filename, or a redirect URL.
81 /// admin-configured HTTP Location header value for redirection responses
84 /// admin-configured name for the error page template (custom or standard)
87 /// deny_info directive position in squid.conf (for reporting)
90 // XXX: Misnamed. Not just for redirects.
91 /// admin-configured HTTP status code
92 Http::StatusCode page_redirect
;
95 // no copying of any kind
96 ErrorDynamicPageInfo(ErrorDynamicPageInfo
&&) = delete;
101 /// state and parameters shared by several ErrorState::compile*() methods
105 SBuf output
; ///< compilation result
106 const char *input
= nullptr; ///< template bytes that need to be compiled
107 bool building_deny_info_url
= false; ///< whether we compile deny_info URI
108 bool allowRecursion
= false; ///< whether top-level compile() calls are OK
111 /// pretty-prints error page/deny_info building error
112 class BuildErrorPrinter
115 BuildErrorPrinter(const SBuf
&anInputLocation
, int aPage
, const char *aMsg
, const char *aNear
): inputLocation(anInputLocation
), page_id(aPage
), msg(aMsg
), near(aNear
) {}
117 /// reports error details (for admin-visible exceptions and debugging)
118 std::ostream
&print(std::ostream
&) const;
120 /// print() helper to report where the error was found
121 std::ostream
&printLocation(std::ostream
&os
) const;
123 /* saved constructor parameters */
124 const SBuf
&inputLocation
;
130 static inline std::ostream
&
131 operator <<(std::ostream
&os
, const BuildErrorPrinter
&context
)
133 return context
.print(os
);
136 static const char *IsDenyInfoUri(const int page_id
);
138 static void ImportStaticErrorText(const int page_id
, const char *text
, const SBuf
&inputLocation
);
139 static void ValidateStaticError(const int page_id
, const SBuf
&inputLocation
);
141 } // namespace ErrorPage
143 /* local constant and vars */
146 \ingroup ErrorPageInternal
148 \note hard coded error messages are not appended with %S
149 * automagically to give you more control on the format
151 static const struct {
152 int type
; /* and page_id */
156 error_hard_text
[] = {
162 "<div id=\"footer\">\n"
163 "Generated %T by %h (%s)\n"
172 ERR_SECURE_ACCEPT_FAIL
,
176 ERR_REQUEST_START_TIMEOUT
,
177 "request start timedout"
185 /// \ingroup ErrorPageInternal
186 static std::vector
<ErrorDynamicPageInfo
*> ErrorDynamicPages
;
188 /* local prototypes */
190 /// \ingroup ErrorPageInternal
191 static const int error_hard_text_count
= sizeof(error_hard_text
) / sizeof(*error_hard_text
);
193 /// \ingroup ErrorPageInternal
194 static char **error_text
= NULL
;
196 /// \ingroup ErrorPageInternal
197 static int error_page_count
= 0;
199 /// \ingroup ErrorPageInternal
200 static MemBuf error_stylesheet
;
202 static const char *errorFindHardText(err_type type
);
203 static IOCB errorSendComplete
;
205 /// \ingroup ErrorPageInternal
206 /// manages an error page template
207 class ErrorPageFile
: public TemplateFile
210 ErrorPageFile(const char *name
, const err_type code
) : TemplateFile(name
, code
) {}
212 /// The template text data read from disk
213 const char *text() { return template_
.c_str(); }
216 virtual void setDefault() override
{
217 template_
= "Internal Error: Missing Template ";
218 template_
.append(templateName
.termedBuf());
222 /// \ingroup ErrorPageInternal
223 err_type
&operator++ (err_type
&anErr
)
225 int tmp
= (int)anErr
;
226 anErr
= (err_type
)(++tmp
);
230 /// \ingroup ErrorPageInternal
231 int operator - (err_type
const &anErr
, err_type
const &anErr2
)
233 return (int)anErr
- (int)anErr2
;
236 /// \return deny_info URL if the given page is a deny_info page with a URL
237 /// \return nullptr otherwise
239 ErrorPage::IsDenyInfoUri(const int page_id
)
241 if (ERR_MAX
<= page_id
&& page_id
< error_page_count
)
242 return ErrorDynamicPages
.at(page_id
- ERR_MAX
)->uri
; // may be nil
247 errorInitialize(void)
249 using ErrorPage::ImportStaticErrorText
;
253 error_page_count
= ERR_MAX
+ ErrorDynamicPages
.size();
254 error_text
= static_cast<char **>(xcalloc(error_page_count
, sizeof(char *)));
256 for (i
= ERR_NONE
, ++i
; i
< error_page_count
; ++i
) {
257 safe_free(error_text
[i
]);
259 if ((text
= errorFindHardText(i
))) {
261 * Index any hard-coded error text into defaults.
263 static const SBuf
builtIn("built-in");
264 ImportStaticErrorText(i
, text
, builtIn
);
266 } else if (i
< ERR_MAX
) {
268 * Index precompiled fixed template files from one of two sources:
269 * (a) default language translation directory (error_default_language)
270 * (b) admin specified custom directory (error_directory)
272 ErrorPageFile
errTmpl(err_type_str
[i
], i
);
273 errTmpl
.loadDefault();
274 ImportStaticErrorText(i
, errTmpl
.text(), errTmpl
.filename
);
277 * Index any unknown file names used by deny_info.
279 ErrorDynamicPageInfo
*info
= ErrorDynamicPages
.at(i
- ERR_MAX
);
280 assert(info
&& info
->id
== i
&& info
->page_name
);
282 if (info
->filename
) {
283 /** But only if they are not redirection URL. */
284 ErrorPageFile
errTmpl(info
->filename
, ERR_MAX
);
285 errTmpl
.loadDefault();
286 ImportStaticErrorText(i
, errTmpl
.text(), errTmpl
.filename
);
289 ErrorPage::ValidateStaticError(i
, info
->cfgLocation
);
294 error_stylesheet
.reset();
296 // look for and load stylesheet into global MemBuf for it.
297 if (Config
.errorStylesheet
) {
298 ErrorPageFile
tmpl("StylesSheet", ERR_MAX
);
299 tmpl
.loadFromFile(Config
.errorStylesheet
);
300 error_stylesheet
.appendf("%s",tmpl
.text());
304 Ssl::errorDetailInitialize();
314 for (i
= ERR_NONE
+ 1; i
< error_page_count
; ++i
)
315 safe_free(error_text
[i
]);
317 safe_free(error_text
);
320 while (!ErrorDynamicPages
.empty()) {
321 delete ErrorDynamicPages
.back();
322 ErrorDynamicPages
.pop_back();
325 error_page_count
= 0;
328 Ssl::errorDetailClean();
332 /// \ingroup ErrorPageInternal
334 errorFindHardText(err_type type
)
338 for (i
= 0; i
< error_hard_text_count
; ++i
)
339 if (error_hard_text
[i
].type
== type
)
340 return error_hard_text
[i
].text
;
345 TemplateFile::TemplateFile(const char *name
, const err_type code
): silent(false), wasLoaded(false), templateName(name
), templateCode(code
)
351 TemplateFile::loadDefault()
353 if (loaded()) // already loaded?
356 /** test error_directory configured location */
357 if (Config
.errorDirectory
) {
358 char path
[MAXPATHLEN
];
359 snprintf(path
, sizeof(path
), "%s/%s", Config
.errorDirectory
, templateName
.termedBuf());
364 /** test error_default_language location */
365 if (!loaded() && Config
.errorDefaultLanguage
) {
366 if (!tryLoadTemplate(Config
.errorDefaultLanguage
)) {
367 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "Unable to load default error language files. Reset to backups.");
372 /* test default location if failed (templates == English translation base templates) */
374 tryLoadTemplate("templates");
377 /* giving up if failed */
379 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "WARNING: failed to find or read error text file " << templateName
);
387 TemplateFile::tryLoadTemplate(const char *lang
)
391 char path
[MAXPATHLEN
];
392 /* TODO: prep the directory path string to prevent snprintf ... */
393 snprintf(path
, sizeof(path
), "%s/%s/%s",
394 DEFAULT_SQUID_ERROR_DIR
, lang
, templateName
.termedBuf());
395 path
[MAXPATHLEN
-1] = '\0';
397 if (loadFromFile(path
))
401 if ( strlen(lang
) == 2) {
402 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
403 /* use first result. */
404 debugs(4,2, HERE
<< "wildcard fallback errors not coded yet.");
412 TemplateFile::loadFromFile(const char *path
)
418 if (loaded()) // already loaded?
421 fd
= file_open(path
, O_RDONLY
| O_TEXT
);
424 /* with dynamic locale negotiation we may see some failures before a success. */
425 if (!silent
&& templateCode
< TCP_RESET
) {
427 debugs(4, DBG_CRITICAL
, "ERROR: loading file '" << path
<< "': " << xstrerr(xerrno
));
434 while ((len
= FD_READ_METHOD(fd
, buf
, sizeof(buf
))) > 0) {
435 template_
.append(buf
, len
);
441 debugs(4, DBG_CRITICAL
, MYNAME
<< "ERROR: failed to fully read: '" << path
<< "': " << xstrerr(xerrno
));
448 filename
= SBuf(path
);
451 debugs(4, DBG_CRITICAL
, "ERROR: parsing error in template file: " << path
);
460 bool strHdrAcptLangGetItem(const String
&hdr
, char *lang
, int langLen
, size_t &pos
)
462 while (pos
< hdr
.size()) {
464 /* skip any initial whitespace. */
465 while (pos
< hdr
.size() && xisspace(hdr
[pos
]))
469 * Header value format:
470 * - sequence of whitespace delimited tags
471 * - each tag may suffix with ';'.* which we can ignore.
472 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
473 * with preference given to an exact match.
475 bool invalid_byte
= false;
477 while (pos
< hdr
.size() && hdr
[pos
] != ';' && hdr
[pos
] != ',' && !xisspace(hdr
[pos
]) && dt
< (lang
+ (langLen
-1)) ) {
479 #if USE_HTTP_VIOLATIONS
480 // if accepting violations we may as well accept some broken browsers
481 // which may send us the right code, wrong ISO formatting.
486 *dt
= xtolower(hdr
[pos
]);
487 // valid codes only contain A-Z, hyphen (-) and *
488 if (*dt
!= '-' && *dt
!= '*' && (*dt
< 'a' || *dt
> 'z') )
491 ++dt
; // move to next destination byte.
495 *dt
= '\0'; // nul-terminated the filename content string before system use.
497 // if we terminated the tag on garbage or ';' we need to skip to the next ',' or end of header.
498 while (pos
< hdr
.size() && hdr
[pos
] != ',')
501 if (pos
< hdr
.size() && hdr
[pos
] == ',')
504 debugs(4, 9, "STATE: lang=" << lang
<< ", pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
506 /* if we found anything we might use, try it. */
507 if (*lang
!= '\0' && !invalid_byte
)
514 TemplateFile::loadFor(const HttpRequest
*request
)
519 if (loaded()) // already loaded?
522 if (!request
|| !request
->header
.getList(Http::HdrType::ACCEPT_LANGUAGE
, &hdr
))
526 size_t pos
= 0; // current parsing position in header string
528 debugs(4, 6, HERE
<< "Testing Header: '" << hdr
<< "'");
530 while ( strHdrAcptLangGetItem(hdr
, lang
, 256, pos
) ) {
532 /* wildcard uses the configured default language */
533 if (lang
[0] == '*' && lang
[1] == '\0') {
534 debugs(4, 6, HERE
<< "Found language '" << lang
<< "'. Using configured default.");
538 debugs(4, 6, HERE
<< "Found language '" << lang
<< "', testing for available template");
540 if (tryLoadTemplate(lang
)) {
541 /* store the language we found for the Content-Language reply header */
544 } else if (Config
.errorLogMissingLanguages
) {
545 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << lang
);
553 ErrorDynamicPageInfo::ErrorDynamicPageInfo(const int anId
, const char *aName
, const SBuf
&aCfgLocation
):
555 page_name(xstrdup(aName
)),
558 cfgLocation(aCfgLocation
),
559 page_redirect(static_cast<Http::StatusCode
>(atoi(page_name
)))
561 const char *filenameOrUri
= nullptr;
562 if (xisdigit(*page_name
)) {
563 if (const char *statusCodeEnd
= strchr(page_name
, ':'))
564 filenameOrUri
= statusCodeEnd
+ 1;
566 assert(!page_redirect
);
567 filenameOrUri
= page_name
;
570 // Guessed uri, filename, or both values may be nil or malformed.
571 // They are validated later.
572 if (!page_redirect
) {
573 if (filenameOrUri
&& strchr(filenameOrUri
, ':')) // looks like a URL
576 filename
= filenameOrUri
;
578 else if (page_redirect
/100 == 3) {
579 // redirects imply a URL
582 // non-redirects imply an error page name
583 filename
= filenameOrUri
;
586 const auto info
= this; // source code change reduction hack
587 // TODO: Move and refactor to avoid self_destruct()s in reconfigure.
589 /* WARNING on redirection status:
590 * 2xx are permitted, but not documented officially.
591 * - might be useful for serving static files (PAC etc) in special cases
592 * 3xx require a URL suitable for Location: header.
593 * - the current design does not allow for a Location: URI as well as a local file template
594 * although this possibility is explicitly permitted in the specs.
595 * 4xx-5xx require a local file template.
596 * - sending Location: on these codes with no body is invalid by the specs.
597 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
598 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
600 if (info
->page_redirect
== Http::scNone
)
601 ; // special case okay.
602 else if (info
->page_redirect
< 200 || info
->page_redirect
> 599) {
604 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
606 } else if ( /* >= 200 && */ info
->page_redirect
< 300 && strchr(&(page_name
[4]), ':')) {
607 // 2xx require a local template file
608 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
610 } else if (info
->page_redirect
>= 300 && info
->page_redirect
<= 399 && !strchr(&(page_name
[4]), ':')) {
611 // 3xx require an absolute URL
612 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a URL on '" << page_name
<< "'");
614 } else if (info
->page_redirect
>= 400 /* && <= 599 */ && strchr(&(page_name
[4]), ':')) {
615 // 4xx/5xx require a local template file
616 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
622 /// \ingroup ErrorPageInternal
624 errorPageId(const char *page_name
)
626 for (int i
= 0; i
< ERR_MAX
; ++i
) {
627 if (strcmp(err_type_str
[i
], page_name
) == 0)
631 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); ++j
) {
632 if (strcmp(ErrorDynamicPages
[j
]->page_name
, page_name
) == 0)
640 errorReservePageId(const char *page_name
, const SBuf
&cfgLocation
)
642 int id
= errorPageId(page_name
);
644 if (id
== ERR_NONE
) {
645 id
= ERR_MAX
+ ErrorDynamicPages
.size();
646 const auto info
= new ErrorDynamicPageInfo(id
, page_name
, cfgLocation
);
647 ErrorDynamicPages
.push_back(info
);
653 /// \ingroup ErrorPageInternal
655 errorPageName(int pageId
)
657 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
658 return err_type_str
[pageId
];
660 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
661 return ErrorDynamicPages
[pageId
- ERR_MAX
]->page_name
;
663 return "ERR_UNKNOWN"; /* should not happen */
667 ErrorState::NewForwarding(err_type type
, HttpRequestPointer
&request
, const AccessLogEntry::Pointer
&ale
)
669 const Http::StatusCode status
= (request
&& request
->flags
.needValidation
) ?
670 Http::scGatewayTimeout
: Http::scServiceUnavailable
;
671 return new ErrorState(type
, status
, request
.getRaw(), ale
);
674 ErrorState::ErrorState(err_type t
) :
681 ErrorState::ErrorState(err_type t
, Http::StatusCode status
, HttpRequest
* req
, const AccessLogEntry::Pointer
&anAle
) :
684 if (page_id
>= ERR_MAX
&& ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
!= Http::scNone
)
685 httpStatus
= ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
;
691 src_addr
= req
->client_addr
;
697 ErrorState::ErrorState(HttpRequest
* req
, HttpReply
*errorReply
) :
698 ErrorState(ERR_RELAY_REMOTE
)
701 response_
= errorReply
;
702 httpStatus
= errorReply
->sline
.status();
706 src_addr
= req
->client_addr
;
711 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
713 assert(entry
->mem_obj
!= NULL
);
714 assert (entry
->isEmpty());
715 debugs(4, 4, "Creating an error page for entry " << entry
<<
716 " with errorstate " << err
<<
717 " page id " << err
->page_id
);
719 if (entry
->store_status
!= STORE_PENDING
) {
720 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
722 * If the entry is not STORE_PENDING, then no clients
723 * care about it, and we don't need to generate an
726 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
727 assert(entry
->mem_obj
->nclients
== 0);
732 if (err
->page_id
== TCP_RESET
) {
734 debugs(4, 2, "RSTing this reply");
735 err
->request
->flags
.resetTcp
= true;
739 entry
->storeErrorResponse(err
->BuildHttpReply());
744 errorSend(const Comm::ConnectionPointer
&conn
, ErrorState
* err
)
746 debugs(4, 3, conn
<< ", err=" << err
);
747 assert(Comm::IsConnOpen(conn
));
749 HttpReplyPointer
rep(err
->BuildHttpReply());
751 MemBuf
*mb
= rep
->pack();
752 AsyncCall::Pointer call
= commCbCall(78, 5, "errorSendComplete",
753 CommIoCbPtrFun(&errorSendComplete
, err
));
754 Comm::Write(conn
, mb
, call
);
759 \ingroup ErrorPageAPI
761 * Called by commHandleWrite() after data has been written
762 * to the client socket.
764 \note If there is a callback, the callback is responsible for
765 * closing the FD, otherwise we do it ourselves.
768 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *, size_t size
, Comm::Flag errflag
, int, void *data
)
770 ErrorState
*err
= static_cast<ErrorState
*>(data
);
771 debugs(4, 3, HERE
<< conn
<< ", size=" << size
);
773 if (errflag
!= Comm::ERR_CLOSING
) {
775 debugs(4, 3, "errorSendComplete: callback");
776 err
->callback(conn
->fd
, err
->callback_data
, size
);
778 debugs(4, 3, "errorSendComplete: comm_close");
786 ErrorState::~ErrorState()
788 safe_free(redirect_url
);
790 safe_free(request_hdrs
);
791 wordlistDestroy(&ftp
.server_msg
);
792 safe_free(ftp
.request
);
793 safe_free(ftp
.reply
);
796 if (err_language
!= Config
.errorDefaultLanguage
)
798 safe_free(err_language
);
805 ErrorState::Dump(MemBuf
* mb
)
808 char ntoabuf
[MAX_IPSTRLEN
];
811 /* email subject line */
812 str
.appendf("CacheErrorInfo - %s", errorPageName(type
));
813 mb
->appendf("?subject=%s", rfc1738_escape_part(str
.buf
));
816 str
.appendf("CacheHost: %s\r\n", getMyHostname());
818 str
.appendf("ErrPage: %s\r\n", errorPageName(type
));
821 str
.appendf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
823 str
.append("Err: [none]\r\n", 13);
826 if (auth_user_request
.getRaw() && auth_user_request
->denyMessage())
827 str
.appendf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
829 if (dnsError
.size() > 0)
830 str
.appendf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
833 str
.appendf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
836 str
.appendf("ClientIP: %s\r\n", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
838 if (request
&& request
->hier
.host
[0] != '\0') {
839 str
.appendf("ServerIP: %s\r\n", request
->hier
.host
);
842 str
.append("\r\n", 2);
844 str
.append("HTTP Request:\r\n", 15);
846 str
.appendf(SQUIDSBUFPH
" " SQUIDSBUFPH
" %s/%d.%d\n",
847 SQUIDSBUFPRINT(request
->method
.image()),
848 SQUIDSBUFPRINT(request
->url
.path()),
849 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
850 request
->http_ver
.major
, request
->http_ver
.minor
);
851 request
->header
.packInto(&str
);
854 str
.append("\r\n", 2);
858 str
.appendf("FTP Request: %s\r\n", ftp
.request
);
859 str
.appendf("FTP Reply: %s\r\n", (ftp
.reply
? ftp
.reply
:"[none]"));
860 str
.append("FTP Msg: ", 9);
861 wordlistCat(ftp
.server_msg
, &str
);
862 str
.append("\r\n", 2);
865 str
.append("\r\n", 2);
866 mb
->appendf("&body=%s", rfc1738_escape_part(str
.buf
));
871 /// \ingroup ErrorPageInternal
872 #define CVT_BUF_SZ 512
875 ErrorState::compileLogformatCode(Build
&build
)
877 assert(LogformatMagic
.cmp(build
.input
, LogformatMagic
.length()) == 0);
880 const auto logformat
= build
.input
+ LogformatMagic
.length();
882 // Logformat supports undocumented "external" encoding specifications
883 // like [%>h] or "%<a". To preserve the possibility of extending
884 // @Squid{} syntax to non-logformat sequences, we require logformat
885 // sequences to start with '%'. This restriction does not limit
886 // logformat quoting abilities. TODO: Deprecate "external" encoding?
887 if (*logformat
!= '%')
888 throw TexcHere("logformat expressions that do not start with % are not supported");
890 static MemBuf result
;
892 const auto logformatLen
= Format::AssembleOne(logformat
, result
, ale
);
893 assert(logformatLen
> 0);
894 const auto closure
= logformat
+ logformatLen
;
896 throw TexcHere("Missing closing brace (})");
897 build
.output
.append(result
.content(), result
.contentSize());
898 build
.input
= closure
+ 1;
901 noteBuildError("Bad @Squid{logformat} sequence", build
.input
);
904 // we cannot recover reliably so stop interpreting the rest of input
905 const auto remainingSize
= strlen(build
.input
);
906 build
.output
.append(build
.input
, remainingSize
);
907 build
.input
+= remainingSize
;
911 ErrorState::compileLegacyCode(Build
&build
)
914 const char *p
= NULL
; /* takes priority over mb if set */
916 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
917 char ntoabuf
[MAX_IPSTRLEN
];
921 const auto &building_deny_info_url
= build
.building_deny_info_url
; // a change reduction hack
923 const auto letter
= build
.input
[1];
929 if (request
&& request
->auth_user_request
)
930 p
= request
->auth_user_request
->username();
937 // TODO: When/if we get ALE here, pass it as well
938 if (const auto addr
= FindListeningPortAddress(request
.getRaw(), nullptr))
939 mb
.appendf("%s", addr
->toStr(ntoabuf
, MAX_IPSTRLEN
));
945 mb
.appendf("%u", getMyPort());
949 if (building_deny_info_url
) break;
951 const SBuf
&tmp
= Ftp::UrlWith2f(request
.getRaw());
952 mb
.append(tmp
.rawContent(), tmp
.length());
958 if (building_deny_info_url
) break;
959 p
= errorPageName(type
);
963 if (!build
.allowRecursion
)
964 p
= "%D"; // if recursion is not allowed, do not convert
966 // currently only SSL error details implemented
968 detail
->useRequest(request
.getRaw());
969 const String
&errDetail
= detail
->toString();
970 if (errDetail
.size() > 0) {
971 const auto compiledDetail
= compileBody(errDetail
.termedBuf(), false);
972 mb
.append(compiledDetail
.rawContent(), compiledDetail
.length());
977 if (!mb
.contentSize())
978 mb
.append("[No Error Detail]", 17);
982 mb
.appendf("%d", xerrno
);
987 mb
.appendf("(%d) %s", xerrno
, strerror(xerrno
));
989 mb
.append("[No Error]", 10);
993 if (building_deny_info_url
) break;
994 /* FTP REQUEST LINE */
1002 if (building_deny_info_url
) break;
1003 /* FTP REPLY LINE */
1011 if (building_deny_info_url
) break;
1012 /* FTP SERVER RESPONSE */
1014 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
1016 } else if (ftp
.server_msg
) {
1017 wordlistCat(ftp
.server_msg
, &mb
);
1022 mb
.appendf("%s", getMyHostname());
1027 if (request
->hier
.host
[0] != '\0') // if non-empty string.
1028 p
= request
->hier
.host
;
1030 p
= request
->url
.host();
1031 } else if (!building_deny_info_url
)
1032 p
= "[unknown host]";
1036 mb
.appendf("%s", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
1040 if (request
&& request
->hier
.tcpServer
)
1041 p
= request
->hier
.tcpServer
->remote
.toStr(ntoabuf
,MAX_IPSTRLEN
);
1042 else if (!building_deny_info_url
)
1047 if (building_deny_info_url
) break;
1048 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
1053 if (building_deny_info_url
) break;
1054 if (Config
.errHtmlText
) {
1055 mb
.appendf("%s", Config
.errHtmlText
);
1058 p
= "[not available]";
1062 if (building_deny_info_url
) break;
1064 if (auth_user_request
.getRaw())
1065 p
= auth_user_request
->denyMessage("[not available]");
1067 p
= "[not available]";
1075 const SBuf
&m
= request
->method
.image();
1076 mb
.append(m
.rawContent(), m
.length());
1077 } else if (!building_deny_info_url
)
1078 p
= "[unknown method]";
1082 if (!building_deny_info_url
)
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
)
1209 mb
.appendf("%s", detail
->errorName());
1212 if (!building_deny_info_url
)
1213 p
= "[Unknown Error Code]";
1217 if (building_deny_info_url
) break;
1218 if (dnsError
.size() > 0)
1219 p
= dnsError
.termedBuf();
1220 else if (ftp
.cwd_msg
)
1227 if (building_deny_info_url
) break;
1239 if (building_deny_info_url
)
1240 bypassBuildErrorXXX("Unsupported deny_info %code", build
.input
);
1241 else if (letter
!= ';')
1242 bypassBuildErrorXXX("Unsupported error page %code", build
.input
);
1243 // else too many "font-size: 100%;" template errors to report
1245 mb
.append(build
.input
, 2);
1251 p
= mb
.buf
; /* do not use mb after this assignment! */
1255 debugs(4, 3, "%" << letter
<< " --> '" << p
<< "'" );
1260 if (building_deny_info_url
&& !no_urlescape
)
1261 p
= rfc1738_escape_part(p
);
1263 // TODO: Optimize by replacing mb with direct build.output usage.
1264 build
.output
.append(p
, strlen(p
));
1269 ErrorState::validate()
1271 if (const auto urlTemplate
= ErrorPage::IsDenyInfoUri(page_id
)) {
1272 (void)compile(urlTemplate
, true, true);
1274 assert(page_id
> ERR_NONE
);
1275 assert(page_id
< error_page_count
);
1276 (void)compileBody(error_text
[page_id
], true);
1281 ErrorState::BuildHttpReply()
1284 return response_
.getRaw();
1286 HttpReply
*rep
= new HttpReply
;
1287 const char *name
= errorPageName(page_id
);
1288 /* no LMT for error pages; error pages expire immediately */
1290 if (const auto urlTemplate
= ErrorPage::IsDenyInfoUri(page_id
)) {
1292 Http::StatusCode status
= Http::scFound
;
1293 // Use configured 3xx reply status if set.
1295 status
= httpStatus
;
1297 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1298 if (request
&& request
->method
!= Http::METHOD_GET
&& request
->method
!= Http::METHOD_HEAD
&& request
->http_ver
>= Http::ProtocolVersion(1,1))
1299 status
= Http::scTemporaryRedirect
;
1302 rep
->setHeaders(status
, NULL
, "text/html;charset=utf-8", 0, 0, -1);
1305 auto location
= compile(urlTemplate
, true, true);
1306 rep
->header
.putStr(Http::HdrType::LOCATION
, location
.c_str());
1309 httpHeaderPutStrf(&rep
->header
, Http::HdrType::X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
1311 const auto body
= buildBody();
1312 rep
->setHeaders(httpStatus
, NULL
, "text/html;charset=utf-8", body
.length(), 0, -1);
1314 * include some information for downstream caches. Implicit
1315 * replaceable content. This isn't quite sufficient. xerrno is not
1316 * necessarily meaningful to another system, so we really should
1317 * expand it. Additionally, we should identify ourselves. Someone
1318 * might want to know. Someone _will_ want to know OTOH, the first
1319 * X-CACHE-MISS entry should tell us who.
1321 httpHeaderPutStrf(&rep
->header
, Http::HdrType::X_SQUID_ERROR
, "%s %d", name
, xerrno
);
1325 * If error page auto-negotiate is enabled in any way, send the Vary.
1326 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1327 * We have even better reasons though:
1328 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1330 if (!Config
.errorDirectory
) {
1331 /* We 'negotiated' this ONLY from the Accept-Language. */
1332 rep
->header
.delById(Http::HdrType::VARY
);
1333 rep
->header
.putStr(Http::HdrType::VARY
, "Accept-Language");
1336 /* add the Content-Language header according to RFC section 14.12 */
1338 rep
->header
.putStr(Http::HdrType::CONTENT_LANGUAGE
, err_language
);
1340 #endif /* USE_ERROR_LOCALES */
1342 /* default templates are in English */
1343 /* language is known unless error_directory override used */
1344 if (!Config
.errorDirectory
)
1345 rep
->header
.putStr(Http::HdrType::CONTENT_LANGUAGE
, "en");
1348 rep
->body
.set(body
);
1351 // Make sure error codes get back to the client side for logging and
1354 int edc
= ERR_DETAIL_NONE
; // error detail code
1357 edc
= detail
->errorNo();
1364 request
->detailError(type
, edc
);
1371 ErrorState::buildBody()
1373 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
1376 /** error_directory option in squid.conf overrides translations.
1377 * Custom errors are always found either in error_directory or the templates directory.
1378 * Otherwise locate the Accept-Language header
1380 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
) {
1381 if (err_language
&& err_language
!= Config
.errorDefaultLanguage
)
1382 safe_free(err_language
);
1384 ErrorPageFile
localeTmpl(err_type_str
[page_id
], static_cast<err_type
>(page_id
));
1385 if (localeTmpl
.loadFor(request
.getRaw())) {
1386 inputLocation
= localeTmpl
.filename
;
1387 assert(localeTmpl
.language());
1388 err_language
= xstrdup(localeTmpl
.language());
1389 return compileBody(localeTmpl
.text(), true);
1392 #endif /* USE_ERR_LOCALES */
1395 * If client-specific error templates are not enabled or available.
1396 * fall back to the old style squid.conf settings.
1399 if (!Config
.errorDirectory
)
1400 err_language
= Config
.errorDefaultLanguage
;
1402 debugs(4, 2, "No existing error page language negotiated for " << errorPageName(page_id
) << ". Using default error file.");
1403 return compileBody(error_text
[page_id
], true);
1407 ErrorState::compileBody(const char *input
, bool allowRecursion
)
1409 return compile(input
, false, allowRecursion
);
1413 ErrorState::compile(const char *input
, bool building_deny_info_url
, bool allowRecursion
)
1418 build
.building_deny_info_url
= building_deny_info_url
;
1419 build
.allowRecursion
= allowRecursion
;
1420 build
.input
= input
;
1422 auto blockStart
= build
.input
;
1423 while (const auto letter
= *build
.input
) {
1424 if (letter
== '%') {
1425 build
.output
.append(blockStart
, build
.input
- blockStart
);
1426 compileLegacyCode(build
);
1427 blockStart
= build
.input
;
1429 else if (letter
== '@' && LogformatMagic
.cmp(build
.input
, LogformatMagic
.length()) == 0) {
1430 build
.output
.append(blockStart
, build
.input
- blockStart
);
1431 compileLogformatCode(build
);
1432 blockStart
= build
.input
;
1437 build
.output
.append(blockStart
, build
.input
- blockStart
);
1438 return build
.output
;
1441 /// react to a compile() error
1442 /// \param msg description of what went wrong
1443 /// \param near approximate start of the problematic input
1444 /// \param forceBypass whether detection of this error was introduced late,
1445 /// after old configurations containing this error could have been
1446 /// successfully validated and deployed (i.e. the admin may not be
1447 /// able to fix this newly detected but old problem quickly)
1449 ErrorState::noteBuildError_(const char *msg
, const char *near
, const bool forceBypass
)
1451 using ErrorPage::BuildErrorPrinter
;
1452 const auto runtime
= !starting_up
;
1453 if (runtime
|| forceBypass
) {
1454 // swallow this problem because the admin may not be (and/or the page
1455 // building code is not) ready to handle throwing consequences
1457 static unsigned int seenErrors
= 0;
1460 const auto debugLevel
=
1461 (seenErrors
> 100) ? DBG_DATA
:
1462 (starting_up
|| reconfiguring
) ? DBG_CRITICAL
:
1463 3; // most other errors have been reported as configuration errors
1465 // Error fatality depends on the error context: Reconfiguration errors
1466 // are, like startup ones, DBG_CRITICAL but will never become FATAL.
1467 if (starting_up
&& seenErrors
<= 10)
1468 debugs(4, debugLevel
, "WARNING: The following configuration error will be fatal in future Squid versions");
1470 debugs(4, debugLevel
, "ERROR: " << BuildErrorPrinter(inputLocation
, page_id
, msg
, near
));
1472 throw TexcHere(ToSBuf(BuildErrorPrinter(inputLocation
, page_id
, msg
, near
)));
1476 /* ErrorPage::BuildErrorPrinter */
1479 ErrorPage::BuildErrorPrinter::printLocation(std::ostream
&os
) const {
1480 if (!inputLocation
.isEmpty())
1481 return os
<< inputLocation
;
1483 if (page_id
< ERR_NONE
|| page_id
>= error_page_count
)
1484 return os
<< "[error page " << page_id
<< "]"; // should not happen
1486 if (page_id
< ERR_MAX
)
1487 return os
<< err_type_str
[page_id
];
1489 return os
<< "deny_info " << ErrorDynamicPages
.at(page_id
- ERR_MAX
)->page_name
;
1493 ErrorPage::BuildErrorPrinter::print(std::ostream
&os
) const {
1494 printLocation(os
) << ": " << msg
<< " near ";
1496 // TODO: Add support for prefix printing to Raw
1497 const size_t maxContextLength
= 15; // plus "..."
1498 if (strlen(near
) > maxContextLength
) {
1499 os
.write(near
, maxContextLength
);
1505 // XXX: We should not be converting (inner) exception to text if we are
1506 // going to throw again. See "add arbitrary (re)thrower-supplied details"
1507 // TODO in TextException.h for a long-term in-catcher solution.
1508 if (std::current_exception())
1509 os
<< "\n additional info: " << CurrentException
;
1514 /// add error page template to the global index
1516 ErrorPage::ImportStaticErrorText(const int page_id
, const char *text
, const SBuf
&inputLocation
)
1518 assert(!error_text
[page_id
]);
1519 error_text
[page_id
] = xstrdup(text
);
1520 ValidateStaticError(page_id
, inputLocation
);
1523 /// validate static error page
1525 ErrorPage::ValidateStaticError(const int page_id
, const SBuf
&inputLocation
)
1527 // Supplying nil ALE pointer limits validation to logformat %code
1528 // recognition by Format::Token::parse(). This is probably desirable
1529 // because actual %code assembly is slow and should not affect validation
1530 // when our ALE cannot have any real data (this code is not associated
1531 // with any real transaction).
1532 ErrorState
anErr(err_type(page_id
), Http::scNone
, nullptr, nullptr);
1533 anErr
.inputLocation
= inputLocation
;