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"
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"
173 "unexpected client disconnect"
176 ERR_SECURE_ACCEPT_FAIL
,
180 ERR_REQUEST_START_TIMEOUT
,
181 "request start timedout"
189 /// \ingroup ErrorPageInternal
190 static std::vector
<ErrorDynamicPageInfo
*> ErrorDynamicPages
;
192 /* local prototypes */
194 /// \ingroup ErrorPageInternal
195 static const int error_hard_text_count
= sizeof(error_hard_text
) / sizeof(*error_hard_text
);
197 /// \ingroup ErrorPageInternal
198 static char **error_text
= nullptr;
200 /// \ingroup ErrorPageInternal
201 static int error_page_count
= 0;
203 /// \ingroup ErrorPageInternal
204 static MemBuf error_stylesheet
;
206 static const char *errorFindHardText(err_type type
);
207 static IOCB errorSendComplete
;
209 /// \ingroup ErrorPageInternal
210 /// manages an error page template
211 class ErrorPageFile
: public TemplateFile
214 ErrorPageFile(const char *name
, const err_type code
) : TemplateFile(name
, code
) {}
216 /// The template text data read from disk
217 const char *text() { return template_
.c_str(); }
220 virtual void setDefault() override
{
221 template_
= "Internal Error: Missing Template ";
222 template_
.append(templateName
.termedBuf());
226 /// \ingroup ErrorPageInternal
228 operator++ (err_type
&anErr
)
230 int tmp
= (int)anErr
;
231 anErr
= (err_type
)(++tmp
);
235 /// \ingroup ErrorPageInternal
237 operator -(err_type
const &anErr
, err_type
const &anErr2
)
239 return (int)anErr
- (int)anErr2
;
242 /// \return deny_info URL if the given page is a deny_info page with a URL
243 /// \return nullptr otherwise
245 ErrorPage::IsDenyInfoUri(const int page_id
)
247 if (ERR_MAX
<= page_id
&& page_id
< error_page_count
)
248 return ErrorDynamicPages
.at(page_id
- ERR_MAX
)->uri
; // may be nil
253 errorInitialize(void)
255 using ErrorPage::ImportStaticErrorText
;
259 error_page_count
= ERR_MAX
+ ErrorDynamicPages
.size();
260 error_text
= static_cast<char **>(xcalloc(error_page_count
, sizeof(char *)));
262 for (i
= ERR_NONE
, ++i
; i
< error_page_count
; ++i
) {
263 safe_free(error_text
[i
]);
265 if ((text
= errorFindHardText(i
))) {
267 * Index any hard-coded error text into defaults.
269 static const SBuf
builtIn("built-in");
270 ImportStaticErrorText(i
, text
, builtIn
);
272 } else if (i
< ERR_MAX
) {
274 * Index precompiled fixed template files from one of two sources:
275 * (a) default language translation directory (error_default_language)
276 * (b) admin specified custom directory (error_directory)
278 ErrorPageFile
errTmpl(err_type_str
[i
], i
);
279 errTmpl
.loadDefault();
280 ImportStaticErrorText(i
, errTmpl
.text(), errTmpl
.filename
);
283 * Index any unknown file names used by deny_info.
285 ErrorDynamicPageInfo
*info
= ErrorDynamicPages
.at(i
- ERR_MAX
);
286 assert(info
&& info
->id
== i
&& info
->page_name
);
288 if (info
->filename
) {
289 /** But only if they are not redirection URL. */
290 ErrorPageFile
errTmpl(info
->filename
, ERR_MAX
);
291 errTmpl
.loadDefault();
292 ImportStaticErrorText(i
, errTmpl
.text(), errTmpl
.filename
);
295 ErrorPage::ValidateStaticError(i
, info
->cfgLocation
);
300 error_stylesheet
.reset();
302 // look for and load stylesheet into global MemBuf for it.
303 if (Config
.errorStylesheet
) {
304 ErrorPageFile
tmpl("StylesSheet", ERR_MAX
);
305 tmpl
.loadFromFile(Config
.errorStylesheet
);
306 error_stylesheet
.appendf("%s",tmpl
.text());
310 Ssl::errorDetailInitialize();
320 for (i
= ERR_NONE
+ 1; i
< error_page_count
; ++i
)
321 safe_free(error_text
[i
]);
323 safe_free(error_text
);
326 while (!ErrorDynamicPages
.empty()) {
327 delete ErrorDynamicPages
.back();
328 ErrorDynamicPages
.pop_back();
331 error_page_count
= 0;
334 Ssl::errorDetailClean();
338 /// \ingroup ErrorPageInternal
340 errorFindHardText(err_type type
)
344 for (i
= 0; i
< error_hard_text_count
; ++i
)
345 if (error_hard_text
[i
].type
== type
)
346 return error_hard_text
[i
].text
;
351 TemplateFile::TemplateFile(const char *name
, const err_type code
): silent(false), wasLoaded(false), templateName(name
), templateCode(code
)
357 TemplateFile::loadDefault()
359 if (loaded()) // already loaded?
362 /** test error_directory configured location */
363 if (Config
.errorDirectory
) {
364 char path
[MAXPATHLEN
];
365 snprintf(path
, sizeof(path
), "%s/%s", Config
.errorDirectory
, templateName
.termedBuf());
370 /** test error_default_language location */
371 if (!loaded() && Config
.errorDefaultLanguage
) {
372 if (!tryLoadTemplate(Config
.errorDefaultLanguage
)) {
373 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "ERROR: Unable to load default error language files. Reset to backups.");
378 /* test default location if failed (templates == English translation base templates) */
380 tryLoadTemplate("templates");
383 /* giving up if failed */
385 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "WARNING: failed to find or read error text file " << templateName
);
393 TemplateFile::tryLoadTemplate(const char *lang
)
397 char path
[MAXPATHLEN
];
398 /* TODO: prep the directory path string to prevent snprintf ... */
399 snprintf(path
, sizeof(path
), "%s/%s/%s",
400 DEFAULT_SQUID_ERROR_DIR
, lang
, templateName
.termedBuf());
401 path
[MAXPATHLEN
-1] = '\0';
403 if (loadFromFile(path
))
407 if ( strlen(lang
) == 2) {
408 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
409 /* use first result. */
410 debugs(4,2, "wildcard fallback errors not coded yet.");
418 TemplateFile::loadFromFile(const char *path
)
424 if (loaded()) // already loaded?
427 fd
= file_open(path
, O_RDONLY
| O_TEXT
);
430 /* with dynamic locale negotiation we may see some failures before a success. */
431 if (!silent
&& templateCode
< TCP_RESET
) {
433 debugs(4, DBG_CRITICAL
, "ERROR: loading file '" << path
<< "': " << xstrerr(xerrno
));
440 while ((len
= FD_READ_METHOD(fd
, buf
, sizeof(buf
))) > 0) {
441 template_
.append(buf
, len
);
447 debugs(4, DBG_CRITICAL
, MYNAME
<< "ERROR: failed to fully read: '" << path
<< "': " << xstrerr(xerrno
));
454 filename
= SBuf(path
);
457 debugs(4, DBG_CRITICAL
, "ERROR: parsing error in template file: " << path
);
466 bool strHdrAcptLangGetItem(const String
&hdr
, char *lang
, int langLen
, size_t &pos
)
468 while (pos
< hdr
.size()) {
470 /* skip any initial whitespace. */
471 while (pos
< hdr
.size() && xisspace(hdr
[pos
]))
475 * Header value format:
476 * - sequence of whitespace delimited tags
477 * - each tag may suffix with ';'.* which we can ignore.
478 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
479 * with preference given to an exact match.
481 bool invalid_byte
= false;
483 while (pos
< hdr
.size() && hdr
[pos
] != ';' && hdr
[pos
] != ',' && !xisspace(hdr
[pos
]) && dt
< (lang
+ (langLen
-1)) ) {
485 #if USE_HTTP_VIOLATIONS
486 // if accepting violations we may as well accept some broken browsers
487 // which may send us the right code, wrong ISO formatting.
492 *dt
= xtolower(hdr
[pos
]);
493 // valid codes only contain A-Z, hyphen (-) and *
494 if (*dt
!= '-' && *dt
!= '*' && (*dt
< 'a' || *dt
> 'z') )
497 ++dt
; // move to next destination byte.
501 *dt
= '\0'; // nul-terminated the filename content string before system use.
503 // if we terminated the tag on garbage or ';' we need to skip to the next ',' or end of header.
504 while (pos
< hdr
.size() && hdr
[pos
] != ',')
507 if (pos
< hdr
.size() && hdr
[pos
] == ',')
510 debugs(4, 9, "STATE: lang=" << lang
<< ", pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
512 /* if we found anything we might use, try it. */
513 if (*lang
!= '\0' && !invalid_byte
)
520 TemplateFile::loadFor(const HttpRequest
*request
)
525 if (loaded()) // already loaded?
528 if (!request
|| !request
->header
.getList(Http::HdrType::ACCEPT_LANGUAGE
, &hdr
))
532 size_t pos
= 0; // current parsing position in header string
534 debugs(4, 6, "Testing Header: '" << hdr
<< "'");
536 while ( strHdrAcptLangGetItem(hdr
, lang
, 256, pos
) ) {
538 /* wildcard uses the configured default language */
539 if (lang
[0] == '*' && lang
[1] == '\0') {
540 debugs(4, 6, "Found language '" << lang
<< "'. Using configured default.");
544 debugs(4, 6, "Found language '" << lang
<< "', testing for available template");
546 if (tryLoadTemplate(lang
)) {
547 /* store the language we found for the Content-Language reply header */
550 } else if (Config
.errorLogMissingLanguages
) {
551 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << lang
);
561 ErrorDynamicPageInfo::ErrorDynamicPageInfo(const int anId
, const char *aName
, const SBuf
&aCfgLocation
):
563 page_name(xstrdup(aName
)),
566 cfgLocation(aCfgLocation
),
567 page_redirect(static_cast<Http::StatusCode
>(atoi(page_name
)))
569 const char *filenameOrUri
= nullptr;
570 if (xisdigit(*page_name
)) {
571 if (const char *statusCodeEnd
= strchr(page_name
, ':'))
572 filenameOrUri
= statusCodeEnd
+ 1;
574 assert(!page_redirect
);
575 filenameOrUri
= page_name
;
578 // Guessed uri, filename, or both values may be nil or malformed.
579 // They are validated later.
580 if (!page_redirect
) {
581 if (filenameOrUri
&& strchr(filenameOrUri
, ':')) // looks like a URL
584 filename
= filenameOrUri
;
586 else if (page_redirect
/100 == 3) {
587 // redirects imply a URL
590 // non-redirects imply an error page name
591 filename
= filenameOrUri
;
594 const auto info
= this; // source code change reduction hack
595 // TODO: Move and refactor to avoid self_destruct()s in reconfigure.
597 /* WARNING on redirection status:
598 * 2xx are permitted, but not documented officially.
599 * - might be useful for serving static files (PAC etc) in special cases
600 * 3xx require a URL suitable for Location: header.
601 * - the current design does not allow for a Location: URI as well as a local file template
602 * although this possibility is explicitly permitted in the specs.
603 * 4xx-5xx require a local file template.
604 * - sending Location: on these codes with no body is invalid by the specs.
605 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
606 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
608 if (info
->page_redirect
== Http::scNone
)
609 ; // special case okay.
610 else if (info
->page_redirect
< 200 || info
->page_redirect
> 599) {
612 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
614 } else if ( /* >= 200 && */ info
->page_redirect
< 300 && strchr(&(page_name
[4]), ':')) {
615 // 2xx require a local template file
616 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
618 } else if (info
->page_redirect
>= 300 && info
->page_redirect
<= 399 && !strchr(&(page_name
[4]), ':')) {
619 // 3xx require an absolute URL
620 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a URL on '" << page_name
<< "'");
622 } else if (info
->page_redirect
>= 400 /* && <= 599 */ && strchr(&(page_name
[4]), ':')) {
623 // 4xx/5xx require a local template file
624 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
630 /// \ingroup ErrorPageInternal
632 errorPageId(const char *page_name
)
634 for (int i
= 0; i
< ERR_MAX
; ++i
) {
635 if (strcmp(err_type_str
[i
], page_name
) == 0)
639 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); ++j
) {
640 if (strcmp(ErrorDynamicPages
[j
]->page_name
, page_name
) == 0)
648 errorReservePageId(const char *page_name
, const SBuf
&cfgLocation
)
650 int id
= errorPageId(page_name
);
652 if (id
== ERR_NONE
) {
653 id
= ERR_MAX
+ ErrorDynamicPages
.size();
654 const auto info
= new ErrorDynamicPageInfo(id
, page_name
, cfgLocation
);
655 ErrorDynamicPages
.push_back(info
);
661 /// \ingroup ErrorPageInternal
663 errorPageName(int pageId
)
665 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
666 return err_type_str
[pageId
];
668 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
669 return ErrorDynamicPages
[pageId
- ERR_MAX
]->page_name
;
671 return "ERR_UNKNOWN"; /* should not happen */
675 ErrorState::NewForwarding(err_type type
, HttpRequestPointer
&request
, const AccessLogEntry::Pointer
&ale
)
677 const Http::StatusCode status
= (request
&& request
->flags
.needValidation
) ?
678 Http::scGatewayTimeout
: Http::scServiceUnavailable
;
679 return new ErrorState(type
, status
, request
.getRaw(), ale
);
682 ErrorState::ErrorState(err_type t
) :
689 ErrorState::ErrorState(err_type t
, Http::StatusCode status
, HttpRequest
* req
, const AccessLogEntry::Pointer
&anAle
) :
692 if (page_id
>= ERR_MAX
&& ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
!= Http::scNone
)
693 httpStatus
= ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
;
699 src_addr
= req
->client_addr
;
705 ErrorState::ErrorState(HttpRequest
* req
, HttpReply
*errorReply
) :
706 ErrorState(ERR_RELAY_REMOTE
)
709 response_
= errorReply
;
710 httpStatus
= errorReply
->sline
.status();
714 src_addr
= req
->client_addr
;
719 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
721 assert(entry
->mem_obj
!= nullptr);
722 assert (entry
->isEmpty());
723 debugs(4, 4, "storing " << err
<< " in " << *entry
);
725 if (entry
->store_status
!= STORE_PENDING
) {
726 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
728 * If the entry is not STORE_PENDING, then no clients
729 * care about it, and we don't need to generate an
732 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
733 assert(entry
->mem_obj
->nclients
== 0);
738 if (err
->page_id
== TCP_RESET
) {
740 debugs(4, 2, "RSTing this reply");
741 err
->request
->flags
.resetTcp
= true;
745 entry
->storeErrorResponse(err
->BuildHttpReply());
750 errorSend(const Comm::ConnectionPointer
&conn
, ErrorState
* err
)
752 debugs(4, 3, conn
<< ", err=" << err
);
753 assert(Comm::IsConnOpen(conn
));
755 HttpReplyPointer
rep(err
->BuildHttpReply());
757 MemBuf
*mb
= rep
->pack();
758 AsyncCall::Pointer call
= commCbCall(78, 5, "errorSendComplete",
759 CommIoCbPtrFun(&errorSendComplete
, err
));
760 Comm::Write(conn
, mb
, call
);
765 \ingroup ErrorPageAPI
767 * Called by commHandleWrite() after data has been written
768 * to the client socket.
770 \note If there is a callback, the callback is responsible for
771 * closing the FD, otherwise we do it ourselves.
774 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *, size_t size
, Comm::Flag errflag
, int, void *data
)
776 ErrorState
*err
= static_cast<ErrorState
*>(data
);
777 debugs(4, 3, conn
<< ", size=" << size
);
779 if (errflag
!= Comm::ERR_CLOSING
) {
781 debugs(4, 3, "errorSendComplete: callback");
782 err
->callback(conn
->fd
, err
->callback_data
, size
);
784 debugs(4, 3, "errorSendComplete: comm_close");
792 ErrorState::~ErrorState()
794 safe_free(redirect_url
);
796 safe_free(request_hdrs
);
797 wordlistDestroy(&ftp
.server_msg
);
798 safe_free(ftp
.request
);
799 safe_free(ftp
.reply
);
802 if (err_language
!= Config
.errorDefaultLanguage
)
804 safe_free(err_language
);
808 ErrorState::Dump(MemBuf
* mb
)
811 char ntoabuf
[MAX_IPSTRLEN
];
814 /* email subject line */
815 str
.appendf("CacheErrorInfo - %s", errorPageName(type
));
816 mb
->appendf("?subject=%s", rfc1738_escape_part(str
.buf
));
819 str
.appendf("CacheHost: %s\r\n", getMyHostname());
821 str
.appendf("ErrPage: %s\r\n", errorPageName(type
));
824 str
.appendf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
826 str
.append("Err: [none]\r\n", 13);
829 if (auth_user_request
.getRaw() && auth_user_request
->denyMessage())
830 str
.appendf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
832 if (dnsError
.size() > 0)
833 str
.appendf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
836 str
.appendf("TimeStamp: %s\r\n\r\n", Time::FormatRfc1123(squid_curtime
));
839 str
.appendf("ClientIP: %s\r\n", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
841 if (request
&& request
->hier
.host
[0] != '\0') {
842 str
.appendf("ServerIP: %s\r\n", request
->hier
.host
);
845 str
.append("\r\n", 2);
847 str
.append("HTTP Request:\r\n", 15);
849 str
.appendf(SQUIDSBUFPH
" " SQUIDSBUFPH
" %s/%d.%d\n",
850 SQUIDSBUFPRINT(request
->method
.image()),
851 SQUIDSBUFPRINT(request
->url
.path()),
852 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
853 request
->http_ver
.major
, request
->http_ver
.minor
);
854 request
->header
.packInto(&str
);
857 str
.append("\r\n", 2);
861 str
.appendf("FTP Request: %s\r\n", ftp
.request
);
862 str
.appendf("FTP Reply: %s\r\n", (ftp
.reply
? ftp
.reply
:"[none]"));
863 str
.append("FTP Msg: ", 9);
864 wordlistCat(ftp
.server_msg
, &str
);
865 str
.append("\r\n", 2);
868 str
.append("\r\n", 2);
869 mb
->appendf("&body=%s", rfc1738_escape_part(str
.buf
));
874 /// \ingroup ErrorPageInternal
875 #define CVT_BUF_SZ 512
878 ErrorState::compileLogformatCode(Build
&build
)
880 assert(LogformatMagic
.cmp(build
.input
, LogformatMagic
.length()) == 0);
883 const auto logformat
= build
.input
+ LogformatMagic
.length();
885 // Logformat supports undocumented "external" encoding specifications
886 // like [%>h] or "%<a". To preserve the possibility of extending
887 // @Squid{} syntax to non-logformat sequences, we require logformat
888 // sequences to start with '%'. This restriction does not limit
889 // logformat quoting abilities. TODO: Deprecate "external" encoding?
890 if (*logformat
!= '%')
891 throw TexcHere("logformat expressions that do not start with % are not supported");
893 static MemBuf result
;
895 const auto logformatLen
= Format::AssembleOne(logformat
, result
, ale
);
896 assert(logformatLen
> 0);
897 const auto closure
= logformat
+ logformatLen
;
899 throw TexcHere("Missing closing brace (})");
900 build
.output
.append(result
.content(), result
.contentSize());
901 build
.input
= closure
+ 1;
904 noteBuildError("Bad @Squid{logformat} sequence", build
.input
);
907 // we cannot recover reliably so stop interpreting the rest of input
908 const auto remainingSize
= strlen(build
.input
);
909 build
.output
.append(build
.input
, remainingSize
);
910 build
.input
+= remainingSize
;
914 ErrorState::compileLegacyCode(Build
&build
)
917 const char *p
= nullptr; /* takes priority over mb if set */
919 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
920 char ntoabuf
[MAX_IPSTRLEN
];
924 const auto &building_deny_info_url
= build
.building_deny_info_url
; // a change reduction hack
926 const auto letter
= build
.input
[1];
932 if (request
&& request
->auth_user_request
)
933 p
= request
->auth_user_request
->username();
940 // TODO: When/if we get ALE here, pass it as well
941 if (const auto addr
= FindListeningPortAddress(request
.getRaw(), nullptr))
942 mb
.appendf("%s", addr
->toStr(ntoabuf
, MAX_IPSTRLEN
));
948 mb
.appendf("%u", getMyPort());
952 if (building_deny_info_url
) break;
954 const SBuf
&tmp
= Ftp::UrlWith2f(request
.getRaw());
955 mb
.append(tmp
.rawContent(), tmp
.length());
961 if (building_deny_info_url
) break;
962 p
= errorPageName(type
);
966 if (!build
.allowRecursion
)
967 p
= "%D"; // if recursion is not allowed, do not convert
969 auto rawDetail
= detail
->verbose(request
);
970 // XXX: Performance regression. c_str() reallocates
971 const auto compiledDetail
= compileBody(rawDetail
.c_str(), false);
972 mb
.append(compiledDetail
.rawContent(), compiledDetail
.length());
975 if (!mb
.contentSize())
976 mb
.append("[No Error Detail]", 17);
980 mb
.appendf("%d", xerrno
);
985 mb
.appendf("(%d) %s", xerrno
, strerror(xerrno
));
987 mb
.append("[No Error]", 10);
991 if (building_deny_info_url
) break;
992 /* FTP REQUEST LINE */
1000 if (building_deny_info_url
) break;
1001 /* FTP REPLY LINE */
1009 if (building_deny_info_url
) break;
1010 /* FTP SERVER RESPONSE */
1012 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
1014 } else if (ftp
.server_msg
) {
1015 wordlistCat(ftp
.server_msg
, &mb
);
1020 mb
.appendf("%s", getMyHostname());
1025 if (request
->hier
.host
[0] != '\0') // if non-empty string.
1026 p
= request
->hier
.host
;
1028 p
= request
->url
.host();
1029 } else if (!building_deny_info_url
)
1030 p
= "[unknown host]";
1034 mb
.appendf("%s", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
1038 if (request
&& request
->hier
.tcpServer
)
1039 p
= request
->hier
.tcpServer
->remote
.toStr(ntoabuf
,MAX_IPSTRLEN
);
1040 else if (!building_deny_info_url
)
1045 if (building_deny_info_url
) break;
1046 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
1051 if (building_deny_info_url
) break;
1052 if (Config
.errHtmlText
) {
1053 mb
.appendf("%s", Config
.errHtmlText
);
1056 p
= "[not available]";
1060 if (building_deny_info_url
) break;
1062 if (auth_user_request
.getRaw())
1063 p
= auth_user_request
->denyMessage("[not available]");
1065 p
= "[not available]";
1073 const SBuf
&m
= request
->method
.image();
1074 mb
.append(m
.rawContent(), m
.length());
1075 } else if (!building_deny_info_url
)
1076 p
= "[unknown method]";
1080 if (!building_deny_info_url
)
1082 /* [[fallthrough]] */
1084 p
= request
? request
->extacl_message
.termedBuf() : external_acl_message
;
1085 if (!p
&& !building_deny_info_url
)
1086 p
= "[not available]";
1091 mb
.appendf("%u", request
->url
.port());
1092 } else if (!building_deny_info_url
) {
1093 p
= "[unknown port]";
1099 const SBuf
&m
= request
->url
.getScheme().image();
1100 mb
.append(m
.rawContent(), m
.length());
1101 } else if (!building_deny_info_url
) {
1102 p
= "[unknown protocol]";
1107 if (building_deny_info_url
) {
1108 if (request
!= nullptr) {
1109 const SBuf
&tmp
= request
->url
.path();
1110 mb
.append(tmp
.rawContent(), tmp
.length());
1117 mb
.appendf(SQUIDSBUFPH
" " SQUIDSBUFPH
" %s/%d.%d\n",
1118 SQUIDSBUFPRINT(request
->method
.image()),
1119 SQUIDSBUFPRINT(request
->url
.path()),
1120 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
1121 request
->http_ver
.major
, request
->http_ver
.minor
);
1122 request
->header
.packInto(&mb
, true); //hide authorization data
1123 } else if (request_hdrs
) {
1131 /* for backward compat we make %s show the full URL. Drop this in some future release. */
1132 if (building_deny_info_url
) {
1134 const SBuf
&tmp
= request
->effectiveRequestUri();
1135 mb
.append(tmp
.rawContent(), tmp
.length());
1138 debugs(0, DBG_CRITICAL
, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
1140 p
= visible_appname_string
;
1144 if (building_deny_info_url
) {
1145 p
= visible_appname_string
;
1148 /* signature may contain %-escapes, recursion */
1149 if (page_id
!= ERR_SQUID_SIGNATURE
) {
1150 const int saved_id
= page_id
;
1151 page_id
= ERR_SQUID_SIGNATURE
;
1152 const auto signature
= buildBody();
1153 mb
.append(signature
.rawContent(), signature
.length());
1157 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1163 mb
.appendf("%s", Time::FormatHttpd(squid_curtime
));
1167 mb
.appendf("%s", Time::FormatRfc1123(squid_curtime
));
1171 /* Using the fake-https version of absolute-URI so error pages see https:// */
1172 /* even when the url-path cannot be shown as more than '*' */
1174 p
= urlCanonicalFakeHttps(request
.getRaw());
1177 else if (!building_deny_info_url
)
1183 const SBuf
&tmp
= request
->effectiveRequestUri();
1184 mb
.append(tmp
.rawContent(), tmp
.length());
1187 else if (!building_deny_info_url
)
1192 if (Config
.adminEmail
)
1193 mb
.appendf("%s", Config
.adminEmail
);
1194 else if (!building_deny_info_url
)
1199 if (building_deny_info_url
) break;
1200 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
1207 const auto brief
= detail
->brief();
1208 mb
.append(brief
.rawContent(), brief
.length());
1209 } else if (!building_deny_info_url
) {
1210 p
= "[Unknown Error Code]";
1215 if (building_deny_info_url
) break;
1216 if (dnsError
.size() > 0)
1217 p
= dnsError
.termedBuf();
1218 else if (ftp
.cwd_msg
)
1225 if (building_deny_info_url
) break;
1237 if (building_deny_info_url
)
1238 bypassBuildErrorXXX("Unsupported deny_info %code", build
.input
);
1239 else if (letter
!= ';')
1240 bypassBuildErrorXXX("Unsupported error page %code", build
.input
);
1241 // else too many "font-size: 100%;" template errors to report
1243 mb
.append(build
.input
, 2);
1249 p
= mb
.buf
; /* do not use mb after this assignment! */
1253 debugs(4, 3, "%" << letter
<< " --> '" << p
<< "'" );
1258 if (building_deny_info_url
&& !no_urlescape
)
1259 p
= rfc1738_escape_part(p
);
1261 // TODO: Optimize by replacing mb with direct build.output usage.
1262 build
.output
.append(p
, strlen(p
));
1267 ErrorState::validate()
1269 if (const auto urlTemplate
= ErrorPage::IsDenyInfoUri(page_id
)) {
1270 (void)compile(urlTemplate
, true, true);
1272 assert(page_id
> ERR_NONE
);
1273 assert(page_id
< error_page_count
);
1274 (void)compileBody(error_text
[page_id
], true);
1279 ErrorState::BuildHttpReply()
1282 return response_
.getRaw();
1284 HttpReply
*rep
= new HttpReply
;
1285 const char *name
= errorPageName(page_id
);
1286 /* no LMT for error pages; error pages expire immediately */
1288 if (const auto urlTemplate
= ErrorPage::IsDenyInfoUri(page_id
)) {
1290 Http::StatusCode status
= Http::scFound
;
1291 // Use configured 3xx reply status if set.
1293 status
= httpStatus
;
1295 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1296 if (request
&& request
->method
!= Http::METHOD_GET
&& request
->method
!= Http::METHOD_HEAD
&& request
->http_ver
>= Http::ProtocolVersion(1,1))
1297 status
= Http::scTemporaryRedirect
;
1300 rep
->setHeaders(status
, nullptr, "text/html;charset=utf-8", 0, 0, -1);
1303 auto location
= compile(urlTemplate
, true, true);
1304 rep
->header
.putStr(Http::HdrType::LOCATION
, location
.c_str());
1307 httpHeaderPutStrf(&rep
->header
, Http::HdrType::X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
1309 const auto body
= buildBody();
1310 rep
->setHeaders(httpStatus
, nullptr, "text/html;charset=utf-8", body
.length(), 0, -1);
1312 * include some information for downstream caches. Implicit
1313 * replaceable content. This isn't quite sufficient. xerrno is not
1314 * necessarily meaningful to another system, so we really should
1315 * expand it. Additionally, we should identify ourselves. Someone
1316 * might want to know. Someone _will_ want to know OTOH, the first
1317 * X-CACHE-MISS entry should tell us who.
1319 httpHeaderPutStrf(&rep
->header
, Http::HdrType::X_SQUID_ERROR
, "%s %d", name
, xerrno
);
1323 * If error page auto-negotiate is enabled in any way, send the Vary.
1324 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1325 * We have even better reasons though:
1326 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1328 if (!Config
.errorDirectory
) {
1329 /* We 'negotiated' this ONLY from the Accept-Language. */
1330 rep
->header
.delById(Http::HdrType::VARY
);
1331 rep
->header
.putStr(Http::HdrType::VARY
, "Accept-Language");
1334 /* add the Content-Language header according to RFC section 14.12 */
1336 rep
->header
.putStr(Http::HdrType::CONTENT_LANGUAGE
, err_language
);
1338 #endif /* USE_ERROR_LOCALES */
1340 /* default templates are in English */
1341 /* language is known unless error_directory override used */
1342 if (!Config
.errorDirectory
)
1343 rep
->header
.putStr(Http::HdrType::CONTENT_LANGUAGE
, "en");
1346 rep
->body
.set(body
);
1349 // Make sure error codes get back to the client side for logging and
1353 request
->detailError(type
, detail
);
1355 request
->detailError(type
, SysErrorDetail::NewIfAny(xerrno
));
1362 ErrorState::buildBody()
1364 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
1367 /** error_directory option in squid.conf overrides translations.
1368 * Custom errors are always found either in error_directory or the templates directory.
1369 * Otherwise locate the Accept-Language header
1371 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
) {
1372 if (err_language
&& err_language
!= Config
.errorDefaultLanguage
)
1373 safe_free(err_language
);
1375 ErrorPageFile
localeTmpl(err_type_str
[page_id
], static_cast<err_type
>(page_id
));
1376 if (localeTmpl
.loadFor(request
.getRaw())) {
1377 inputLocation
= localeTmpl
.filename
;
1378 assert(localeTmpl
.language());
1379 err_language
= xstrdup(localeTmpl
.language());
1380 return compileBody(localeTmpl
.text(), true);
1383 #endif /* USE_ERR_LOCALES */
1386 * If client-specific error templates are not enabled or available.
1387 * fall back to the old style squid.conf settings.
1390 if (!Config
.errorDirectory
)
1391 err_language
= Config
.errorDefaultLanguage
;
1393 debugs(4, 2, "No existing error page language negotiated for " << this << ". Using default error file.");
1394 return compileBody(error_text
[page_id
], true);
1398 ErrorState::compileBody(const char *input
, bool allowRecursion
)
1400 return compile(input
, false, allowRecursion
);
1404 ErrorState::compile(const char *input
, bool building_deny_info_url
, bool allowRecursion
)
1409 build
.building_deny_info_url
= building_deny_info_url
;
1410 build
.allowRecursion
= allowRecursion
;
1411 build
.input
= input
;
1413 auto blockStart
= build
.input
;
1414 while (const auto letter
= *build
.input
) {
1415 if (letter
== '%') {
1416 build
.output
.append(blockStart
, build
.input
- blockStart
);
1417 compileLegacyCode(build
);
1418 blockStart
= build
.input
;
1420 else if (letter
== '@' && LogformatMagic
.cmp(build
.input
, LogformatMagic
.length()) == 0) {
1421 build
.output
.append(blockStart
, build
.input
- blockStart
);
1422 compileLogformatCode(build
);
1423 blockStart
= build
.input
;
1428 build
.output
.append(blockStart
, build
.input
- blockStart
);
1429 return build
.output
;
1432 /// react to a compile() error
1433 /// \param msg description of what went wrong
1434 /// \param near approximate start of the problematic input
1435 /// \param forceBypass whether detection of this error was introduced late,
1436 /// after old configurations containing this error could have been
1437 /// successfully validated and deployed (i.e. the admin may not be
1438 /// able to fix this newly detected but old problem quickly)
1440 ErrorState::noteBuildError_(const char *msg
, const char *near
, const bool forceBypass
)
1442 using ErrorPage::BuildErrorPrinter
;
1443 const auto runtime
= !starting_up
;
1444 if (runtime
|| forceBypass
) {
1445 // swallow this problem because the admin may not be (and/or the page
1446 // building code is not) ready to handle throwing consequences
1448 static unsigned int seenErrors
= 0;
1451 const auto debugLevel
=
1452 (seenErrors
> 100) ? DBG_DATA
:
1453 (starting_up
|| reconfiguring
) ? DBG_CRITICAL
:
1454 3; // most other errors have been reported as configuration errors
1456 // Error fatality depends on the error context: Reconfiguration errors
1457 // are, like startup ones, DBG_CRITICAL but will never become FATAL.
1458 if (starting_up
&& seenErrors
<= 10)
1459 debugs(4, debugLevel
, "WARNING: The following configuration error will be fatal in future Squid versions");
1461 debugs(4, debugLevel
, "ERROR: " << BuildErrorPrinter(inputLocation
, page_id
, msg
, near
));
1463 throw TexcHere(ToSBuf(BuildErrorPrinter(inputLocation
, page_id
, msg
, near
)));
1467 /* ErrorPage::BuildErrorPrinter */
1470 ErrorPage::BuildErrorPrinter::printLocation(std::ostream
&os
) const {
1471 if (!inputLocation
.isEmpty())
1472 return os
<< inputLocation
;
1474 if (page_id
< ERR_NONE
|| page_id
>= error_page_count
)
1475 return os
<< "[error page " << page_id
<< "]"; // should not happen
1477 if (page_id
< ERR_MAX
)
1478 return os
<< err_type_str
[page_id
];
1480 return os
<< "deny_info " << ErrorDynamicPages
.at(page_id
- ERR_MAX
)->page_name
;
1484 ErrorPage::BuildErrorPrinter::print(std::ostream
&os
) const {
1485 printLocation(os
) << ": " << msg
<< " near ";
1487 // TODO: Add support for prefix printing to Raw
1488 const size_t maxContextLength
= 15; // plus "..."
1489 if (strlen(near
) > maxContextLength
) {
1490 os
.write(near
, maxContextLength
);
1496 // XXX: We should not be converting (inner) exception to text if we are
1497 // going to throw again. See "add arbitrary (re)thrower-supplied details"
1498 // TODO in TextException.h for a long-term in-catcher solution.
1499 if (std::current_exception())
1500 os
<< "\n additional info: " << CurrentException
;
1505 /// add error page template to the global index
1507 ErrorPage::ImportStaticErrorText(const int page_id
, const char *text
, const SBuf
&inputLocation
)
1509 assert(!error_text
[page_id
]);
1510 error_text
[page_id
] = xstrdup(text
);
1511 ValidateStaticError(page_id
, inputLocation
);
1514 /// validate static error page
1516 ErrorPage::ValidateStaticError(const int page_id
, const SBuf
&inputLocation
)
1518 // Supplying nil ALE pointer limits validation to logformat %code
1519 // recognition by Format::Token::parse(). This is probably desirable
1520 // because actual %code assembly is slow and should not affect validation
1521 // when our ALE cannot have any real data (this code is not associated
1522 // with any real transaction).
1523 ErrorState
anErr(err_type(page_id
), Http::scNone
, nullptr, nullptr);
1524 anErr
.inputLocation
= inputLocation
;
1529 operator <<(std::ostream
&os
, const ErrorState
*err
)
1532 os
<< errorPageName(err
->page_id
);