]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/errorpage.cc
2 * DEBUG: section 04 Error Generation
3 * AUTHOR: Duane Wessels
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
34 #include "comm/Connection.h"
35 #include "comm/Write.h"
37 #include "err_detail_type.h"
38 #include "errorpage.h"
41 #include "html_quote.h"
42 #include "HttpHeaderTools.h"
43 #include "HttpReply.h"
44 #include "HttpRequest.h"
46 #include "MemObject.h"
48 #include "SquidConfig.h"
53 #include "URLScheme.h"
56 #include "auth/UserRequest.h"
58 #include "SquidTime.h"
60 #include "ssl/ErrorDetailManager.h"
64 \defgroup ErrorPageInternal Error Page Internals
67 \section Abstract Abstract:
68 * These routines are used to generate error messages to be
69 * sent to clients. The error type is used to select between
70 * the various message formats. (formats are stored in the
71 * Config.errorDirectory)
74 #if !defined(DEFAULT_SQUID_ERROR_DIR)
75 /** Where to look for errors if config path fails.
76 \note Please use ./configure --datadir=/path instead of patching
78 #define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
81 /// \ingroup ErrorPageInternal
82 CBDATA_CLASS_INIT(ErrorState
);
86 /// \ingroup ErrorPageInternal
90 Http::StatusCode page_redirect
;
91 } ErrorDynamicPageInfo
;
93 /* local constant and vars */
96 \ingroup ErrorPageInternal
98 \note hard coded error messages are not appended with %S
99 * automagically to give you more control on the format
101 static const struct {
102 int type
; /* and page_id */
106 error_hard_text
[] = {
112 "<div id=\"footer\">\n"
113 "Generated %T by %h (%s)\n"
123 /// \ingroup ErrorPageInternal
124 static Vector
<ErrorDynamicPageInfo
*> ErrorDynamicPages
;
126 /* local prototypes */
128 /// \ingroup ErrorPageInternal
129 static const int error_hard_text_count
= sizeof(error_hard_text
) / sizeof(*error_hard_text
);
131 /// \ingroup ErrorPageInternal
132 static char **error_text
= NULL
;
134 /// \ingroup ErrorPageInternal
135 static int error_page_count
= 0;
137 /// \ingroup ErrorPageInternal
138 static MemBuf error_stylesheet
;
140 static const char *errorFindHardText(err_type type
);
141 static ErrorDynamicPageInfo
*errorDynamicPageInfoCreate(int id
, const char *page_name
);
142 static void errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
);
143 static IOCB errorSendComplete
;
145 /// \ingroup ErrorPageInternal
146 /// manages an error page template
147 class ErrorPageFile
: public TemplateFile
150 ErrorPageFile(const char *name
, const err_type code
): TemplateFile(name
,code
) { textBuf
.init();}
152 /// The template text data read from disk
153 const char *text() { return textBuf
.content(); }
156 /// stores the data read from disk to a local buffer
157 virtual bool parse(const char *buf
, int len
, bool eof
) {
159 textBuf
.append(buf
, len
);
163 MemBuf textBuf
; ///< A buffer to store the error page
166 /// \ingroup ErrorPageInternal
167 err_type
&operator++ (err_type
&anErr
)
169 int tmp
= (int)anErr
;
170 anErr
= (err_type
)(++tmp
);
174 /// \ingroup ErrorPageInternal
175 int operator - (err_type
const &anErr
, err_type
const &anErr2
)
177 return (int)anErr
- (int)anErr2
;
181 errorInitialize(void)
185 error_page_count
= ERR_MAX
+ ErrorDynamicPages
.size();
186 error_text
= static_cast<char **>(xcalloc(error_page_count
, sizeof(char *)));
188 for (i
= ERR_NONE
, ++i
; i
< error_page_count
; ++i
) {
189 safe_free(error_text
[i
]);
191 if ((text
= errorFindHardText(i
))) {
193 * Index any hard-coded error text into defaults.
195 error_text
[i
] = xstrdup(text
);
197 } else if (i
< ERR_MAX
) {
199 * Index precompiled fixed template files from one of two sources:
200 * (a) default language translation directory (error_default_language)
201 * (b) admin specified custom directory (error_directory)
203 ErrorPageFile
errTmpl(err_type_str
[i
], i
);
204 error_text
[i
] = errTmpl
.loadDefault() ? xstrdup(errTmpl
.text()) : NULL
;
207 * Index any unknown file names used by deny_info.
209 ErrorDynamicPageInfo
*info
= ErrorDynamicPages
[i
- ERR_MAX
];
210 assert(info
&& info
->id
== i
&& info
->page_name
);
212 const char *pg
= info
->page_name
;
213 if (info
->page_redirect
!= Http::scNone
)
214 pg
= info
->page_name
+4;
216 if (strchr(pg
, ':') == NULL
) {
217 /** But only if they are not redirection URL. */
218 ErrorPageFile
errTmpl(pg
, ERR_MAX
);
219 error_text
[i
] = errTmpl
.loadDefault() ? xstrdup(errTmpl
.text()) : NULL
;
224 error_stylesheet
.reset();
226 // look for and load stylesheet into global MemBuf for it.
227 if (Config
.errorStylesheet
) {
228 ErrorPageFile
tmpl("StylesSheet", ERR_MAX
);
229 tmpl
.loadFromFile(Config
.errorStylesheet
);
230 error_stylesheet
.Printf("%s",tmpl
.text());
234 Ssl::errorDetailInitialize();
244 for (i
= ERR_NONE
+ 1; i
< error_page_count
; ++i
)
245 safe_free(error_text
[i
]);
247 safe_free(error_text
);
250 while (!ErrorDynamicPages
.empty()) {
251 errorDynamicPageInfoDestroy(ErrorDynamicPages
.back());
252 ErrorDynamicPages
.pop_back();
255 error_page_count
= 0;
258 Ssl::errorDetailClean();
262 /// \ingroup ErrorPageInternal
264 errorFindHardText(err_type type
)
268 for (i
= 0; i
< error_hard_text_count
; ++i
)
269 if (error_hard_text
[i
].type
== type
)
270 return error_hard_text
[i
].text
;
275 TemplateFile::TemplateFile(const char *name
, const err_type code
): silent(false), wasLoaded(false), templateName(name
), templateCode(code
)
281 TemplateFile::loadDefault()
283 if (loaded()) // already loaded?
286 /** test error_directory configured location */
287 if (Config
.errorDirectory
) {
288 char path
[MAXPATHLEN
];
289 snprintf(path
, sizeof(path
), "%s/%s", Config
.errorDirectory
, templateName
.termedBuf());
294 /** test error_default_language location */
295 if (!loaded() && Config
.errorDefaultLanguage
) {
296 if (!tryLoadTemplate(Config
.errorDefaultLanguage
)) {
297 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "Unable to load default error language files. Reset to backups.");
302 /* test default location if failed (templates == English translation base templates) */
304 tryLoadTemplate("templates");
307 /* giving up if failed */
309 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "WARNING: failed to find or read error text file " << templateName
);
310 parse("Internal Error: Missing Template ", 33, '\0');
311 parse(templateName
.termedBuf(), templateName
.size(), '\0');
318 TemplateFile::tryLoadTemplate(const char *lang
)
322 char path
[MAXPATHLEN
];
323 /* TODO: prep the directory path string to prevent snprintf ... */
324 snprintf(path
, sizeof(path
), "%s/%s/%s",
325 DEFAULT_SQUID_ERROR_DIR
, lang
, templateName
.termedBuf());
326 path
[MAXPATHLEN
-1] = '\0';
328 if (loadFromFile(path
))
332 if ( strlen(lang
) == 2) {
333 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
334 /* use first result. */
335 debugs(4,2, HERE
<< "wildcard fallback errors not coded yet.");
343 TemplateFile::loadFromFile(const char *path
)
349 if (loaded()) // already loaded?
352 fd
= file_open(path
, O_RDONLY
| O_TEXT
);
355 /* with dynamic locale negotiation we may see some failures before a success. */
356 if (!silent
&& templateCode
< TCP_RESET
)
357 debugs(4, DBG_CRITICAL
, HERE
<< "'" << path
<< "': " << xstrerror());
362 while ((len
= FD_READ_METHOD(fd
, buf
, sizeof(buf
))) > 0) {
363 if (!parse(buf
, len
, false)) {
364 debugs(4, DBG_CRITICAL
, HERE
<< " parse error while reading template file: " << path
);
372 debugs(4, DBG_CRITICAL
, HERE
<< "failed to fully read: '" << path
<< "': " << xstrerror());
381 bool strHdrAcptLangGetItem(const String
&hdr
, char *lang
, int langLen
, size_t &pos
)
383 while (pos
< hdr
.size()) {
386 /* skip any initial whitespace. */
387 while (pos
< hdr
.size() && xisspace(hdr
[pos
]))
391 * Header value format:
392 * - sequence of whitespace delimited tags
393 * - each tag may suffix with ';'.* which we can ignore.
394 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
395 * with preference given to an exact match.
397 bool invalid_byte
= false;
398 while (pos
< hdr
.size() && hdr
[pos
] != ';' && hdr
[pos
] != ',' && !xisspace(hdr
[pos
]) && dt
< (lang
+ (langLen
-1)) ) {
400 #if USE_HTTP_VIOLATIONS
401 // if accepting violations we may as well accept some broken browsers
402 // which may send us the right code, wrong ISO formatting.
407 *dt
= xtolower(hdr
[pos
]);
408 // valid codes only contain A-Z, hyphen (-) and *
409 if (*dt
!= '-' && *dt
!= '*' && (*dt
< 'a' || *dt
> 'z') )
412 ++dt
; // move to next destination byte.
416 *dt
= '\0'; // nul-terminated the filename content string before system use.
419 // if we terminated the tag on garbage or ';' we need to skip to the next ',' or end of header.
420 while (pos
< hdr
.size() && hdr
[pos
] != ',')
423 if (pos
< hdr
.size() && hdr
[pos
] == ',')
426 debugs(4, 9, HERE
<< "STATE: dt='" << dt
<< "', lang='" << lang
<< "', pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
428 /* if we found anything we might use, try it. */
429 if (*lang
!= '\0' && !invalid_byte
)
436 TemplateFile::loadFor(const HttpRequest
*request
)
441 if (loaded()) // already loaded?
444 if (!request
|| !request
->header
.getList(HDR_ACCEPT_LANGUAGE
, &hdr
) )
448 size_t pos
= 0; // current parsing position in header string
450 debugs(4, 6, HERE
<< "Testing Header: '" << hdr
<< "'");
452 while ( strHdrAcptLangGetItem(hdr
, lang
, 256, pos
) ) {
454 /* wildcard uses the configured default language */
455 if (lang
[0] == '*' && lang
[1] == '\0') {
456 debugs(4, 6, HERE
<< "Found language '" << lang
<< "'. Using configured default.");
460 debugs(4, 6, HERE
<< "Found language '" << lang
<< "', testing for available template");
462 if (tryLoadTemplate(lang
)) {
463 /* store the language we found for the Content-Language reply header */
466 } else if (Config
.errorLogMissingLanguages
) {
467 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << lang
);
475 /// \ingroup ErrorPageInternal
476 static ErrorDynamicPageInfo
*
477 errorDynamicPageInfoCreate(int id
, const char *page_name
)
479 ErrorDynamicPageInfo
*info
= new ErrorDynamicPageInfo
;
481 info
->page_name
= xstrdup(page_name
);
482 info
->page_redirect
= static_cast<Http::StatusCode
>(atoi(page_name
));
484 /* WARNING on redirection status:
485 * 2xx are permitted, but not documented officially.
486 * - might be useful for serving static files (PAC etc) in special cases
487 * 3xx require a URL suitable for Location: header.
488 * - the current design does not allow for a Location: URI as well as a local file template
489 * although this possibility is explicitly permitted in the specs.
490 * 4xx-5xx require a local file template.
491 * - sending Location: on these codes with no body is invalid by the specs.
492 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
493 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
495 if (info
->page_redirect
== Http::scNone
)
496 ; // special case okay.
497 else if (info
->page_redirect
< 200 || info
->page_redirect
> 599) {
499 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
501 } else if ( /* >= 200 && */ info
->page_redirect
< 300 && strchr(&(page_name
[4]), ':')) {
502 // 2xx require a local template file
503 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
505 } else if (info
->page_redirect
>= 300 && info
->page_redirect
<= 399 && !strchr(&(page_name
[4]), ':')) {
506 // 3xx require an absolute URL
507 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a URL on '" << page_name
<< "'");
509 } else if (info
->page_redirect
>= 400 /* && <= 599 */ && strchr(&(page_name
[4]), ':')) {
510 // 4xx/5xx require a local template file
511 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
519 /// \ingroup ErrorPageInternal
521 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
)
524 safe_free(info
->page_name
);
528 /// \ingroup ErrorPageInternal
530 errorPageId(const char *page_name
)
532 for (int i
= 0; i
< ERR_MAX
; ++i
) {
533 if (strcmp(err_type_str
[i
], page_name
) == 0)
537 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); ++j
) {
538 if (strcmp(ErrorDynamicPages
[j
]->page_name
, page_name
) == 0)
546 errorReservePageId(const char *page_name
)
548 ErrorDynamicPageInfo
*info
;
549 int id
= errorPageId(page_name
);
551 if (id
== ERR_NONE
) {
552 info
= errorDynamicPageInfoCreate(ERR_MAX
+ ErrorDynamicPages
.size(), page_name
);
553 ErrorDynamicPages
.push_back(info
);
560 /// \ingroup ErrorPageInternal
562 errorPageName(int pageId
)
564 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
565 return err_type_str
[pageId
];
567 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
568 return ErrorDynamicPages
[pageId
- ERR_MAX
]->page_name
;
570 return "ERR_UNKNOWN"; /* should not happen */
573 ErrorState::ErrorState(err_type t
, Http::StatusCode status
, HttpRequest
* req
) :
579 auth_user_request (NULL
),
596 detailCode(ERR_DETAIL_NONE
)
598 memset(&ftp
, 0, sizeof(ftp
));
600 if (page_id
>= ERR_MAX
&& ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
!= Http::scNone
)
601 httpStatus
= ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
;
605 HTTPMSGLOCK(request
);
606 src_addr
= req
->client_addr
;
611 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
613 assert(entry
->mem_obj
!= NULL
);
614 assert (entry
->isEmpty());
615 debugs(4, 4, "Creating an error page for entry " << entry
<<
616 " with errorstate " << err
<<
617 " page id " << err
->page_id
);
619 if (entry
->store_status
!= STORE_PENDING
) {
620 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
622 * If the entry is not STORE_PENDING, then no clients
623 * care about it, and we don't need to generate an
626 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
627 assert(entry
->mem_obj
->nclients
== 0);
632 if (err
->page_id
== TCP_RESET
) {
634 debugs(4, 2, "RSTing this reply");
635 err
->request
->flags
.resetTcp
= true;
639 entry
->lock("errorAppendEntry");
641 entry
->replaceHttpReply( err
->BuildHttpReply() );
644 entry
->negativeCache();
645 entry
->releaseRequest();
646 entry
->unlock("errorAppendEntry");
651 errorSend(const Comm::ConnectionPointer
&conn
, ErrorState
* err
)
654 debugs(4, 3, HERE
<< conn
<< ", err=" << err
);
655 assert(Comm::IsConnOpen(conn
));
657 rep
= err
->BuildHttpReply();
659 MemBuf
*mb
= rep
->pack();
660 AsyncCall::Pointer call
= commCbCall(78, 5, "errorSendComplete",
661 CommIoCbPtrFun(&errorSendComplete
, err
));
662 Comm::Write(conn
, mb
, call
);
669 \ingroup ErrorPageAPI
671 * Called by commHandleWrite() after data has been written
672 * to the client socket.
674 \note If there is a callback, the callback is responsible for
675 * closing the FD, otherwise we do it ourselves.
678 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
680 ErrorState
*err
= static_cast<ErrorState
*>(data
);
681 debugs(4, 3, HERE
<< conn
<< ", size=" << size
);
683 if (errflag
!= COMM_ERR_CLOSING
) {
685 debugs(4, 3, "errorSendComplete: callback");
686 err
->callback(conn
->fd
, err
->callback_data
, size
);
688 debugs(4, 3, "errorSendComplete: comm_close");
696 ErrorState::~ErrorState()
698 HTTPMSGUNLOCK(request
);
699 safe_free(redirect_url
);
701 safe_free(request_hdrs
);
702 wordlistDestroy(&ftp
.server_msg
);
703 safe_free(ftp
.request
);
704 safe_free(ftp
.reply
);
706 auth_user_request
= NULL
;
710 if (err_language
!= Config
.errorDefaultLanguage
)
712 safe_free(err_language
);
719 ErrorState::Dump(MemBuf
* mb
)
722 char ntoabuf
[MAX_IPSTRLEN
];
725 /* email subject line */
726 str
.Printf("CacheErrorInfo - %s", errorPageName(type
));
727 mb
->Printf("?subject=%s", rfc1738_escape_part(str
.buf
));
730 str
.Printf("CacheHost: %s\r\n", getMyHostname());
732 str
.Printf("ErrPage: %s\r\n", errorPageName(type
));
735 str
.Printf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
737 str
.Printf("Err: [none]\r\n");
740 if (auth_user_request
->denyMessage())
741 str
.Printf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
743 if (dnsError
.size() > 0)
744 str
.Printf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
747 str
.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
750 str
.Printf("ClientIP: %s\r\n", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
752 if (request
&& request
->hier
.host
[0] != '\0') {
753 str
.Printf("ServerIP: %s\r\n", request
->hier
.host
);
758 str
.Printf("HTTP Request:\r\n");
760 if (NULL
!= request
) {
762 String urlpath_or_slash
;
764 if (request
->urlpath
.size() != 0)
765 urlpath_or_slash
= request
->urlpath
;
767 urlpath_or_slash
= "/";
769 str
.Printf("%s " SQUIDSTRINGPH
" %s/%d.%d\n",
770 RequestMethodStr(request
->method
),
771 SQUIDSTRINGPRINT(urlpath_or_slash
),
772 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
773 request
->http_ver
.major
, request
->http_ver
.minor
);
774 packerToMemInit(&pck
, &str
);
775 request
->header
.packInto(&pck
);
783 str
.Printf("FTP Request: %s\r\n", ftp
.request
);
784 str
.Printf("FTP Reply: %s\r\n", (ftp
.reply
? ftp
.reply
:"[none]"));
785 str
.Printf("FTP Msg: ");
786 wordlistCat(ftp
.server_msg
, &str
);
791 mb
->Printf("&body=%s", rfc1738_escape_part(str
.buf
));
796 /// \ingroup ErrorPageInternal
797 #define CVT_BUF_SZ 512
800 ErrorState::Convert(char token
, bool building_deny_info_url
, bool allowRecursion
)
803 const char *p
= NULL
; /* takes priority over mb if set */
805 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
806 char ntoabuf
[MAX_IPSTRLEN
];
814 if (request
&& request
->auth_user_request
!= NULL
)
815 p
= request
->auth_user_request
->username();
822 mb
.Printf("%d", getMyPort());
826 if (building_deny_info_url
) break;
827 p
= request
? ftpUrlWith2f(request
) : "[no URL]";
831 if (building_deny_info_url
) break;
832 p
= errorPageName(type
);
837 p
= "%D"; // if recursion is not allowed, do not convert
839 // currently only SSL error details implemented
841 detail
->useRequest(request
);
842 const String
&errDetail
= detail
->toString();
843 if (errDetail
.size() > 0) {
844 MemBuf
*detail_mb
= ConvertText(errDetail
.termedBuf(), false);
845 mb
.append(detail_mb
->content(), detail_mb
->contentSize());
851 if (!mb
.contentSize())
852 mb
.Printf("[No Error Detail]");
856 mb
.Printf("%d", xerrno
);
861 mb
.Printf("(%d) %s", xerrno
, strerror(xerrno
));
863 mb
.Printf("[No Error]");
867 if (building_deny_info_url
) break;
868 /* FTP REQUEST LINE */
876 if (building_deny_info_url
) break;
885 if (building_deny_info_url
) break;
886 /* FTP SERVER RESPONSE */
888 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
890 } else if (ftp
.server_msg
) {
891 wordlistCat(ftp
.server_msg
, &mb
);
896 mb
.Printf("%s", getMyHostname());
901 if (request
->hier
.host
[0] != '\0') // if non-empty string.
902 p
= request
->hier
.host
;
904 p
= request
->GetHost();
905 } else if (!building_deny_info_url
)
906 p
= "[unknown host]";
910 mb
.Printf("%s", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
914 if (request
&& request
->hier
.tcpServer
!= NULL
)
915 p
= request
->hier
.tcpServer
->remote
.toStr(ntoabuf
,MAX_IPSTRLEN
);
916 else if (!building_deny_info_url
)
921 if (building_deny_info_url
) break;
922 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
927 if (building_deny_info_url
) break;
928 if (Config
.errHtmlText
) {
929 mb
.Printf("%s", Config
.errHtmlText
);
932 p
= "[not available]";
936 if (building_deny_info_url
) break;
938 p
= auth_user_request
->denyMessage("[not available]");
946 p
= RequestMethodStr(request
->method
);
947 else if (!building_deny_info_url
)
948 p
= "[unknown method]";
952 p
= request
? request
->extacl_message
.termedBuf() : external_acl_message
;
953 if (!p
&& !building_deny_info_url
)
954 p
= "[not available]";
959 mb
.Printf("%d", (int) request
->port
);
960 } else if (!building_deny_info_url
) {
961 p
= "[unknown port]";
967 p
= AnyP::ProtocolType_str
[request
->protocol
];
968 } else if (!building_deny_info_url
) {
969 p
= "[unknown protocol]";
974 if (building_deny_info_url
) {
975 p
= (request
->urlpath
.size() != 0 ? request
->urlpath
.termedBuf() : "/");
979 if (NULL
!= request
) {
981 String urlpath_or_slash
;
983 if (request
->urlpath
.size() != 0)
984 urlpath_or_slash
= request
->urlpath
;
986 urlpath_or_slash
= "/";
988 mb
.Printf("%s " SQUIDSTRINGPH
" %s/%d.%d\n",
989 RequestMethodStr(request
->method
),
990 SQUIDSTRINGPRINT(urlpath_or_slash
),
991 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
992 request
->http_ver
.major
, request
->http_ver
.minor
);
993 packerToMemInit(&pck
, &mb
);
994 request
->header
.packInto(&pck
, true); //hide authorization data
996 } else if (request_hdrs
) {
1004 /* for backward compat we make %s show the full URL. Drop this in some future release. */
1005 if (building_deny_info_url
) {
1006 p
= request
? urlCanonical(request
) : url
;
1007 debugs(0, DBG_CRITICAL
, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
1009 p
= visible_appname_string
;
1013 if (building_deny_info_url
) {
1014 p
= visible_appname_string
;
1017 /* signature may contain %-escapes, recursion */
1018 if (page_id
!= ERR_SQUID_SIGNATURE
) {
1019 const int saved_id
= page_id
;
1020 page_id
= ERR_SQUID_SIGNATURE
;
1021 MemBuf
*sign_mb
= BuildContent();
1022 mb
.Printf("%s", sign_mb
->content());
1028 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1034 mb
.Printf("%s", Time::FormatHttpd(squid_curtime
));
1038 mb
.Printf("%s", mkrfc1123(squid_curtime
));
1042 /* Using the fake-https version of canonical so error pages see https:// */
1043 /* even when the url-path cannot be shown as more than '*' */
1045 p
= urlCanonicalFakeHttps(request
);
1048 else if (!building_deny_info_url
)
1054 p
= urlCanonical(request
);
1057 else if (!building_deny_info_url
)
1062 if (Config
.adminEmail
)
1063 mb
.Printf("%s", Config
.adminEmail
);
1064 else if (!building_deny_info_url
)
1069 if (building_deny_info_url
) break;
1070 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
1078 mb
.Printf("%s", detail
->errorName());
1081 if (!building_deny_info_url
)
1082 p
= "[Unknown Error Code]";
1086 if (building_deny_info_url
) break;
1087 if (dnsError
.size() > 0)
1088 p
= dnsError
.termedBuf();
1089 else if (ftp
.cwd_msg
)
1096 if (building_deny_info_url
) break;
1108 mb
.Printf("%%%c", token
);
1114 p
= mb
.buf
; /* do not use mb after this assignment! */
1118 debugs(4, 3, "errorConvert: %%" << token
<< " --> '" << p
<< "'" );
1123 if (building_deny_info_url
&& !no_urlescape
)
1124 p
= rfc1738_escape_part(p
);
1130 ErrorState::DenyInfoLocation(const char *name
, HttpRequest
*aRequest
, MemBuf
&result
)
1132 char const *m
= name
;
1137 m
+= 4; // skip "3xx:"
1139 while ((p
= strchr(m
, '%'))) {
1140 result
.append(m
, p
- m
); /* copy */
1141 t
= Convert(*++p
, true, true); /* convert */
1142 result
.Printf("%s", t
); /* copy */
1143 m
= p
+ 1; /* advance */
1147 result
.Printf("%s", m
); /* copy tail */
1149 assert((size_t)result
.contentSize() == strlen(result
.content()));
1153 ErrorState::BuildHttpReply()
1155 HttpReply
*rep
= new HttpReply
;
1156 const char *name
= errorPageName(page_id
);
1157 /* no LMT for error pages; error pages expire immediately */
1159 if (name
[0] == '3' || (name
[0] != '2' && name
[0] != '4' && name
[0] != '5' && strchr(name
, ':'))) {
1161 Http::StatusCode status
= Http::scMovedTemporarily
;
1162 // Use configured 3xx reply status if set.
1164 status
= httpStatus
;
1166 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1167 if (request
->method
!= Http::METHOD_GET
&& request
->method
!= Http::METHOD_HEAD
&& request
->http_ver
>= Http::ProtocolVersion(1,1))
1168 status
= Http::scTemporaryRedirect
;
1171 rep
->setHeaders(status
, NULL
, "text/html;charset=utf-8", 0, 0, -1);
1174 MemBuf redirect_location
;
1175 redirect_location
.init();
1176 DenyInfoLocation(name
, request
, redirect_location
);
1177 httpHeaderPutStrf(&rep
->header
, HDR_LOCATION
, "%s", redirect_location
.content() );
1180 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
1182 MemBuf
*content
= BuildContent();
1183 rep
->setHeaders(httpStatus
, NULL
, "text/html;charset=utf-8", content
->contentSize(), 0, -1);
1185 * include some information for downstream caches. Implicit
1186 * replaceable content. This isn't quite sufficient. xerrno is not
1187 * necessarily meaningful to another system, so we really should
1188 * expand it. Additionally, we should identify ourselves. Someone
1189 * might want to know. Someone _will_ want to know OTOH, the first
1190 * X-CACHE-MISS entry should tell us who.
1192 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%s %d", name
, xerrno
);
1196 * If error page auto-negotiate is enabled in any way, send the Vary.
1197 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1198 * We have even better reasons though:
1199 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1201 if (!Config
.errorDirectory
) {
1202 /* We 'negotiated' this ONLY from the Accept-Language. */
1203 rep
->header
.delById(HDR_VARY
);
1204 rep
->header
.putStr(HDR_VARY
, "Accept-Language");
1207 /* add the Content-Language header according to RFC section 14.12 */
1209 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, err_language
);
1211 #endif /* USE_ERROR_LOCALES */
1213 /* default templates are in English */
1214 /* language is known unless error_directory override used */
1215 if (!Config
.errorDirectory
)
1216 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, "en");
1219 rep
->body
.setMb(content
);
1220 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1223 // Make sure error codes get back to the client side for logging and
1226 int edc
= ERR_DETAIL_NONE
; // error detail code
1229 edc
= detail
->errorNo();
1236 request
->detailError(type
, edc
);
1243 ErrorState::BuildContent()
1245 const char *m
= NULL
;
1247 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
1250 ErrorPageFile
*localeTmpl
= NULL
;
1252 /** error_directory option in squid.conf overrides translations.
1253 * Custom errors are always found either in error_directory or the templates directory.
1254 * Otherwise locate the Accept-Language header
1256 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
) {
1257 if (err_language
&& err_language
!= Config
.errorDefaultLanguage
)
1258 safe_free(err_language
);
1260 localeTmpl
= new ErrorPageFile(err_type_str
[page_id
], static_cast<err_type
>(page_id
));
1261 if (localeTmpl
->loadFor(request
)) {
1262 m
= localeTmpl
->text();
1263 assert(localeTmpl
->language());
1264 err_language
= xstrdup(localeTmpl
->language());
1267 #endif /* USE_ERR_LOCALES */
1270 * If client-specific error templates are not enabled or available.
1271 * fall back to the old style squid.conf settings.
1274 m
= error_text
[page_id
];
1276 if (!Config
.errorDirectory
)
1277 err_language
= Config
.errorDefaultLanguage
;
1279 debugs(4, 2, HERE
<< "No existing error page language negotiated for " << errorPageName(page_id
) << ". Using default error file.");
1282 MemBuf
*result
= ConvertText(m
, true);
1290 MemBuf
*ErrorState::ConvertText(const char *text
, bool allowRecursion
)
1292 MemBuf
*content
= new MemBuf
;
1294 const char *m
= text
;
1298 while ((p
= strchr(m
, '%'))) {
1299 content
->append(m
, p
- m
); /* copy */
1300 const char *t
= Convert(*++p
, false, allowRecursion
); /* convert */
1301 content
->Printf("%s", t
); /* copy */
1302 m
= p
+ 1; /* advance */
1306 content
->Printf("%s", m
); /* copy tail */
1308 content
->terminate();
1310 assert((size_t)content
->contentSize() == strlen(content
->content()));