]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/errorpage.cc
2 * Copyright (C) 1996-2015 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"
17 #include "err_detail_type.h"
18 #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
)
334 debugs(4, DBG_CRITICAL
, HERE
<< "'" << path
<< "': " << xstrerror());
339 while ((len
= FD_READ_METHOD(fd
, buf
, sizeof(buf
))) > 0) {
340 if (!parse(buf
, len
, false)) {
341 debugs(4, DBG_CRITICAL
, HERE
<< " parse error while reading template file: " << path
);
349 debugs(4, DBG_CRITICAL
, HERE
<< "failed to fully read: '" << path
<< "': " << xstrerror());
358 bool strHdrAcptLangGetItem(const String
&hdr
, char *lang
, int langLen
, size_t &pos
)
360 while (pos
< hdr
.size()) {
363 /* skip any initial whitespace. */
364 while (pos
< hdr
.size() && xisspace(hdr
[pos
]))
368 * Header value format:
369 * - sequence of whitespace delimited tags
370 * - each tag may suffix with ';'.* which we can ignore.
371 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
372 * with preference given to an exact match.
374 bool invalid_byte
= false;
375 while (pos
< hdr
.size() && hdr
[pos
] != ';' && hdr
[pos
] != ',' && !xisspace(hdr
[pos
]) && dt
< (lang
+ (langLen
-1)) ) {
377 #if USE_HTTP_VIOLATIONS
378 // if accepting violations we may as well accept some broken browsers
379 // which may send us the right code, wrong ISO formatting.
384 *dt
= xtolower(hdr
[pos
]);
385 // valid codes only contain A-Z, hyphen (-) and *
386 if (*dt
!= '-' && *dt
!= '*' && (*dt
< 'a' || *dt
> 'z') )
389 ++dt
; // move to next destination byte.
393 *dt
= '\0'; // nul-terminated the filename content string before system use.
396 // if we terminated the tag on garbage or ';' we need to skip to the next ',' or end of header.
397 while (pos
< hdr
.size() && hdr
[pos
] != ',')
400 if (pos
< hdr
.size() && hdr
[pos
] == ',')
403 debugs(4, 9, HERE
<< "STATE: dt='" << dt
<< "', lang='" << lang
<< "', pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
405 /* if we found anything we might use, try it. */
406 if (*lang
!= '\0' && !invalid_byte
)
413 TemplateFile::loadFor(const HttpRequest
*request
)
418 if (loaded()) // already loaded?
421 if (!request
|| !request
->header
.getList(HDR_ACCEPT_LANGUAGE
, &hdr
) )
425 size_t pos
= 0; // current parsing position in header string
427 debugs(4, 6, HERE
<< "Testing Header: '" << hdr
<< "'");
429 while ( strHdrAcptLangGetItem(hdr
, lang
, 256, pos
) ) {
431 /* wildcard uses the configured default language */
432 if (lang
[0] == '*' && lang
[1] == '\0') {
433 debugs(4, 6, HERE
<< "Found language '" << lang
<< "'. Using configured default.");
437 debugs(4, 6, HERE
<< "Found language '" << lang
<< "', testing for available template");
439 if (tryLoadTemplate(lang
)) {
440 /* store the language we found for the Content-Language reply header */
443 } else if (Config
.errorLogMissingLanguages
) {
444 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << lang
);
452 /// \ingroup ErrorPageInternal
453 static ErrorDynamicPageInfo
*
454 errorDynamicPageInfoCreate(int id
, const char *page_name
)
456 ErrorDynamicPageInfo
*info
= new ErrorDynamicPageInfo
;
458 info
->page_name
= xstrdup(page_name
);
459 info
->page_redirect
= static_cast<Http::StatusCode
>(atoi(page_name
));
461 /* WARNING on redirection status:
462 * 2xx are permitted, but not documented officially.
463 * - might be useful for serving static files (PAC etc) in special cases
464 * 3xx require a URL suitable for Location: header.
465 * - the current design does not allow for a Location: URI as well as a local file template
466 * although this possibility is explicitly permitted in the specs.
467 * 4xx-5xx require a local file template.
468 * - sending Location: on these codes with no body is invalid by the specs.
469 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
470 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
472 if (info
->page_redirect
== Http::scNone
)
473 ; // special case okay.
474 else if (info
->page_redirect
< 200 || info
->page_redirect
> 599) {
476 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
478 } else if ( /* >= 200 && */ info
->page_redirect
< 300 && strchr(&(page_name
[4]), ':')) {
479 // 2xx require a local template file
480 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
482 } else if (info
->page_redirect
>= 300 && info
->page_redirect
<= 399 && !strchr(&(page_name
[4]), ':')) {
483 // 3xx require an absolute URL
484 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a URL on '" << page_name
<< "'");
486 } else if (info
->page_redirect
>= 400 /* && <= 599 */ && strchr(&(page_name
[4]), ':')) {
487 // 4xx/5xx require a local template file
488 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
496 /// \ingroup ErrorPageInternal
498 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
)
501 safe_free(info
->page_name
);
505 /// \ingroup ErrorPageInternal
507 errorPageId(const char *page_name
)
509 for (int i
= 0; i
< ERR_MAX
; ++i
) {
510 if (strcmp(err_type_str
[i
], page_name
) == 0)
514 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); ++j
) {
515 if (strcmp(ErrorDynamicPages
[j
]->page_name
, page_name
) == 0)
523 errorReservePageId(const char *page_name
)
525 ErrorDynamicPageInfo
*info
;
526 int id
= errorPageId(page_name
);
528 if (id
== ERR_NONE
) {
529 info
= errorDynamicPageInfoCreate(ERR_MAX
+ ErrorDynamicPages
.size(), page_name
);
530 ErrorDynamicPages
.push_back(info
);
537 /// \ingroup ErrorPageInternal
539 errorPageName(int pageId
)
541 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
542 return err_type_str
[pageId
];
544 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
545 return ErrorDynamicPages
[pageId
- ERR_MAX
]->page_name
;
547 return "ERR_UNKNOWN"; /* should not happen */
551 ErrorState::NewForwarding(err_type type
, HttpRequest
*request
)
554 const Http::StatusCode status
= request
->flags
.needValidation
?
555 Http::scGatewayTimeout
: Http::scServiceUnavailable
;
556 return new ErrorState(type
, status
, request
);
559 ErrorState::ErrorState(err_type t
, Http::StatusCode status
, HttpRequest
* req
) :
565 auth_user_request (NULL
),
582 detailCode(ERR_DETAIL_NONE
)
584 memset(&ftp
, 0, sizeof(ftp
));
586 if (page_id
>= ERR_MAX
&& ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
!= Http::scNone
)
587 httpStatus
= ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
;
591 HTTPMSGLOCK(request
);
592 src_addr
= req
->client_addr
;
597 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
599 assert(entry
->mem_obj
!= NULL
);
600 assert (entry
->isEmpty());
601 debugs(4, 4, "Creating an error page for entry " << entry
<<
602 " with errorstate " << err
<<
603 " page id " << err
->page_id
);
605 if (entry
->store_status
!= STORE_PENDING
) {
606 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
608 * If the entry is not STORE_PENDING, then no clients
609 * care about it, and we don't need to generate an
612 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
613 assert(entry
->mem_obj
->nclients
== 0);
618 if (err
->page_id
== TCP_RESET
) {
620 debugs(4, 2, "RSTing this reply");
621 err
->request
->flags
.resetTcp
= true;
625 entry
->storeErrorResponse(err
->BuildHttpReply());
630 errorSend(const Comm::ConnectionPointer
&conn
, ErrorState
* err
)
633 debugs(4, 3, HERE
<< conn
<< ", err=" << err
);
634 assert(Comm::IsConnOpen(conn
));
636 rep
= err
->BuildHttpReply();
638 MemBuf
*mb
= rep
->pack();
639 AsyncCall::Pointer call
= commCbCall(78, 5, "errorSendComplete",
640 CommIoCbPtrFun(&errorSendComplete
, err
));
641 Comm::Write(conn
, mb
, call
);
648 \ingroup ErrorPageAPI
650 * Called by commHandleWrite() after data has been written
651 * to the client socket.
653 \note If there is a callback, the callback is responsible for
654 * closing the FD, otherwise we do it ourselves.
657 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *, size_t size
, Comm::Flag errflag
, int, void *data
)
659 ErrorState
*err
= static_cast<ErrorState
*>(data
);
660 debugs(4, 3, HERE
<< conn
<< ", size=" << size
);
662 if (errflag
!= Comm::ERR_CLOSING
) {
664 debugs(4, 3, "errorSendComplete: callback");
665 err
->callback(conn
->fd
, err
->callback_data
, size
);
667 debugs(4, 3, "errorSendComplete: comm_close");
675 ErrorState::~ErrorState()
677 HTTPMSGUNLOCK(request
);
678 safe_free(redirect_url
);
680 safe_free(request_hdrs
);
681 wordlistDestroy(&ftp
.server_msg
);
682 safe_free(ftp
.request
);
683 safe_free(ftp
.reply
);
685 auth_user_request
= NULL
;
689 if (err_language
!= Config
.errorDefaultLanguage
)
691 safe_free(err_language
);
698 ErrorState::Dump(MemBuf
* mb
)
701 char ntoabuf
[MAX_IPSTRLEN
];
704 /* email subject line */
705 str
.appendf("CacheErrorInfo - %s", errorPageName(type
));
706 mb
->appendf("?subject=%s", rfc1738_escape_part(str
.buf
));
709 str
.appendf("CacheHost: %s\r\n", getMyHostname());
711 str
.appendf("ErrPage: %s\r\n", errorPageName(type
));
714 str
.appendf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
716 str
.append("Err: [none]\r\n", 13);
719 if (auth_user_request
.getRaw() && auth_user_request
->denyMessage())
720 str
.appendf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
722 if (dnsError
.size() > 0)
723 str
.appendf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
726 str
.appendf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
729 str
.appendf("ClientIP: %s\r\n", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
731 if (request
&& request
->hier
.host
[0] != '\0') {
732 str
.appendf("ServerIP: %s\r\n", request
->hier
.host
);
735 str
.append("\r\n", 2);
737 str
.append("HTTP Request:\r\n", 15);
739 str
.appendf(SQUIDSBUFPH
" " SQUIDSBUFPH
" %s/%d.%d\n",
740 SQUIDSBUFPRINT(request
->method
.image()),
741 SQUIDSBUFPRINT(request
->url
.path()),
742 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
743 request
->http_ver
.major
, request
->http_ver
.minor
);
744 request
->header
.packInto(&str
);
747 str
.append("\r\n", 2);
751 str
.appendf("FTP Request: %s\r\n", ftp
.request
);
752 str
.appendf("FTP Reply: %s\r\n", (ftp
.reply
? ftp
.reply
:"[none]"));
753 str
.append("FTP Msg: ", 9);
754 wordlistCat(ftp
.server_msg
, &str
);
755 str
.append("\r\n", 2);
758 str
.append("\r\n", 2);
759 mb
->appendf("&body=%s", rfc1738_escape_part(str
.buf
));
764 /// \ingroup ErrorPageInternal
765 #define CVT_BUF_SZ 512
768 ErrorState::Convert(char token
, bool building_deny_info_url
, bool allowRecursion
)
771 const char *p
= NULL
; /* takes priority over mb if set */
773 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
774 char ntoabuf
[MAX_IPSTRLEN
];
782 if (request
&& request
->auth_user_request
!= NULL
)
783 p
= request
->auth_user_request
->username();
790 mb
.appendf("%u", getMyPort());
794 if (building_deny_info_url
) break;
796 const SBuf
&tmp
= Ftp::UrlWith2f(request
);
797 mb
.append(tmp
.rawContent(), tmp
.length());
803 if (building_deny_info_url
) break;
804 p
= errorPageName(type
);
809 p
= "%D"; // if recursion is not allowed, do not convert
811 // currently only SSL error details implemented
813 detail
->useRequest(request
);
814 const String
&errDetail
= detail
->toString();
815 if (errDetail
.size() > 0) {
816 MemBuf
*detail_mb
= ConvertText(errDetail
.termedBuf(), false);
817 mb
.append(detail_mb
->content(), detail_mb
->contentSize());
823 if (!mb
.contentSize())
824 mb
.append("[No Error Detail]", 17);
828 mb
.appendf("%d", xerrno
);
833 mb
.appendf("(%d) %s", xerrno
, strerror(xerrno
));
835 mb
.append("[No Error]", 10);
839 if (building_deny_info_url
) break;
840 /* FTP REQUEST LINE */
848 if (building_deny_info_url
) break;
857 if (building_deny_info_url
) break;
858 /* FTP SERVER RESPONSE */
860 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
862 } else if (ftp
.server_msg
) {
863 wordlistCat(ftp
.server_msg
, &mb
);
868 mb
.appendf("%s", getMyHostname());
873 if (request
->hier
.host
[0] != '\0') // if non-empty string.
874 p
= request
->hier
.host
;
876 p
= request
->url
.host();
877 } else if (!building_deny_info_url
)
878 p
= "[unknown host]";
882 mb
.appendf("%s", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
886 if (request
&& request
->hier
.tcpServer
!= NULL
)
887 p
= request
->hier
.tcpServer
->remote
.toStr(ntoabuf
,MAX_IPSTRLEN
);
888 else if (!building_deny_info_url
)
893 if (building_deny_info_url
) break;
894 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
899 if (building_deny_info_url
) break;
900 if (Config
.errHtmlText
) {
901 mb
.appendf("%s", Config
.errHtmlText
);
904 p
= "[not available]";
908 if (building_deny_info_url
) break;
910 if (auth_user_request
.getRaw())
911 p
= auth_user_request
->denyMessage("[not available]");
913 p
= "[not available]";
921 const SBuf
&m
= request
->method
.image();
922 mb
.append(m
.rawContent(), m
.length());
923 } else if (!building_deny_info_url
)
924 p
= "[unknown method]";
928 p
= request
? request
->extacl_message
.termedBuf() : external_acl_message
;
929 if (!p
&& !building_deny_info_url
)
930 p
= "[not available]";
935 mb
.appendf("%u", request
->url
.port());
936 } else if (!building_deny_info_url
) {
937 p
= "[unknown port]";
943 p
= request
->url
.getScheme().c_str();
944 } else if (!building_deny_info_url
) {
945 p
= "[unknown protocol]";
950 if (building_deny_info_url
) {
951 if (request
!= NULL
) {
952 SBuf tmp
= request
->url
.path();
959 if (request
!= NULL
) {
960 mb
.appendf(SQUIDSBUFPH
" " SQUIDSBUFPH
" %s/%d.%d\n",
961 SQUIDSBUFPRINT(request
->method
.image()),
962 SQUIDSBUFPRINT(request
->url
.path()),
963 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
964 request
->http_ver
.major
, request
->http_ver
.minor
);
965 request
->header
.packInto(&mb
, true); //hide authorization data
966 } else if (request_hdrs
) {
974 /* for backward compat we make %s show the full URL. Drop this in some future release. */
975 if (building_deny_info_url
) {
977 const SBuf
&tmp
= request
->effectiveRequestUri();
978 mb
.append(tmp
.rawContent(), tmp
.length());
981 debugs(0, DBG_CRITICAL
, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
983 p
= visible_appname_string
;
987 if (building_deny_info_url
) {
988 p
= visible_appname_string
;
991 /* signature may contain %-escapes, recursion */
992 if (page_id
!= ERR_SQUID_SIGNATURE
) {
993 const int saved_id
= page_id
;
994 page_id
= ERR_SQUID_SIGNATURE
;
995 MemBuf
*sign_mb
= BuildContent();
996 mb
.append(sign_mb
->content(), sign_mb
->contentSize());
1002 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1008 mb
.appendf("%s", Time::FormatHttpd(squid_curtime
));
1012 mb
.appendf("%s", mkrfc1123(squid_curtime
));
1016 /* Using the fake-https version of absolute-URI so error pages see https:// */
1017 /* even when the url-path cannot be shown as more than '*' */
1019 p
= urlCanonicalFakeHttps(request
);
1022 else if (!building_deny_info_url
)
1028 const SBuf
&tmp
= request
->effectiveRequestUri();
1029 mb
.append(tmp
.rawContent(), tmp
.length());
1032 else if (!building_deny_info_url
)
1037 if (Config
.adminEmail
)
1038 mb
.appendf("%s", Config
.adminEmail
);
1039 else if (!building_deny_info_url
)
1044 if (building_deny_info_url
) break;
1045 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
1053 mb
.appendf("%s", detail
->errorName());
1056 if (!building_deny_info_url
)
1057 p
= "[Unknown Error Code]";
1061 if (building_deny_info_url
) break;
1062 if (dnsError
.size() > 0)
1063 p
= dnsError
.termedBuf();
1064 else if (ftp
.cwd_msg
)
1071 if (building_deny_info_url
) break;
1083 mb
.appendf("%%%c", token
);
1089 p
= mb
.buf
; /* do not use mb after this assignment! */
1093 debugs(4, 3, "errorConvert: %%" << token
<< " --> '" << p
<< "'" );
1098 if (building_deny_info_url
&& !no_urlescape
)
1099 p
= rfc1738_escape_part(p
);
1105 ErrorState::DenyInfoLocation(const char *name
, HttpRequest
*, MemBuf
&result
)
1107 char const *m
= name
;
1112 m
+= 4; // skip "3xx:"
1114 while ((p
= strchr(m
, '%'))) {
1115 result
.append(m
, p
- m
); /* copy */
1116 t
= Convert(*++p
, true, true); /* convert */
1117 result
.appendf("%s", t
); /* copy */
1118 m
= p
+ 1; /* advance */
1122 result
.appendf("%s", m
); /* copy tail */
1124 assert((size_t)result
.contentSize() == strlen(result
.content()));
1128 ErrorState::BuildHttpReply()
1130 HttpReply
*rep
= new HttpReply
;
1131 const char *name
= errorPageName(page_id
);
1132 /* no LMT for error pages; error pages expire immediately */
1134 if (name
[0] == '3' || (name
[0] != '2' && name
[0] != '4' && name
[0] != '5' && strchr(name
, ':'))) {
1136 Http::StatusCode status
= Http::scFound
;
1137 // Use configured 3xx reply status if set.
1139 status
= httpStatus
;
1141 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1142 if (request
!= NULL
&& request
->method
!= Http::METHOD_GET
&& request
->method
!= Http::METHOD_HEAD
&& request
->http_ver
>= Http::ProtocolVersion(1,1))
1143 status
= Http::scTemporaryRedirect
;
1146 rep
->setHeaders(status
, NULL
, "text/html;charset=utf-8", 0, 0, -1);
1149 MemBuf redirect_location
;
1150 redirect_location
.init();
1151 DenyInfoLocation(name
, request
, redirect_location
);
1152 httpHeaderPutStrf(&rep
->header
, HDR_LOCATION
, "%s", redirect_location
.content() );
1155 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
1157 MemBuf
*content
= BuildContent();
1158 rep
->setHeaders(httpStatus
, NULL
, "text/html;charset=utf-8", content
->contentSize(), 0, -1);
1160 * include some information for downstream caches. Implicit
1161 * replaceable content. This isn't quite sufficient. xerrno is not
1162 * necessarily meaningful to another system, so we really should
1163 * expand it. Additionally, we should identify ourselves. Someone
1164 * might want to know. Someone _will_ want to know OTOH, the first
1165 * X-CACHE-MISS entry should tell us who.
1167 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%s %d", name
, xerrno
);
1171 * If error page auto-negotiate is enabled in any way, send the Vary.
1172 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1173 * We have even better reasons though:
1174 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1176 if (!Config
.errorDirectory
) {
1177 /* We 'negotiated' this ONLY from the Accept-Language. */
1178 rep
->header
.delById(HDR_VARY
);
1179 rep
->header
.putStr(HDR_VARY
, "Accept-Language");
1182 /* add the Content-Language header according to RFC section 14.12 */
1184 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, err_language
);
1186 #endif /* USE_ERROR_LOCALES */
1188 /* default templates are in English */
1189 /* language is known unless error_directory override used */
1190 if (!Config
.errorDirectory
)
1191 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, "en");
1194 rep
->body
.setMb(content
);
1195 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1198 // Make sure error codes get back to the client side for logging and
1201 int edc
= ERR_DETAIL_NONE
; // error detail code
1204 edc
= detail
->errorNo();
1211 request
->detailError(type
, edc
);
1218 ErrorState::BuildContent()
1220 const char *m
= NULL
;
1222 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
1225 ErrorPageFile
*localeTmpl
= NULL
;
1227 /** error_directory option in squid.conf overrides translations.
1228 * Custom errors are always found either in error_directory or the templates directory.
1229 * Otherwise locate the Accept-Language header
1231 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
) {
1232 if (err_language
&& err_language
!= Config
.errorDefaultLanguage
)
1233 safe_free(err_language
);
1235 localeTmpl
= new ErrorPageFile(err_type_str
[page_id
], static_cast<err_type
>(page_id
));
1236 if (localeTmpl
->loadFor(request
)) {
1237 m
= localeTmpl
->text();
1238 assert(localeTmpl
->language());
1239 err_language
= xstrdup(localeTmpl
->language());
1242 #endif /* USE_ERR_LOCALES */
1245 * If client-specific error templates are not enabled or available.
1246 * fall back to the old style squid.conf settings.
1249 m
= error_text
[page_id
];
1251 if (!Config
.errorDirectory
)
1252 err_language
= Config
.errorDefaultLanguage
;
1254 debugs(4, 2, HERE
<< "No existing error page language negotiated for " << errorPageName(page_id
) << ". Using default error file.");
1257 MemBuf
*result
= ConvertText(m
, true);
1265 MemBuf
*ErrorState::ConvertText(const char *text
, bool allowRecursion
)
1267 MemBuf
*content
= new MemBuf
;
1269 const char *m
= text
;
1273 while ((p
= strchr(m
, '%'))) {
1274 content
->append(m
, p
- m
); /* copy */
1275 const char *t
= Convert(*++p
, false, allowRecursion
); /* convert */
1276 content
->appendf("%s", t
); /* copy */
1277 m
= p
+ 1; /* advance */
1281 content
->appendf("%s", m
); /* copy tail */
1283 content
->terminate();
1285 assert((size_t)content
->contentSize() == strlen(content
->content()));