]>
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"
54 #include "auth/UserRequest.h"
56 #include "SquidTime.h"
58 #include "ssl/ErrorDetailManager.h"
62 \defgroup ErrorPageInternal Error Page Internals
65 \section Abstract Abstract:
66 * These routines are used to generate error messages to be
67 * sent to clients. The error type is used to select between
68 * the various message formats. (formats are stored in the
69 * Config.errorDirectory)
72 #if !defined(DEFAULT_SQUID_ERROR_DIR)
73 /** Where to look for errors if config path fails.
74 \note Please use ./configure --datadir=/path instead of patching
76 #define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
79 /// \ingroup ErrorPageInternal
80 CBDATA_CLASS_INIT(ErrorState
);
84 /// \ingroup ErrorPageInternal
88 Http::StatusCode page_redirect
;
89 } ErrorDynamicPageInfo
;
91 /* local constant and vars */
94 \ingroup ErrorPageInternal
96 \note hard coded error messages are not appended with %S
97 * automagically to give you more control on the format
100 int type
; /* and page_id */
104 error_hard_text
[] = {
110 "<div id=\"footer\">\n"
111 "Generated %T by %h (%s)\n"
121 /// \ingroup ErrorPageInternal
122 static Vector
<ErrorDynamicPageInfo
*> ErrorDynamicPages
;
124 /* local prototypes */
126 /// \ingroup ErrorPageInternal
127 static const int error_hard_text_count
= sizeof(error_hard_text
) / sizeof(*error_hard_text
);
129 /// \ingroup ErrorPageInternal
130 static char **error_text
= NULL
;
132 /// \ingroup ErrorPageInternal
133 static int error_page_count
= 0;
135 /// \ingroup ErrorPageInternal
136 static MemBuf error_stylesheet
;
138 static const char *errorFindHardText(err_type type
);
139 static ErrorDynamicPageInfo
*errorDynamicPageInfoCreate(int id
, const char *page_name
);
140 static void errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
);
141 static IOCB errorSendComplete
;
143 /// \ingroup ErrorPageInternal
144 /// manages an error page template
145 class ErrorPageFile
: public TemplateFile
148 ErrorPageFile(const char *name
, const err_type code
): TemplateFile(name
,code
) { textBuf
.init();}
150 /// The template text data read from disk
151 const char *text() { return textBuf
.content(); }
154 /// stores the data read from disk to a local buffer
155 virtual bool parse(const char *buf
, int len
, bool eof
) {
157 textBuf
.append(buf
, len
);
161 MemBuf textBuf
; ///< A buffer to store the error page
164 /// \ingroup ErrorPageInternal
165 err_type
&operator++ (err_type
&anErr
)
167 int tmp
= (int)anErr
;
168 anErr
= (err_type
)(++tmp
);
172 /// \ingroup ErrorPageInternal
173 int operator - (err_type
const &anErr
, err_type
const &anErr2
)
175 return (int)anErr
- (int)anErr2
;
179 errorInitialize(void)
183 error_page_count
= ERR_MAX
+ ErrorDynamicPages
.size();
184 error_text
= static_cast<char **>(xcalloc(error_page_count
, sizeof(char *)));
186 for (i
= ERR_NONE
, ++i
; i
< error_page_count
; ++i
) {
187 safe_free(error_text
[i
]);
189 if ((text
= errorFindHardText(i
))) {
191 * Index any hard-coded error text into defaults.
193 error_text
[i
] = xstrdup(text
);
195 } else if (i
< ERR_MAX
) {
197 * Index precompiled fixed template files from one of two sources:
198 * (a) default language translation directory (error_default_language)
199 * (b) admin specified custom directory (error_directory)
201 ErrorPageFile
errTmpl(err_type_str
[i
], i
);
202 error_text
[i
] = errTmpl
.loadDefault() ? xstrdup(errTmpl
.text()) : NULL
;
205 * Index any unknown file names used by deny_info.
207 ErrorDynamicPageInfo
*info
= ErrorDynamicPages
.items
[i
- ERR_MAX
];
208 assert(info
&& info
->id
== i
&& info
->page_name
);
210 const char *pg
= info
->page_name
;
211 if (info
->page_redirect
!= Http::scNone
)
212 pg
= info
->page_name
+4;
214 if (strchr(pg
, ':') == NULL
) {
215 /** But only if they are not redirection URL. */
216 ErrorPageFile
errTmpl(pg
, ERR_MAX
);
217 error_text
[i
] = errTmpl
.loadDefault() ? xstrdup(errTmpl
.text()) : NULL
;
222 error_stylesheet
.reset();
224 // look for and load stylesheet into global MemBuf for it.
225 if (Config
.errorStylesheet
) {
226 ErrorPageFile
tmpl("StylesSheet", ERR_MAX
);
227 tmpl
.loadFromFile(Config
.errorStylesheet
);
228 error_stylesheet
.Printf("%s",tmpl
.text());
232 Ssl::errorDetailInitialize();
242 for (i
= ERR_NONE
+ 1; i
< error_page_count
; ++i
)
243 safe_free(error_text
[i
]);
245 safe_free(error_text
);
248 while (ErrorDynamicPages
.size())
249 errorDynamicPageInfoDestroy(ErrorDynamicPages
.pop_back());
251 error_page_count
= 0;
254 Ssl::errorDetailClean();
258 /// \ingroup ErrorPageInternal
260 errorFindHardText(err_type type
)
264 for (i
= 0; i
< error_hard_text_count
; ++i
)
265 if (error_hard_text
[i
].type
== type
)
266 return error_hard_text
[i
].text
;
271 TemplateFile::TemplateFile(const char *name
, const err_type code
): silent(false), wasLoaded(false), templateName(name
), templateCode(code
)
277 TemplateFile::loadDefault()
279 if (loaded()) // already loaded?
282 /** test error_directory configured location */
283 if (Config
.errorDirectory
) {
284 char path
[MAXPATHLEN
];
285 snprintf(path
, sizeof(path
), "%s/%s", Config
.errorDirectory
, templateName
.termedBuf());
290 /** test error_default_language location */
291 if (!loaded() && Config
.errorDefaultLanguage
) {
292 if (!tryLoadTemplate(Config
.errorDefaultLanguage
)) {
293 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "Unable to load default error language files. Reset to backups.");
298 /* test default location if failed (templates == English translation base templates) */
300 tryLoadTemplate("templates");
303 /* giving up if failed */
305 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "WARNING: failed to find or read error text file " << templateName
);
306 parse("Internal Error: Missing Template ", 33, '\0');
307 parse(templateName
.termedBuf(), templateName
.size(), '\0');
314 TemplateFile::tryLoadTemplate(const char *lang
)
318 char path
[MAXPATHLEN
];
319 /* TODO: prep the directory path string to prevent snprintf ... */
320 snprintf(path
, sizeof(path
), "%s/%s/%s",
321 DEFAULT_SQUID_ERROR_DIR
, lang
, templateName
.termedBuf());
322 path
[MAXPATHLEN
-1] = '\0';
324 if (loadFromFile(path
))
328 if ( strlen(lang
) == 2) {
329 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
330 /* use first result. */
331 debugs(4,2, HERE
<< "wildcard fallback errors not coded yet.");
339 TemplateFile::loadFromFile(const char *path
)
345 if (loaded()) // already loaded?
348 fd
= file_open(path
, O_RDONLY
| O_TEXT
);
351 /* with dynamic locale negotiation we may see some failures before a success. */
352 if (!silent
&& templateCode
< TCP_RESET
)
353 debugs(4, DBG_CRITICAL
, HERE
<< "'" << path
<< "': " << xstrerror());
358 while ((len
= FD_READ_METHOD(fd
, buf
, sizeof(buf
))) > 0) {
359 if (!parse(buf
, len
, false)) {
360 debugs(4, DBG_CRITICAL
, HERE
<< " parse error while reading template file: " << path
);
368 debugs(4, DBG_CRITICAL
, HERE
<< "failed to fully read: '" << path
<< "': " << xstrerror());
377 bool strHdrAcptLangGetItem(const String
&hdr
, char *lang
, int langLen
, size_t &pos
)
379 while (pos
< hdr
.size()) {
382 /* skip any initial whitespace. */
383 while (pos
< hdr
.size() && xisspace(hdr
[pos
]))
387 * Header value format:
388 * - sequence of whitespace delimited tags
389 * - each tag may suffix with ';'.* which we can ignore.
390 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
391 * with preference given to an exact match.
393 bool invalid_byte
= false;
394 while (pos
< hdr
.size() && hdr
[pos
] != ';' && hdr
[pos
] != ',' && !xisspace(hdr
[pos
]) && dt
< (lang
+ (langLen
-1)) ) {
396 #if USE_HTTP_VIOLATIONS
397 // if accepting violations we may as well accept some broken browsers
398 // which may send us the right code, wrong ISO formatting.
403 *dt
= xtolower(hdr
[pos
]);
404 // valid codes only contain A-Z, hyphen (-) and *
405 if (*dt
!= '-' && *dt
!= '*' && (*dt
< 'a' || *dt
> 'z') )
408 ++dt
; // move to next destination byte.
412 *dt
= '\0'; // nul-terminated the filename content string before system use.
415 // if we terminated the tag on garbage or ';' we need to skip to the next ',' or end of header.
416 while (pos
< hdr
.size() && hdr
[pos
] != ',')
419 if (pos
< hdr
.size() && hdr
[pos
] == ',')
422 debugs(4, 9, HERE
<< "STATE: dt='" << dt
<< "', lang='" << lang
<< "', pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
424 /* if we found anything we might use, try it. */
425 if (*lang
!= '\0' && !invalid_byte
)
432 TemplateFile::loadFor(const HttpRequest
*request
)
437 if (loaded()) // already loaded?
440 if (!request
|| !request
->header
.getList(HDR_ACCEPT_LANGUAGE
, &hdr
) )
444 size_t pos
= 0; // current parsing position in header string
446 debugs(4, 6, HERE
<< "Testing Header: '" << hdr
<< "'");
448 while ( strHdrAcptLangGetItem(hdr
, lang
, 256, pos
) ) {
450 /* wildcard uses the configured default language */
451 if (lang
[0] == '*' && lang
[1] == '\0') {
452 debugs(4, 6, HERE
<< "Found language '" << lang
<< "'. Using configured default.");
456 debugs(4, 6, HERE
<< "Found language '" << lang
<< "', testing for available template");
458 if (tryLoadTemplate(lang
)) {
459 /* store the language we found for the Content-Language reply header */
462 } else if (Config
.errorLogMissingLanguages
) {
463 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << lang
);
471 /// \ingroup ErrorPageInternal
472 static ErrorDynamicPageInfo
*
473 errorDynamicPageInfoCreate(int id
, const char *page_name
)
475 ErrorDynamicPageInfo
*info
= new ErrorDynamicPageInfo
;
477 info
->page_name
= xstrdup(page_name
);
478 info
->page_redirect
= static_cast<Http::StatusCode
>(atoi(page_name
));
480 /* WARNING on redirection status:
481 * 2xx are permitted, but not documented officially.
482 * - might be useful for serving static files (PAC etc) in special cases
483 * 3xx require a URL suitable for Location: header.
484 * - the current design does not allow for a Location: URI as well as a local file template
485 * although this possibility is explicitly permitted in the specs.
486 * 4xx-5xx require a local file template.
487 * - sending Location: on these codes with no body is invalid by the specs.
488 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
489 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
491 if (info
->page_redirect
== Http::scNone
)
492 ; // special case okay.
493 else if (info
->page_redirect
< 200 || info
->page_redirect
> 599) {
495 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
497 } else if ( /* >= 200 && */ info
->page_redirect
< 300 && strchr(&(page_name
[4]), ':')) {
498 // 2xx require a local template file
499 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
501 } else if (info
->page_redirect
>= 300 && info
->page_redirect
<= 399 && !strchr(&(page_name
[4]), ':')) {
502 // 3xx require an absolute URL
503 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a URL on '" << page_name
<< "'");
505 } else if (info
->page_redirect
>= 400 /* && <= 599 */ && strchr(&(page_name
[4]), ':')) {
506 // 4xx/5xx require a local template file
507 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
515 /// \ingroup ErrorPageInternal
517 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
)
520 safe_free(info
->page_name
);
524 /// \ingroup ErrorPageInternal
526 errorPageId(const char *page_name
)
528 for (int i
= 0; i
< ERR_MAX
; ++i
) {
529 if (strcmp(err_type_str
[i
], page_name
) == 0)
533 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); ++j
) {
534 if (strcmp(ErrorDynamicPages
.items
[j
]->page_name
, page_name
) == 0)
542 errorReservePageId(const char *page_name
)
544 ErrorDynamicPageInfo
*info
;
545 int id
= errorPageId(page_name
);
547 if (id
== ERR_NONE
) {
548 info
= errorDynamicPageInfoCreate(ERR_MAX
+ ErrorDynamicPages
.size(), page_name
);
549 ErrorDynamicPages
.push_back(info
);
556 /// \ingroup ErrorPageInternal
558 errorPageName(int pageId
)
560 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
561 return err_type_str
[pageId
];
563 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
564 return ErrorDynamicPages
.items
[pageId
- ERR_MAX
]->page_name
;
566 return "ERR_UNKNOWN"; /* should not happen */
569 ErrorState::ErrorState(err_type t
, Http::StatusCode status
, HttpRequest
* req
) :
575 auth_user_request (NULL
),
592 detailCode(ERR_DETAIL_NONE
)
594 memset(&ftp
, 0, sizeof(ftp
));
596 if (page_id
>= ERR_MAX
&& ErrorDynamicPages
.items
[page_id
- ERR_MAX
]->page_redirect
!= Http::scNone
)
597 httpStatus
= ErrorDynamicPages
.items
[page_id
- ERR_MAX
]->page_redirect
;
601 HTTPMSGLOCK(request
);
602 src_addr
= req
->client_addr
;
607 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
609 assert(entry
->mem_obj
!= NULL
);
610 assert (entry
->isEmpty());
611 debugs(4, 4, "Creating an error page for entry " << entry
<<
612 " with errorstate " << err
<<
613 " page id " << err
->page_id
);
615 if (entry
->store_status
!= STORE_PENDING
) {
616 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
618 * If the entry is not STORE_PENDING, then no clients
619 * care about it, and we don't need to generate an
622 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
623 assert(entry
->mem_obj
->nclients
== 0);
628 if (err
->page_id
== TCP_RESET
) {
630 debugs(4, 2, "RSTing this reply");
631 err
->request
->flags
.resetTcp
= true;
635 entry
->lock("errorAppendEntry");
637 entry
->replaceHttpReply( err
->BuildHttpReply() );
640 entry
->negativeCache();
641 entry
->releaseRequest();
642 entry
->unlock("errorAppendEntry");
647 errorSend(const Comm::ConnectionPointer
&conn
, ErrorState
* err
)
650 debugs(4, 3, HERE
<< conn
<< ", err=" << err
);
651 assert(Comm::IsConnOpen(conn
));
653 rep
= err
->BuildHttpReply();
655 MemBuf
*mb
= rep
->pack();
656 AsyncCall::Pointer call
= commCbCall(78, 5, "errorSendComplete",
657 CommIoCbPtrFun(&errorSendComplete
, err
));
658 Comm::Write(conn
, mb
, call
);
665 \ingroup ErrorPageAPI
667 * Called by commHandleWrite() after data has been written
668 * to the client socket.
670 \note If there is a callback, the callback is responsible for
671 * closing the FD, otherwise we do it ourselves.
674 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
676 ErrorState
*err
= static_cast<ErrorState
*>(data
);
677 debugs(4, 3, HERE
<< conn
<< ", size=" << size
);
679 if (errflag
!= COMM_ERR_CLOSING
) {
681 debugs(4, 3, "errorSendComplete: callback");
682 err
->callback(conn
->fd
, err
->callback_data
, size
);
684 debugs(4, 3, "errorSendComplete: comm_close");
692 ErrorState::~ErrorState()
694 HTTPMSGUNLOCK(request
);
695 safe_free(redirect_url
);
697 safe_free(request_hdrs
);
698 wordlistDestroy(&ftp
.server_msg
);
699 safe_free(ftp
.request
);
700 safe_free(ftp
.reply
);
702 auth_user_request
= NULL
;
706 if (err_language
!= Config
.errorDefaultLanguage
)
708 safe_free(err_language
);
715 ErrorState::Dump(MemBuf
* mb
)
718 char ntoabuf
[MAX_IPSTRLEN
];
721 /* email subject line */
722 str
.Printf("CacheErrorInfo - %s", errorPageName(type
));
723 mb
->Printf("?subject=%s", rfc1738_escape_part(str
.buf
));
726 str
.Printf("CacheHost: %s\r\n", getMyHostname());
728 str
.Printf("ErrPage: %s\r\n", errorPageName(type
));
731 str
.Printf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
733 str
.Printf("Err: [none]\r\n");
736 if (auth_user_request
->denyMessage())
737 str
.Printf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
739 if (dnsError
.size() > 0)
740 str
.Printf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
743 str
.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
746 str
.Printf("ClientIP: %s\r\n", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
748 if (request
&& request
->hier
.host
[0] != '\0') {
749 str
.Printf("ServerIP: %s\r\n", request
->hier
.host
);
754 str
.Printf("HTTP Request:\r\n");
756 if (NULL
!= request
) {
758 String urlpath_or_slash
;
760 if (request
->urlpath
.size() != 0)
761 urlpath_or_slash
= request
->urlpath
;
763 urlpath_or_slash
= "/";
765 str
.Printf("%s " SQUIDSTRINGPH
" %s/%d.%d\n",
766 RequestMethodStr(request
->method
),
767 SQUIDSTRINGPRINT(urlpath_or_slash
),
768 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
769 request
->http_ver
.major
, request
->http_ver
.minor
);
770 packerToMemInit(&pck
, &str
);
771 request
->header
.packInto(&pck
);
779 str
.Printf("FTP Request: %s\r\n", ftp
.request
);
780 str
.Printf("FTP Reply: %s\r\n", (ftp
.reply
? ftp
.reply
:"[none]"));
781 str
.Printf("FTP Msg: ");
782 wordlistCat(ftp
.server_msg
, &str
);
787 mb
->Printf("&body=%s", rfc1738_escape_part(str
.buf
));
792 /// \ingroup ErrorPageInternal
793 #define CVT_BUF_SZ 512
796 ErrorState::Convert(char token
, bool building_deny_info_url
, bool allowRecursion
)
799 const char *p
= NULL
; /* takes priority over mb if set */
801 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
802 char ntoabuf
[MAX_IPSTRLEN
];
810 if (request
&& request
->auth_user_request
!= NULL
)
811 p
= request
->auth_user_request
->username();
818 mb
.Printf("%d", getMyPort());
822 if (building_deny_info_url
) break;
823 p
= request
? ftpUrlWith2f(request
) : "[no URL]";
827 if (building_deny_info_url
) break;
828 p
= errorPageName(type
);
833 p
= "%D"; // if recursion is not allowed, do not convert
835 // currently only SSL error details implemented
837 detail
->useRequest(request
);
838 const String
&errDetail
= detail
->toString();
839 if (errDetail
.size() > 0) {
840 MemBuf
*detail_mb
= ConvertText(errDetail
.termedBuf(), false);
841 mb
.append(detail_mb
->content(), detail_mb
->contentSize());
847 if (!mb
.contentSize())
848 mb
.Printf("[No Error Detail]");
852 mb
.Printf("%d", xerrno
);
857 mb
.Printf("(%d) %s", xerrno
, strerror(xerrno
));
859 mb
.Printf("[No Error]");
863 if (building_deny_info_url
) break;
864 /* FTP REQUEST LINE */
872 if (building_deny_info_url
) break;
881 if (building_deny_info_url
) break;
882 /* FTP SERVER RESPONSE */
884 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
886 } else if (ftp
.server_msg
) {
887 wordlistCat(ftp
.server_msg
, &mb
);
892 mb
.Printf("%s", getMyHostname());
897 if (request
->hier
.host
[0] != '\0') // if non-empty string.
898 p
= request
->hier
.host
;
900 p
= request
->GetHost();
901 } else if (!building_deny_info_url
)
902 p
= "[unknown host]";
906 mb
.Printf("%s", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
910 if (request
&& request
->hier
.tcpServer
!= NULL
)
911 p
= request
->hier
.tcpServer
->remote
.toStr(ntoabuf
,MAX_IPSTRLEN
);
912 else if (!building_deny_info_url
)
917 if (building_deny_info_url
) break;
918 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
923 if (building_deny_info_url
) break;
924 if (Config
.errHtmlText
) {
925 mb
.Printf("%s", Config
.errHtmlText
);
928 p
= "[not available]";
932 if (building_deny_info_url
) break;
934 p
= auth_user_request
->denyMessage("[not available]");
942 p
= RequestMethodStr(request
->method
);
943 else if (!building_deny_info_url
)
944 p
= "[unknown method]";
948 p
= request
? request
->extacl_message
.termedBuf() : external_acl_message
;
949 if (!p
&& !building_deny_info_url
)
950 p
= "[not available]";
955 mb
.Printf("%d", (int) request
->port
);
956 } else if (!building_deny_info_url
) {
957 p
= "[unknown port]";
963 p
= AnyP::ProtocolType_str
[request
->protocol
];
964 } else if (!building_deny_info_url
) {
965 p
= "[unknown protocol]";
970 if (building_deny_info_url
) {
971 p
= (request
->urlpath
.size() != 0 ? request
->urlpath
.termedBuf() : "/");
975 if (NULL
!= request
) {
977 String urlpath_or_slash
;
979 if (request
->urlpath
.size() != 0)
980 urlpath_or_slash
= request
->urlpath
;
982 urlpath_or_slash
= "/";
984 mb
.Printf("%s " SQUIDSTRINGPH
" %s/%d.%d\n",
985 RequestMethodStr(request
->method
),
986 SQUIDSTRINGPRINT(urlpath_or_slash
),
987 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
988 request
->http_ver
.major
, request
->http_ver
.minor
);
989 packerToMemInit(&pck
, &mb
);
990 request
->header
.packInto(&pck
, true); //hide authorization data
992 } else if (request_hdrs
) {
1000 /* for backward compat we make %s show the full URL. Drop this in some future release. */
1001 if (building_deny_info_url
) {
1002 p
= request
? urlCanonical(request
) : url
;
1003 debugs(0, DBG_CRITICAL
, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
1005 p
= visible_appname_string
;
1009 if (building_deny_info_url
) {
1010 p
= visible_appname_string
;
1013 /* signature may contain %-escapes, recursion */
1014 if (page_id
!= ERR_SQUID_SIGNATURE
) {
1015 const int saved_id
= page_id
;
1016 page_id
= ERR_SQUID_SIGNATURE
;
1017 MemBuf
*sign_mb
= BuildContent();
1018 mb
.Printf("%s", sign_mb
->content());
1024 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1030 mb
.Printf("%s", Time::FormatHttpd(squid_curtime
));
1034 mb
.Printf("%s", mkrfc1123(squid_curtime
));
1038 /* Using the fake-https version of canonical so error pages see https:// */
1039 /* even when the url-path cannot be shown as more than '*' */
1041 p
= urlCanonicalFakeHttps(request
);
1044 else if (!building_deny_info_url
)
1050 p
= urlCanonical(request
);
1053 else if (!building_deny_info_url
)
1058 if (Config
.adminEmail
)
1059 mb
.Printf("%s", Config
.adminEmail
);
1060 else if (!building_deny_info_url
)
1065 if (building_deny_info_url
) break;
1066 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
1074 mb
.Printf("%s", detail
->errorName());
1077 if (!building_deny_info_url
)
1078 p
= "[Unknown Error Code]";
1082 if (building_deny_info_url
) break;
1083 if (dnsError
.size() > 0)
1084 p
= dnsError
.termedBuf();
1085 else if (ftp
.cwd_msg
)
1092 if (building_deny_info_url
) break;
1104 mb
.Printf("%%%c", token
);
1110 p
= mb
.buf
; /* do not use mb after this assignment! */
1114 debugs(4, 3, "errorConvert: %%" << token
<< " --> '" << p
<< "'" );
1119 if (building_deny_info_url
&& !no_urlescape
)
1120 p
= rfc1738_escape_part(p
);
1126 ErrorState::DenyInfoLocation(const char *name
, HttpRequest
*aRequest
, MemBuf
&result
)
1128 char const *m
= name
;
1133 m
+= 4; // skip "3xx:"
1135 while ((p
= strchr(m
, '%'))) {
1136 result
.append(m
, p
- m
); /* copy */
1137 t
= Convert(*++p
, true, true); /* convert */
1138 result
.Printf("%s", t
); /* copy */
1139 m
= p
+ 1; /* advance */
1143 result
.Printf("%s", m
); /* copy tail */
1145 assert((size_t)result
.contentSize() == strlen(result
.content()));
1149 ErrorState::BuildHttpReply()
1151 HttpReply
*rep
= new HttpReply
;
1152 const char *name
= errorPageName(page_id
);
1153 /* no LMT for error pages; error pages expire immediately */
1155 if (name
[0] == '3' || (name
[0] != '2' && name
[0] != '4' && name
[0] != '5' && strchr(name
, ':'))) {
1157 Http::StatusCode status
= Http::scMovedTemporarily
;
1158 // Use configured 3xx reply status if set.
1160 status
= httpStatus
;
1162 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1163 if (request
->method
!= Http::METHOD_GET
&& request
->method
!= Http::METHOD_HEAD
&& request
->http_ver
>= Http::ProtocolVersion(1,1))
1164 status
= Http::scTemporaryRedirect
;
1167 rep
->setHeaders(status
, NULL
, "text/html;charset=utf-8", 0, 0, -1);
1170 MemBuf redirect_location
;
1171 redirect_location
.init();
1172 DenyInfoLocation(name
, request
, redirect_location
);
1173 httpHeaderPutStrf(&rep
->header
, HDR_LOCATION
, "%s", redirect_location
.content() );
1176 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
1178 MemBuf
*content
= BuildContent();
1179 rep
->setHeaders(httpStatus
, NULL
, "text/html;charset=utf-8", content
->contentSize(), 0, -1);
1181 * include some information for downstream caches. Implicit
1182 * replaceable content. This isn't quite sufficient. xerrno is not
1183 * necessarily meaningful to another system, so we really should
1184 * expand it. Additionally, we should identify ourselves. Someone
1185 * might want to know. Someone _will_ want to know OTOH, the first
1186 * X-CACHE-MISS entry should tell us who.
1188 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%s %d", name
, xerrno
);
1192 * If error page auto-negotiate is enabled in any way, send the Vary.
1193 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1194 * We have even better reasons though:
1195 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1197 if (!Config
.errorDirectory
) {
1198 /* We 'negotiated' this ONLY from the Accept-Language. */
1199 rep
->header
.delById(HDR_VARY
);
1200 rep
->header
.putStr(HDR_VARY
, "Accept-Language");
1203 /* add the Content-Language header according to RFC section 14.12 */
1205 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, err_language
);
1207 #endif /* USE_ERROR_LOCALES */
1209 /* default templates are in English */
1210 /* language is known unless error_directory override used */
1211 if (!Config
.errorDirectory
)
1212 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, "en");
1215 rep
->body
.setMb(content
);
1216 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1219 // Make sure error codes get back to the client side for logging and
1222 int edc
= ERR_DETAIL_NONE
; // error detail code
1225 edc
= detail
->errorNo();
1232 request
->detailError(type
, edc
);
1239 ErrorState::BuildContent()
1241 const char *m
= NULL
;
1243 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
1246 ErrorPageFile
*localeTmpl
= NULL
;
1248 /** error_directory option in squid.conf overrides translations.
1249 * Custom errors are always found either in error_directory or the templates directory.
1250 * Otherwise locate the Accept-Language header
1252 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
) {
1253 if (err_language
&& err_language
!= Config
.errorDefaultLanguage
)
1254 safe_free(err_language
);
1256 localeTmpl
= new ErrorPageFile(err_type_str
[page_id
], static_cast<err_type
>(page_id
));
1257 if (localeTmpl
->loadFor(request
)) {
1258 m
= localeTmpl
->text();
1259 assert(localeTmpl
->language());
1260 err_language
= xstrdup(localeTmpl
->language());
1263 #endif /* USE_ERR_LOCALES */
1266 * If client-specific error templates are not enabled or available.
1267 * fall back to the old style squid.conf settings.
1270 m
= error_text
[page_id
];
1272 if (!Config
.errorDirectory
)
1273 err_language
= Config
.errorDefaultLanguage
;
1275 debugs(4, 2, HERE
<< "No existing error page language negotiated for " << errorPageName(page_id
) << ". Using default error file.");
1278 MemBuf
*result
= ConvertText(m
, true);
1286 MemBuf
*ErrorState::ConvertText(const char *text
, bool allowRecursion
)
1288 MemBuf
*content
= new MemBuf
;
1290 const char *m
= text
;
1294 while ((p
= strchr(m
, '%'))) {
1295 content
->append(m
, p
- m
); /* copy */
1296 const char *t
= Convert(*++p
, false, allowRecursion
); /* convert */
1297 content
->Printf("%s", t
); /* copy */
1298 m
= p
+ 1; /* advance */
1302 content
->Printf("%s", m
); /* copy tail */
1304 content
->terminate();
1306 assert((size_t)content
->contentSize() == strlen(content
->content()));