]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/errorpage.cc
88a0b62ce67dd335e2cb878b483db1da0796ef77
2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 04 Error Generation */
13 #include "clients/forward.h"
14 #include "comm/Connection.h"
15 #include "comm/Write.h"
16 #include "err_detail_type.h"
17 #include "errorpage.h"
20 #include "html_quote.h"
21 #include "HttpHeaderTools.h"
22 #include "HttpReply.h"
23 #include "HttpRequest.h"
25 #include "MemObject.h"
27 #include "SquidConfig.h"
33 #include "auth/UserRequest.h"
35 #include "SquidTime.h"
37 #include "ssl/ErrorDetailManager.h"
41 \defgroup ErrorPageInternal Error Page Internals
44 \section Abstract Abstract:
45 * These routines are used to generate error messages to be
46 * sent to clients. The error type is used to select between
47 * the various message formats. (formats are stored in the
48 * Config.errorDirectory)
51 #if !defined(DEFAULT_SQUID_ERROR_DIR)
52 /** Where to look for errors if config path fails.
53 \note Please use ./configure --datadir=/path instead of patching
55 #define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
58 /// \ingroup ErrorPageInternal
59 CBDATA_CLASS_INIT(ErrorState
);
63 /// \ingroup ErrorPageInternal
67 Http::StatusCode page_redirect
;
68 } ErrorDynamicPageInfo
;
70 /* local constant and vars */
73 \ingroup ErrorPageInternal
75 \note hard coded error messages are not appended with %S
76 * automagically to give you more control on the format
79 int type
; /* and page_id */
89 "<div id=\"footer\">\n"
90 "Generated %T by %h (%s)\n"
100 /// \ingroup ErrorPageInternal
101 static std::vector
<ErrorDynamicPageInfo
*> ErrorDynamicPages
;
103 /* local prototypes */
105 /// \ingroup ErrorPageInternal
106 static const int error_hard_text_count
= sizeof(error_hard_text
) / sizeof(*error_hard_text
);
108 /// \ingroup ErrorPageInternal
109 static char **error_text
= NULL
;
111 /// \ingroup ErrorPageInternal
112 static int error_page_count
= 0;
114 /// \ingroup ErrorPageInternal
115 static MemBuf error_stylesheet
;
117 static const char *errorFindHardText(err_type type
);
118 static ErrorDynamicPageInfo
*errorDynamicPageInfoCreate(int id
, const char *page_name
);
119 static void errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
);
120 static IOCB errorSendComplete
;
122 /// \ingroup ErrorPageInternal
123 /// manages an error page template
124 class ErrorPageFile
: public TemplateFile
127 ErrorPageFile(const char *name
, const err_type code
) : TemplateFile(name
,code
) {textBuf
.init();}
129 /// The template text data read from disk
130 const char *text() { return textBuf
.content(); }
133 /// stores the data read from disk to a local buffer
134 virtual bool parse(const char *buf
, int len
, bool) {
136 textBuf
.append(buf
, len
);
140 MemBuf textBuf
; ///< A buffer to store the error page
143 /// \ingroup ErrorPageInternal
144 err_type
&operator++ (err_type
&anErr
)
146 int tmp
= (int)anErr
;
147 anErr
= (err_type
)(++tmp
);
151 /// \ingroup ErrorPageInternal
152 int operator - (err_type
const &anErr
, err_type
const &anErr2
)
154 return (int)anErr
- (int)anErr2
;
158 errorInitialize(void)
162 error_page_count
= ERR_MAX
+ ErrorDynamicPages
.size();
163 error_text
= static_cast<char **>(xcalloc(error_page_count
, sizeof(char *)));
165 for (i
= ERR_NONE
, ++i
; i
< error_page_count
; ++i
) {
166 safe_free(error_text
[i
]);
168 if ((text
= errorFindHardText(i
))) {
170 * Index any hard-coded error text into defaults.
172 error_text
[i
] = xstrdup(text
);
174 } else if (i
< ERR_MAX
) {
176 * Index precompiled fixed template files from one of two sources:
177 * (a) default language translation directory (error_default_language)
178 * (b) admin specified custom directory (error_directory)
180 ErrorPageFile
errTmpl(err_type_str
[i
], i
);
181 error_text
[i
] = errTmpl
.loadDefault() ? xstrdup(errTmpl
.text()) : NULL
;
184 * Index any unknown file names used by deny_info.
186 ErrorDynamicPageInfo
*info
= ErrorDynamicPages
.at(i
- ERR_MAX
);
187 assert(info
&& info
->id
== i
&& info
->page_name
);
189 const char *pg
= info
->page_name
;
190 if (info
->page_redirect
!= Http::scNone
)
191 pg
= info
->page_name
+4;
193 if (strchr(pg
, ':') == NULL
) {
194 /** But only if they are not redirection URL. */
195 ErrorPageFile
errTmpl(pg
, ERR_MAX
);
196 error_text
[i
] = errTmpl
.loadDefault() ? xstrdup(errTmpl
.text()) : NULL
;
201 error_stylesheet
.reset();
203 // look for and load stylesheet into global MemBuf for it.
204 if (Config
.errorStylesheet
) {
205 ErrorPageFile
tmpl("StylesSheet", ERR_MAX
);
206 tmpl
.loadFromFile(Config
.errorStylesheet
);
207 error_stylesheet
.appendf("%s",tmpl
.text());
211 Ssl::errorDetailInitialize();
221 for (i
= ERR_NONE
+ 1; i
< error_page_count
; ++i
)
222 safe_free(error_text
[i
]);
224 safe_free(error_text
);
227 while (!ErrorDynamicPages
.empty()) {
228 errorDynamicPageInfoDestroy(ErrorDynamicPages
.back());
229 ErrorDynamicPages
.pop_back();
232 error_page_count
= 0;
235 Ssl::errorDetailClean();
239 /// \ingroup ErrorPageInternal
241 errorFindHardText(err_type type
)
245 for (i
= 0; i
< error_hard_text_count
; ++i
)
246 if (error_hard_text
[i
].type
== type
)
247 return error_hard_text
[i
].text
;
252 TemplateFile::TemplateFile(const char *name
, const err_type code
): silent(false), wasLoaded(false), templateName(name
), templateCode(code
)
258 TemplateFile::loadDefault()
260 if (loaded()) // already loaded?
263 /** test error_directory configured location */
264 if (Config
.errorDirectory
) {
265 char path
[MAXPATHLEN
];
266 snprintf(path
, sizeof(path
), "%s/%s", Config
.errorDirectory
, templateName
.termedBuf());
271 /** test error_default_language location */
272 if (!loaded() && Config
.errorDefaultLanguage
) {
273 if (!tryLoadTemplate(Config
.errorDefaultLanguage
)) {
274 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "Unable to load default error language files. Reset to backups.");
279 /* test default location if failed (templates == English translation base templates) */
281 tryLoadTemplate("templates");
284 /* giving up if failed */
286 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "WARNING: failed to find or read error text file " << templateName
);
287 parse("Internal Error: Missing Template ", 33, '\0');
288 parse(templateName
.termedBuf(), templateName
.size(), '\0');
295 TemplateFile::tryLoadTemplate(const char *lang
)
299 char path
[MAXPATHLEN
];
300 /* TODO: prep the directory path string to prevent snprintf ... */
301 snprintf(path
, sizeof(path
), "%s/%s/%s",
302 DEFAULT_SQUID_ERROR_DIR
, lang
, templateName
.termedBuf());
303 path
[MAXPATHLEN
-1] = '\0';
305 if (loadFromFile(path
))
309 if ( strlen(lang
) == 2) {
310 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
311 /* use first result. */
312 debugs(4,2, HERE
<< "wildcard fallback errors not coded yet.");
320 TemplateFile::loadFromFile(const char *path
)
326 if (loaded()) // already loaded?
329 fd
= file_open(path
, O_RDONLY
| O_TEXT
);
332 /* with dynamic locale negotiation we may see some failures before a success. */
333 if (!silent
&& templateCode
< TCP_RESET
) {
335 debugs(4, DBG_CRITICAL
, MYNAME
<< "'" << path
<< "': " << xstrerr(xerrno
));
341 while ((len
= FD_READ_METHOD(fd
, buf
, sizeof(buf
))) > 0) {
342 if (!parse(buf
, len
, false)) {
343 debugs(4, DBG_CRITICAL
, MYNAME
<< "parse error while reading template file: " << path
);
352 debugs(4, DBG_CRITICAL
, MYNAME
<< "ERROR: failed to fully read: '" << path
<< "': " << xstrerr(xerrno
));
361 bool strHdrAcptLangGetItem(const String
&hdr
, char *lang
, int langLen
, size_t &pos
)
363 while (pos
< hdr
.size()) {
365 /* skip any initial whitespace. */
366 while (pos
< hdr
.size() && xisspace(hdr
[pos
]))
370 * Header value format:
371 * - sequence of whitespace delimited tags
372 * - each tag may suffix with ';'.* which we can ignore.
373 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
374 * with preference given to an exact match.
376 bool invalid_byte
= false;
378 while (pos
< hdr
.size() && hdr
[pos
] != ';' && hdr
[pos
] != ',' && !xisspace(hdr
[pos
]) && dt
< (lang
+ (langLen
-1)) ) {
380 #if USE_HTTP_VIOLATIONS
381 // if accepting violations we may as well accept some broken browsers
382 // which may send us the right code, wrong ISO formatting.
387 *dt
= xtolower(hdr
[pos
]);
388 // valid codes only contain A-Z, hyphen (-) and *
389 if (*dt
!= '-' && *dt
!= '*' && (*dt
< 'a' || *dt
> 'z') )
392 ++dt
; // move to next destination byte.
396 *dt
= '\0'; // nul-terminated the filename content string before system use.
398 // if we terminated the tag on garbage or ';' we need to skip to the next ',' or end of header.
399 while (pos
< hdr
.size() && hdr
[pos
] != ',')
402 if (pos
< hdr
.size() && hdr
[pos
] == ',')
405 debugs(4, 9, "STATE: lang=" << lang
<< ", pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
407 /* if we found anything we might use, try it. */
408 if (*lang
!= '\0' && !invalid_byte
)
415 TemplateFile::loadFor(const HttpRequest
*request
)
420 if (loaded()) // already loaded?
423 if (!request
|| !request
->header
.getList(Http::HdrType::ACCEPT_LANGUAGE
, &hdr
) )
427 size_t pos
= 0; // current parsing position in header string
429 debugs(4, 6, HERE
<< "Testing Header: '" << hdr
<< "'");
431 while ( strHdrAcptLangGetItem(hdr
, lang
, 256, pos
) ) {
433 /* wildcard uses the configured default language */
434 if (lang
[0] == '*' && lang
[1] == '\0') {
435 debugs(4, 6, HERE
<< "Found language '" << lang
<< "'. Using configured default.");
439 debugs(4, 6, HERE
<< "Found language '" << lang
<< "', testing for available template");
441 if (tryLoadTemplate(lang
)) {
442 /* store the language we found for the Content-Language reply header */
445 } else if (Config
.errorLogMissingLanguages
) {
446 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << lang
);
454 /// \ingroup ErrorPageInternal
455 static ErrorDynamicPageInfo
*
456 errorDynamicPageInfoCreate(int id
, const char *page_name
)
458 ErrorDynamicPageInfo
*info
= new ErrorDynamicPageInfo
;
460 info
->page_name
= xstrdup(page_name
);
461 info
->page_redirect
= static_cast<Http::StatusCode
>(atoi(page_name
));
463 /* WARNING on redirection status:
464 * 2xx are permitted, but not documented officially.
465 * - might be useful for serving static files (PAC etc) in special cases
466 * 3xx require a URL suitable for Location: header.
467 * - the current design does not allow for a Location: URI as well as a local file template
468 * although this possibility is explicitly permitted in the specs.
469 * 4xx-5xx require a local file template.
470 * - sending Location: on these codes with no body is invalid by the specs.
471 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
472 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
474 if (info
->page_redirect
== Http::scNone
)
475 ; // special case okay.
476 else if (info
->page_redirect
< 200 || info
->page_redirect
> 599) {
478 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
480 } else if ( /* >= 200 && */ info
->page_redirect
< 300 && strchr(&(page_name
[4]), ':')) {
481 // 2xx require a local template file
482 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
484 } else if (info
->page_redirect
>= 300 && info
->page_redirect
<= 399 && !strchr(&(page_name
[4]), ':')) {
485 // 3xx require an absolute URL
486 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a URL on '" << page_name
<< "'");
488 } else if (info
->page_redirect
>= 400 /* && <= 599 */ && strchr(&(page_name
[4]), ':')) {
489 // 4xx/5xx require a local template file
490 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
498 /// \ingroup ErrorPageInternal
500 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
)
503 safe_free(info
->page_name
);
507 /// \ingroup ErrorPageInternal
509 errorPageId(const char *page_name
)
511 for (int i
= 0; i
< ERR_MAX
; ++i
) {
512 if (strcmp(err_type_str
[i
], page_name
) == 0)
516 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); ++j
) {
517 if (strcmp(ErrorDynamicPages
[j
]->page_name
, page_name
) == 0)
525 errorReservePageId(const char *page_name
)
527 ErrorDynamicPageInfo
*info
;
528 int id
= errorPageId(page_name
);
530 if (id
== ERR_NONE
) {
531 info
= errorDynamicPageInfoCreate(ERR_MAX
+ ErrorDynamicPages
.size(), page_name
);
532 ErrorDynamicPages
.push_back(info
);
539 /// \ingroup ErrorPageInternal
541 errorPageName(int pageId
)
543 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
544 return err_type_str
[pageId
];
546 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
547 return ErrorDynamicPages
[pageId
- ERR_MAX
]->page_name
;
549 return "ERR_UNKNOWN"; /* should not happen */
553 ErrorState::NewForwarding(err_type type
, HttpRequest
*request
)
556 const Http::StatusCode status
= request
->flags
.needValidation
?
557 Http::scGatewayTimeout
: Http::scServiceUnavailable
;
558 return new ErrorState(type
, status
, request
);
561 ErrorState::ErrorState(err_type t
, Http::StatusCode status
, HttpRequest
* req
) :
567 auth_user_request (NULL
),
584 detailCode(ERR_DETAIL_NONE
)
586 memset(&ftp
, 0, sizeof(ftp
));
588 if (page_id
>= ERR_MAX
&& ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
!= Http::scNone
)
589 httpStatus
= ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
;
593 HTTPMSGLOCK(request
);
594 src_addr
= req
->client_addr
;
599 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
601 assert(entry
->mem_obj
!= NULL
);
602 assert (entry
->isEmpty());
603 debugs(4, 4, "Creating an error page for entry " << entry
<<
604 " with errorstate " << err
<<
605 " page id " << err
->page_id
);
607 if (entry
->store_status
!= STORE_PENDING
) {
608 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
610 * If the entry is not STORE_PENDING, then no clients
611 * care about it, and we don't need to generate an
614 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
615 assert(entry
->mem_obj
->nclients
== 0);
620 if (err
->page_id
== TCP_RESET
) {
622 debugs(4, 2, "RSTing this reply");
623 err
->request
->flags
.resetTcp
= true;
627 entry
->storeErrorResponse(err
->BuildHttpReply());
632 errorSend(const Comm::ConnectionPointer
&conn
, ErrorState
* err
)
635 debugs(4, 3, HERE
<< conn
<< ", err=" << err
);
636 assert(Comm::IsConnOpen(conn
));
638 rep
= err
->BuildHttpReply();
640 MemBuf
*mb
= rep
->pack();
641 AsyncCall::Pointer call
= commCbCall(78, 5, "errorSendComplete",
642 CommIoCbPtrFun(&errorSendComplete
, err
));
643 Comm::Write(conn
, mb
, call
);
650 \ingroup ErrorPageAPI
652 * Called by commHandleWrite() after data has been written
653 * to the client socket.
655 \note If there is a callback, the callback is responsible for
656 * closing the FD, otherwise we do it ourselves.
659 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *, size_t size
, Comm::Flag errflag
, int, void *data
)
661 ErrorState
*err
= static_cast<ErrorState
*>(data
);
662 debugs(4, 3, HERE
<< conn
<< ", size=" << size
);
664 if (errflag
!= Comm::ERR_CLOSING
) {
666 debugs(4, 3, "errorSendComplete: callback");
667 err
->callback(conn
->fd
, err
->callback_data
, size
);
669 debugs(4, 3, "errorSendComplete: comm_close");
677 ErrorState::~ErrorState()
679 HTTPMSGUNLOCK(request
);
680 safe_free(redirect_url
);
682 safe_free(request_hdrs
);
683 wordlistDestroy(&ftp
.server_msg
);
684 safe_free(ftp
.request
);
685 safe_free(ftp
.reply
);
687 auth_user_request
= NULL
;
691 if (err_language
!= Config
.errorDefaultLanguage
)
693 safe_free(err_language
);
700 ErrorState::Dump(MemBuf
* mb
)
703 char ntoabuf
[MAX_IPSTRLEN
];
706 /* email subject line */
707 str
.appendf("CacheErrorInfo - %s", errorPageName(type
));
708 mb
->appendf("?subject=%s", rfc1738_escape_part(str
.buf
));
711 str
.appendf("CacheHost: %s\r\n", getMyHostname());
713 str
.appendf("ErrPage: %s\r\n", errorPageName(type
));
716 str
.appendf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
718 str
.append("Err: [none]\r\n", 13);
721 if (auth_user_request
.getRaw() && auth_user_request
->denyMessage())
722 str
.appendf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
724 if (dnsError
.size() > 0)
725 str
.appendf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
728 str
.appendf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
731 str
.appendf("ClientIP: %s\r\n", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
733 if (request
&& request
->hier
.host
[0] != '\0') {
734 str
.appendf("ServerIP: %s\r\n", request
->hier
.host
);
737 str
.append("\r\n", 2);
739 str
.append("HTTP Request:\r\n", 15);
741 str
.appendf(SQUIDSBUFPH
" " SQUIDSBUFPH
" %s/%d.%d\n",
742 SQUIDSBUFPRINT(request
->method
.image()),
743 SQUIDSBUFPRINT(request
->url
.path()),
744 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
745 request
->http_ver
.major
, request
->http_ver
.minor
);
746 request
->header
.packInto(&str
);
749 str
.append("\r\n", 2);
753 str
.appendf("FTP Request: %s\r\n", ftp
.request
);
754 str
.appendf("FTP Reply: %s\r\n", (ftp
.reply
? ftp
.reply
:"[none]"));
755 str
.append("FTP Msg: ", 9);
756 wordlistCat(ftp
.server_msg
, &str
);
757 str
.append("\r\n", 2);
760 str
.append("\r\n", 2);
761 mb
->appendf("&body=%s", rfc1738_escape_part(str
.buf
));
766 /// \ingroup ErrorPageInternal
767 #define CVT_BUF_SZ 512
770 ErrorState::Convert(char token
, bool building_deny_info_url
, bool allowRecursion
)
773 const char *p
= NULL
; /* takes priority over mb if set */
775 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
776 char ntoabuf
[MAX_IPSTRLEN
];
784 if (request
&& request
->auth_user_request
!= NULL
)
785 p
= request
->auth_user_request
->username();
792 mb
.appendf("%u", getMyPort());
796 if (building_deny_info_url
) break;
798 const SBuf
&tmp
= Ftp::UrlWith2f(request
);
799 mb
.append(tmp
.rawContent(), tmp
.length());
805 if (building_deny_info_url
) break;
806 p
= errorPageName(type
);
811 p
= "%D"; // if recursion is not allowed, do not convert
813 // currently only SSL error details implemented
815 detail
->useRequest(request
);
816 const String
&errDetail
= detail
->toString();
817 if (errDetail
.size() > 0) {
818 MemBuf
*detail_mb
= ConvertText(errDetail
.termedBuf(), false);
819 mb
.append(detail_mb
->content(), detail_mb
->contentSize());
825 if (!mb
.contentSize())
826 mb
.append("[No Error Detail]", 17);
830 mb
.appendf("%d", xerrno
);
835 mb
.appendf("(%d) %s", xerrno
, strerror(xerrno
));
837 mb
.append("[No Error]", 10);
841 if (building_deny_info_url
) break;
842 /* FTP REQUEST LINE */
850 if (building_deny_info_url
) break;
859 if (building_deny_info_url
) break;
860 /* FTP SERVER RESPONSE */
862 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
864 } else if (ftp
.server_msg
) {
865 wordlistCat(ftp
.server_msg
, &mb
);
870 mb
.appendf("%s", getMyHostname());
875 if (request
->hier
.host
[0] != '\0') // if non-empty string.
876 p
= request
->hier
.host
;
878 p
= request
->url
.host();
879 } else if (!building_deny_info_url
)
880 p
= "[unknown host]";
884 mb
.appendf("%s", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
888 if (request
&& request
->hier
.tcpServer
!= NULL
)
889 p
= request
->hier
.tcpServer
->remote
.toStr(ntoabuf
,MAX_IPSTRLEN
);
890 else if (!building_deny_info_url
)
895 if (building_deny_info_url
) break;
896 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
901 if (building_deny_info_url
) break;
902 if (Config
.errHtmlText
) {
903 mb
.appendf("%s", Config
.errHtmlText
);
906 p
= "[not available]";
910 if (building_deny_info_url
) break;
912 if (auth_user_request
.getRaw())
913 p
= auth_user_request
->denyMessage("[not available]");
915 p
= "[not available]";
923 const SBuf
&m
= request
->method
.image();
924 mb
.append(m
.rawContent(), m
.length());
925 } else if (!building_deny_info_url
)
926 p
= "[unknown method]";
930 if (!building_deny_info_url
)
933 p
= request
? request
->extacl_message
.termedBuf() : external_acl_message
;
934 if (!p
&& !building_deny_info_url
)
935 p
= "[not available]";
940 mb
.appendf("%u", request
->url
.port());
941 } else if (!building_deny_info_url
) {
942 p
= "[unknown port]";
948 const SBuf
&m
= request
->url
.getScheme().image();
949 mb
.append(m
.rawContent(), m
.length());
950 } else if (!building_deny_info_url
) {
951 p
= "[unknown protocol]";
956 if (building_deny_info_url
) {
957 if (request
!= NULL
) {
958 SBuf tmp
= request
->url
.path();
965 if (request
!= NULL
) {
966 mb
.appendf(SQUIDSBUFPH
" " SQUIDSBUFPH
" %s/%d.%d\n",
967 SQUIDSBUFPRINT(request
->method
.image()),
968 SQUIDSBUFPRINT(request
->url
.path()),
969 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
970 request
->http_ver
.major
, request
->http_ver
.minor
);
971 request
->header
.packInto(&mb
, true); //hide authorization data
972 } else if (request_hdrs
) {
980 /* for backward compat we make %s show the full URL. Drop this in some future release. */
981 if (building_deny_info_url
) {
983 const SBuf
&tmp
= request
->effectiveRequestUri();
984 mb
.append(tmp
.rawContent(), tmp
.length());
987 debugs(0, DBG_CRITICAL
, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
989 p
= visible_appname_string
;
993 if (building_deny_info_url
) {
994 p
= visible_appname_string
;
997 /* signature may contain %-escapes, recursion */
998 if (page_id
!= ERR_SQUID_SIGNATURE
) {
999 const int saved_id
= page_id
;
1000 page_id
= ERR_SQUID_SIGNATURE
;
1001 MemBuf
*sign_mb
= BuildContent();
1002 mb
.append(sign_mb
->content(), sign_mb
->contentSize());
1008 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1014 mb
.appendf("%s", Time::FormatHttpd(squid_curtime
));
1018 mb
.appendf("%s", mkrfc1123(squid_curtime
));
1022 /* Using the fake-https version of absolute-URI so error pages see https:// */
1023 /* even when the url-path cannot be shown as more than '*' */
1025 p
= urlCanonicalFakeHttps(request
);
1028 else if (!building_deny_info_url
)
1034 const SBuf
&tmp
= request
->effectiveRequestUri();
1035 mb
.append(tmp
.rawContent(), tmp
.length());
1038 else if (!building_deny_info_url
)
1043 if (Config
.adminEmail
)
1044 mb
.appendf("%s", Config
.adminEmail
);
1045 else if (!building_deny_info_url
)
1050 if (building_deny_info_url
) break;
1051 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
1059 mb
.appendf("%s", detail
->errorName());
1062 if (!building_deny_info_url
)
1063 p
= "[Unknown Error Code]";
1067 if (building_deny_info_url
) break;
1068 if (dnsError
.size() > 0)
1069 p
= dnsError
.termedBuf();
1070 else if (ftp
.cwd_msg
)
1077 if (building_deny_info_url
) break;
1089 mb
.appendf("%%%c", token
);
1095 p
= mb
.buf
; /* do not use mb after this assignment! */
1099 debugs(4, 3, "errorConvert: %%" << token
<< " --> '" << p
<< "'" );
1104 if (building_deny_info_url
&& !no_urlescape
)
1105 p
= rfc1738_escape_part(p
);
1111 ErrorState::DenyInfoLocation(const char *name
, HttpRequest
*, MemBuf
&result
)
1113 char const *m
= name
;
1118 m
+= 4; // skip "3xx:"
1120 while ((p
= strchr(m
, '%'))) {
1121 result
.append(m
, p
- m
); /* copy */
1122 t
= Convert(*++p
, true, true); /* convert */
1123 result
.appendf("%s", t
); /* copy */
1124 m
= p
+ 1; /* advance */
1128 result
.appendf("%s", m
); /* copy tail */
1130 assert((size_t)result
.contentSize() == strlen(result
.content()));
1134 ErrorState::BuildHttpReply()
1136 HttpReply
*rep
= new HttpReply
;
1137 const char *name
= errorPageName(page_id
);
1138 /* no LMT for error pages; error pages expire immediately */
1140 if (name
[0] == '3' || (name
[0] != '2' && name
[0] != '4' && name
[0] != '5' && strchr(name
, ':'))) {
1142 Http::StatusCode status
= Http::scFound
;
1143 // Use configured 3xx reply status if set.
1145 status
= httpStatus
;
1147 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1148 if (request
!= NULL
&& request
->method
!= Http::METHOD_GET
&& request
->method
!= Http::METHOD_HEAD
&& request
->http_ver
>= Http::ProtocolVersion(1,1))
1149 status
= Http::scTemporaryRedirect
;
1152 rep
->setHeaders(status
, NULL
, "text/html;charset=utf-8", 0, 0, -1);
1155 MemBuf redirect_location
;
1156 redirect_location
.init();
1157 DenyInfoLocation(name
, request
, redirect_location
);
1158 httpHeaderPutStrf(&rep
->header
, Http::HdrType::LOCATION
, "%s", redirect_location
.content() );
1161 httpHeaderPutStrf(&rep
->header
, Http::HdrType::X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
1163 MemBuf
*content
= BuildContent();
1164 rep
->setHeaders(httpStatus
, NULL
, "text/html;charset=utf-8", content
->contentSize(), 0, -1);
1166 * include some information for downstream caches. Implicit
1167 * replaceable content. This isn't quite sufficient. xerrno is not
1168 * necessarily meaningful to another system, so we really should
1169 * expand it. Additionally, we should identify ourselves. Someone
1170 * might want to know. Someone _will_ want to know OTOH, the first
1171 * X-CACHE-MISS entry should tell us who.
1173 httpHeaderPutStrf(&rep
->header
, Http::HdrType::X_SQUID_ERROR
, "%s %d", name
, xerrno
);
1177 * If error page auto-negotiate is enabled in any way, send the Vary.
1178 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1179 * We have even better reasons though:
1180 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1182 if (!Config
.errorDirectory
) {
1183 /* We 'negotiated' this ONLY from the Accept-Language. */
1184 rep
->header
.delById(Http::HdrType::VARY
);
1185 rep
->header
.putStr(Http::HdrType::VARY
, "Accept-Language");
1188 /* add the Content-Language header according to RFC section 14.12 */
1190 rep
->header
.putStr(Http::HdrType::CONTENT_LANGUAGE
, err_language
);
1192 #endif /* USE_ERROR_LOCALES */
1194 /* default templates are in English */
1195 /* language is known unless error_directory override used */
1196 if (!Config
.errorDirectory
)
1197 rep
->header
.putStr(Http::HdrType::CONTENT_LANGUAGE
, "en");
1200 rep
->body
.setMb(content
);
1201 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1204 // Make sure error codes get back to the client side for logging and
1207 int edc
= ERR_DETAIL_NONE
; // error detail code
1210 edc
= detail
->errorNo();
1217 request
->detailError(type
, edc
);
1224 ErrorState::BuildContent()
1226 const char *m
= NULL
;
1228 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
1231 ErrorPageFile
*localeTmpl
= NULL
;
1233 /** error_directory option in squid.conf overrides translations.
1234 * Custom errors are always found either in error_directory or the templates directory.
1235 * Otherwise locate the Accept-Language header
1237 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
) {
1238 if (err_language
&& err_language
!= Config
.errorDefaultLanguage
)
1239 safe_free(err_language
);
1241 localeTmpl
= new ErrorPageFile(err_type_str
[page_id
], static_cast<err_type
>(page_id
));
1242 if (localeTmpl
->loadFor(request
)) {
1243 m
= localeTmpl
->text();
1244 assert(localeTmpl
->language());
1245 err_language
= xstrdup(localeTmpl
->language());
1248 #endif /* USE_ERR_LOCALES */
1251 * If client-specific error templates are not enabled or available.
1252 * fall back to the old style squid.conf settings.
1255 m
= error_text
[page_id
];
1257 if (!Config
.errorDirectory
)
1258 err_language
= Config
.errorDefaultLanguage
;
1260 debugs(4, 2, HERE
<< "No existing error page language negotiated for " << errorPageName(page_id
) << ". Using default error file.");
1263 MemBuf
*result
= ConvertText(m
, true);
1271 MemBuf
*ErrorState::ConvertText(const char *text
, bool allowRecursion
)
1273 MemBuf
*content
= new MemBuf
;
1275 const char *m
= text
;
1279 while ((p
= strchr(m
, '%'))) {
1280 content
->append(m
, p
- m
); /* copy */
1281 const char *t
= Convert(*++p
, false, allowRecursion
); /* convert */
1282 content
->appendf("%s", t
); /* copy */
1283 m
= p
+ 1; /* advance */
1287 content
->appendf("%s", m
); /* copy tail */
1289 content
->terminate();
1291 assert((size_t)content
->contentSize() == strlen(content
->content()));