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"
45 #include "MemObject.h"
49 #include "SquidConfig.h"
51 #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_status 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
.items
[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_STATUS_NONE
)
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
.size())
251 errorDynamicPageInfoDestroy(ErrorDynamicPages
.pop_back());
253 error_page_count
= 0;
256 Ssl::errorDetailClean();
260 /// \ingroup ErrorPageInternal
262 errorFindHardText(err_type type
)
266 for (i
= 0; i
< error_hard_text_count
; ++i
)
267 if (error_hard_text
[i
].type
== type
)
268 return error_hard_text
[i
].text
;
273 TemplateFile::TemplateFile(const char *name
, const err_type code
): silent(false), wasLoaded(false), templateName(name
), templateCode(code
)
279 TemplateFile::loadDefault()
281 if (loaded()) // already loaded?
284 /** test error_directory configured location */
285 if (Config
.errorDirectory
) {
286 char path
[MAXPATHLEN
];
287 snprintf(path
, sizeof(path
), "%s/%s", Config
.errorDirectory
, templateName
.termedBuf());
292 /** test error_default_language location */
293 if (!loaded() && Config
.errorDefaultLanguage
) {
294 if (!tryLoadTemplate(Config
.errorDefaultLanguage
)) {
295 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "Unable to load default error language files. Reset to backups.");
300 /* test default location if failed (templates == English translation base templates) */
302 tryLoadTemplate("templates");
305 /* giving up if failed */
307 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "WARNING: failed to find or read error text file " << templateName
);
308 parse("Internal Error: Missing Template ", 33, '\0');
309 parse(templateName
.termedBuf(), templateName
.size(), '\0');
316 TemplateFile::tryLoadTemplate(const char *lang
)
320 char path
[MAXPATHLEN
];
321 /* TODO: prep the directory path string to prevent snprintf ... */
322 snprintf(path
, sizeof(path
), "%s/%s/%s",
323 DEFAULT_SQUID_ERROR_DIR
, lang
, templateName
.termedBuf());
324 path
[MAXPATHLEN
-1] = '\0';
326 if (loadFromFile(path
))
330 if ( strlen(lang
) == 2) {
331 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
332 /* use first result. */
333 debugs(4,2, HERE
<< "wildcard fallback errors not coded yet.");
341 TemplateFile::loadFromFile(const char *path
)
347 if (loaded()) // already loaded?
350 fd
= file_open(path
, O_RDONLY
| O_TEXT
);
353 /* with dynamic locale negotiation we may see some failures before a success. */
354 if (!silent
&& templateCode
< TCP_RESET
)
355 debugs(4, DBG_CRITICAL
, HERE
<< "'" << path
<< "': " << xstrerror());
360 while ((len
= FD_READ_METHOD(fd
, buf
, sizeof(buf
))) > 0) {
361 if (!parse(buf
, len
, false)) {
362 debugs(4, DBG_CRITICAL
, HERE
<< " parse error while reading template file: " << path
);
370 debugs(4, DBG_CRITICAL
, HERE
<< "failed to fully read: '" << path
<< "': " << xstrerror());
379 bool strHdrAcptLangGetItem(const String
&hdr
, char *lang
, int langLen
, size_t &pos
)
381 while (pos
< hdr
.size()) {
385 /* skip any initial whitespace. */
386 while (pos
< hdr
.size() && xisspace(hdr
[pos
]))
389 // IFF we terminated the tag on whitespace or ';' we need to skip to the next ',' or end of header.
390 while (pos
< hdr
.size() && hdr
[pos
] != ',')
397 * Header value format:
398 * - sequence of whitespace delimited tags
399 * - each tag may suffix with ';'.* which we can ignore.
400 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
401 * with preference given to an exact match.
403 bool invalid_byte
= false;
404 while (pos
< hdr
.size() && hdr
[pos
] != ';' && hdr
[pos
] != ',' && !xisspace(hdr
[pos
]) && dt
< (lang
+ (langLen
-1)) ) {
406 #if USE_HTTP_VIOLATIONS
407 // if accepting violations we may as well accept some broken browsers
408 // which may send us the right code, wrong ISO formatting.
413 *dt
= xtolower(hdr
[pos
]);
414 // valid codes only contain A-Z, hyphen (-) and *
415 if (*dt
!= '-' && *dt
!= '*' && (*dt
< 'a' || *dt
> 'z') )
418 ++dt
; // move to next destination byte.
422 *dt
= '\0'; // nul-terminated the filename content string before system use.
425 debugs(4, 9, HERE
<< "STATE: dt='" << dt
<< "', lang='" << lang
<< "', pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
427 /* if we found anything we might use, try it. */
428 if (*lang
!= '\0' && !invalid_byte
)
435 TemplateFile::loadFor(HttpRequest
*request
)
440 if (loaded()) // already loaded?
443 if (!request
|| !request
->header
.getList(HDR_ACCEPT_LANGUAGE
, &hdr
) )
447 size_t pos
= 0; // current parsing position in header string
449 debugs(4, 6, HERE
<< "Testing Header: '" << hdr
<< "'");
451 while ( strHdrAcptLangGetItem(hdr
, lang
, 256, pos
) ) {
453 /* wildcard uses the configured default language */
454 if (lang
[0] == '*' && lang
[1] == '\0') {
455 debugs(4, 6, HERE
<< "Found language '" << lang
<< "'. Using configured default.");
459 debugs(4, 6, HERE
<< "Found language '" << lang
<< "', testing for available template");
461 if (tryLoadTemplate(lang
)) {
462 /* store the language we found for the Content-Language reply header */
465 } else if (Config
.errorLogMissingLanguages
) {
466 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << lang
);
474 /// \ingroup ErrorPageInternal
475 static ErrorDynamicPageInfo
*
476 errorDynamicPageInfoCreate(int id
, const char *page_name
)
478 ErrorDynamicPageInfo
*info
= new ErrorDynamicPageInfo
;
480 info
->page_name
= xstrdup(page_name
);
481 info
->page_redirect
= static_cast<http_status
>(atoi(page_name
));
483 /* WARNING on redirection status:
484 * 2xx are permitted, but not documented officially.
485 * - might be useful for serving static files (PAC etc) in special cases
486 * 3xx require a URL suitable for Location: header.
487 * - the current design does not allow for a Location: URI as well as a local file template
488 * although this possibility is explicitly permitted in the specs.
489 * 4xx-5xx require a local file template.
490 * - sending Location: on these codes with no body is invalid by the specs.
491 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
492 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
494 if (info
->page_redirect
== HTTP_STATUS_NONE
)
495 ; // special case okay.
496 else if (info
->page_redirect
< 200 || info
->page_redirect
> 599) {
498 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
500 } else if ( /* >= 200 && */ info
->page_redirect
< 300 && strchr(&(page_name
[4]), ':')) {
501 // 2xx require a local template file
502 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
504 } else if (info
->page_redirect
>= 300 && info
->page_redirect
<= 399 && !strchr(&(page_name
[4]), ':')) {
505 // 3xx require an absolute URL
506 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a URL on '" << page_name
<< "'");
508 } else if (info
->page_redirect
>= 400 /* && <= 599 */ && strchr(&(page_name
[4]), ':')) {
509 // 4xx/5xx require a local template file
510 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
518 /// \ingroup ErrorPageInternal
520 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
)
523 safe_free(info
->page_name
);
527 /// \ingroup ErrorPageInternal
529 errorPageId(const char *page_name
)
531 for (int i
= 0; i
< ERR_MAX
; ++i
) {
532 if (strcmp(err_type_str
[i
], page_name
) == 0)
536 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); ++j
) {
537 if (strcmp(ErrorDynamicPages
.items
[j
]->page_name
, page_name
) == 0)
545 errorReservePageId(const char *page_name
)
547 ErrorDynamicPageInfo
*info
;
548 int id
= errorPageId(page_name
);
550 if (id
== ERR_NONE
) {
551 info
= errorDynamicPageInfoCreate(ERR_MAX
+ ErrorDynamicPages
.size(), page_name
);
552 ErrorDynamicPages
.push_back(info
);
559 /// \ingroup ErrorPageInternal
561 errorPageName(int pageId
)
563 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
564 return err_type_str
[pageId
];
566 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
567 return ErrorDynamicPages
.items
[pageId
- ERR_MAX
]->page_name
;
569 return "ERR_UNKNOWN"; /* should not happen */
572 ErrorState::ErrorState(err_type t
, http_status status
, HttpRequest
* req
) :
578 auth_user_request (NULL
),
595 detailCode(ERR_DETAIL_NONE
)
597 memset(&flags
, 0, sizeof(flags
));
598 memset(&ftp
, 0, sizeof(ftp
));
600 if (page_id
>= ERR_MAX
&& ErrorDynamicPages
.items
[page_id
- ERR_MAX
]->page_redirect
!= HTTP_STATUS_NONE
)
601 httpStatus
= ErrorDynamicPages
.items
[page_id
- ERR_MAX
]->page_redirect
;
604 request
= HTTPMSGLOCK(req
);
605 src_addr
= req
->client_addr
;
610 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
612 assert(entry
->mem_obj
!= NULL
);
613 assert (entry
->isEmpty());
614 debugs(4, 4, "Creating an error page for entry " << entry
<<
615 " with errorstate " << err
<<
616 " page id " << err
->page_id
);
618 if (entry
->store_status
!= STORE_PENDING
) {
619 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
621 * If the entry is not STORE_PENDING, then no clients
622 * care about it, and we don't need to generate an
625 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
626 assert(entry
->mem_obj
->nclients
== 0);
631 if (err
->page_id
== TCP_RESET
) {
633 debugs(4, 2, "RSTing this reply");
634 err
->request
->flags
.resetTcp
=true;
640 entry
->replaceHttpReply( err
->BuildHttpReply() );
641 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
644 entry
->negativeCache();
645 entry
->releaseRequest();
651 errorSend(const Comm::ConnectionPointer
&conn
, ErrorState
* err
)
654 debugs(4, 3, HERE
<< conn
<< ", err=" << err
);
655 assert(Comm::IsConnOpen(conn
));
657 /* moved in front of errorBuildBuf @?@ */
658 err
->flags
.flag_cbdata
= 1;
660 rep
= err
->BuildHttpReply();
662 MemBuf
*mb
= rep
->pack();
663 AsyncCall::Pointer call
= commCbCall(78, 5, "errorSendComplete",
664 CommIoCbPtrFun(&errorSendComplete
, err
));
665 Comm::Write(conn
, mb
, call
);
672 \ingroup ErrorPageAPI
674 * Called by commHandleWrite() after data has been written
675 * to the client socket.
677 \note If there is a callback, the callback is responsible for
678 * closing the FD, otherwise we do it ourselves.
681 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
683 ErrorState
*err
= static_cast<ErrorState
*>(data
);
684 debugs(4, 3, HERE
<< conn
<< ", size=" << size
);
686 if (errflag
!= COMM_ERR_CLOSING
) {
688 debugs(4, 3, "errorSendComplete: callback");
689 err
->callback(conn
->fd
, err
->callback_data
, size
);
691 debugs(4, 3, "errorSendComplete: comm_close");
699 ErrorState::~ErrorState()
701 HTTPMSGUNLOCK(request
);
702 safe_free(redirect_url
);
704 safe_free(request_hdrs
);
705 wordlistDestroy(&ftp
.server_msg
);
706 safe_free(ftp
.request
);
707 safe_free(ftp
.reply
);
709 auth_user_request
= NULL
;
713 if (err_language
!= Config
.errorDefaultLanguage
)
715 safe_free(err_language
);
722 ErrorState::Dump(MemBuf
* mb
)
725 char ntoabuf
[MAX_IPSTRLEN
];
728 /* email subject line */
729 str
.Printf("CacheErrorInfo - %s", errorPageName(type
));
730 mb
->Printf("?subject=%s", rfc1738_escape_part(str
.buf
));
733 str
.Printf("CacheHost: %s\r\n", getMyHostname());
735 str
.Printf("ErrPage: %s\r\n", errorPageName(type
));
738 str
.Printf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
740 str
.Printf("Err: [none]\r\n");
743 if (auth_user_request
->denyMessage())
744 str
.Printf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
746 if (dnsError
.size() > 0)
747 str
.Printf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
750 str
.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
753 str
.Printf("ClientIP: %s\r\n", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
755 if (request
&& request
->hier
.host
[0] != '\0') {
756 str
.Printf("ServerIP: %s\r\n", request
->hier
.host
);
761 str
.Printf("HTTP Request:\r\n");
763 if (NULL
!= request
) {
765 String urlpath_or_slash
;
767 if (request
->urlpath
.size() != 0)
768 urlpath_or_slash
= request
->urlpath
;
770 urlpath_or_slash
= "/";
772 str
.Printf("%s " SQUIDSTRINGPH
" %s/%d.%d\n",
773 RequestMethodStr(request
->method
),
774 SQUIDSTRINGPRINT(urlpath_or_slash
),
775 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
776 request
->http_ver
.major
, request
->http_ver
.minor
);
777 packerToMemInit(&pck
, &str
);
778 request
->header
.packInto(&pck
);
786 str
.Printf("FTP Request: %s\r\n", ftp
.request
);
787 str
.Printf("FTP Reply: %s\r\n", (ftp
.reply
? ftp
.reply
:"[none]"));
788 str
.Printf("FTP Msg: ");
789 wordlistCat(ftp
.server_msg
, &str
);
794 mb
->Printf("&body=%s", rfc1738_escape_part(str
.buf
));
799 /// \ingroup ErrorPageInternal
800 #define CVT_BUF_SZ 512
803 ErrorState::Convert(char token
, bool building_deny_info_url
, bool allowRecursion
)
806 const char *p
= NULL
; /* takes priority over mb if set */
808 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
809 char ntoabuf
[MAX_IPSTRLEN
];
817 if (request
&& request
->auth_user_request
!= NULL
)
818 p
= request
->auth_user_request
->username();
825 mb
.Printf("%d", getMyPort());
829 if (building_deny_info_url
) break;
830 p
= request
? ftpUrlWith2f(request
) : "[no URL]";
834 if (building_deny_info_url
) break;
835 p
= errorPageName(type
);
840 p
= "%D"; // if recursion is not allowed, do not convert
842 // currently only SSL error details implemented
844 detail
->useRequest(request
);
845 const String
&errDetail
= detail
->toString();
846 if (errDetail
.defined()) {
847 MemBuf
*detail_mb
= ConvertText(errDetail
.termedBuf(), false);
848 mb
.append(detail_mb
->content(), detail_mb
->contentSize());
854 if (!mb
.contentSize())
855 mb
.Printf("[No Error Detail]");
859 mb
.Printf("%d", xerrno
);
864 mb
.Printf("(%d) %s", xerrno
, strerror(xerrno
));
866 mb
.Printf("[No Error]");
870 if (building_deny_info_url
) break;
871 /* FTP REQUEST LINE */
879 if (building_deny_info_url
) break;
888 if (building_deny_info_url
) break;
889 /* FTP SERVER RESPONSE */
891 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
893 } else if (ftp
.server_msg
) {
894 wordlistCat(ftp
.server_msg
, &mb
);
899 mb
.Printf("%s", getMyHostname());
904 if (request
->hier
.host
[0] != '\0') // if non-empty string.
905 p
= request
->hier
.host
;
907 p
= request
->GetHost();
908 } else if (!building_deny_info_url
)
909 p
= "[unknown host]";
913 mb
.Printf("%s", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
917 if (request
&& request
->hier
.tcpServer
!= NULL
)
918 p
= request
->hier
.tcpServer
->remote
.NtoA(ntoabuf
,MAX_IPSTRLEN
);
919 else if (!building_deny_info_url
)
924 if (building_deny_info_url
) break;
925 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
930 if (building_deny_info_url
) break;
931 if (Config
.errHtmlText
) {
932 mb
.Printf("%s", Config
.errHtmlText
);
935 p
= "[not available]";
939 if (building_deny_info_url
) break;
941 p
= auth_user_request
->denyMessage("[not available]");
949 p
= RequestMethodStr(request
->method
);
950 else if (!building_deny_info_url
)
951 p
= "[unknown method]";
955 p
= request
? request
->extacl_message
.termedBuf() : external_acl_message
;
956 if (!p
&& !building_deny_info_url
)
957 p
= "[not available]";
962 mb
.Printf("%d", (int) request
->port
);
963 } else if (!building_deny_info_url
) {
964 p
= "[unknown port]";
970 p
= AnyP::ProtocolType_str
[request
->protocol
];
971 } else if (!building_deny_info_url
) {
972 p
= "[unknown protocol]";
977 if (building_deny_info_url
) {
978 p
= (request
->urlpath
.size() != 0 ? request
->urlpath
.termedBuf() : "/");
982 if (NULL
!= request
) {
984 String urlpath_or_slash
;
986 if (request
->urlpath
.size() != 0)
987 urlpath_or_slash
= request
->urlpath
;
989 urlpath_or_slash
= "/";
991 mb
.Printf("%s " SQUIDSTRINGPH
" %s/%d.%d\n",
992 RequestMethodStr(request
->method
),
993 SQUIDSTRINGPRINT(urlpath_or_slash
),
994 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
995 request
->http_ver
.major
, request
->http_ver
.minor
);
996 packerToMemInit(&pck
, &mb
);
997 request
->header
.packInto(&pck
, true); //hide authorization data
999 } else if (request_hdrs
) {
1007 /* for backward compat we make %s show the full URL. Drop this in some future release. */
1008 if (building_deny_info_url
) {
1009 p
= request
? urlCanonical(request
) : url
;
1010 debugs(0, DBG_CRITICAL
, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
1012 p
= visible_appname_string
;
1016 if (building_deny_info_url
) {
1017 p
= visible_appname_string
;
1020 /* signature may contain %-escapes, recursion */
1021 if (page_id
!= ERR_SQUID_SIGNATURE
) {
1022 const int saved_id
= page_id
;
1023 page_id
= ERR_SQUID_SIGNATURE
;
1024 MemBuf
*sign_mb
= BuildContent();
1025 mb
.Printf("%s", sign_mb
->content());
1031 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1037 mb
.Printf("%s", Time::FormatHttpd(squid_curtime
));
1041 mb
.Printf("%s", mkrfc1123(squid_curtime
));
1045 /* Using the fake-https version of canonical so error pages see https:// */
1046 /* even when the url-path cannot be shown as more than '*' */
1048 p
= urlCanonicalFakeHttps(request
);
1051 else if (!building_deny_info_url
)
1057 p
= urlCanonical(request
);
1060 else if (!building_deny_info_url
)
1065 if (Config
.adminEmail
)
1066 mb
.Printf("%s", Config
.adminEmail
);
1067 else if (!building_deny_info_url
)
1072 if (building_deny_info_url
) break;
1073 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
1081 mb
.Printf("%s", detail
->errorName());
1084 if (!building_deny_info_url
)
1085 p
= "[Unknown Error Code]";
1089 if (building_deny_info_url
) break;
1090 if (dnsError
.size() > 0)
1091 p
= dnsError
.termedBuf();
1092 else if (ftp
.cwd_msg
)
1099 if (building_deny_info_url
) break;
1111 mb
.Printf("%%%c", token
);
1117 p
= mb
.buf
; /* do not use mb after this assignment! */
1121 debugs(4, 3, "errorConvert: %%" << token
<< " --> '" << p
<< "'" );
1126 if (building_deny_info_url
&& !no_urlescape
)
1127 p
= rfc1738_escape_part(p
);
1133 ErrorState::DenyInfoLocation(const char *name
, HttpRequest
*aRequest
, MemBuf
&result
)
1135 char const *m
= name
;
1140 m
+= 4; // skip "3xx:"
1142 while ((p
= strchr(m
, '%'))) {
1143 result
.append(m
, p
- m
); /* copy */
1144 t
= Convert(*++p
, true, true); /* convert */
1145 result
.Printf("%s", t
); /* copy */
1146 m
= p
+ 1; /* advance */
1150 result
.Printf("%s", m
); /* copy tail */
1152 assert((size_t)result
.contentSize() == strlen(result
.content()));
1156 ErrorState::BuildHttpReply()
1158 HttpReply
*rep
= new HttpReply
;
1159 const char *name
= errorPageName(page_id
);
1160 /* no LMT for error pages; error pages expire immediately */
1162 if (name
[0] == '3' || (name
[0] != '2' && name
[0] != '4' && name
[0] != '5' && strchr(name
, ':'))) {
1164 http_status status
= HTTP_MOVED_TEMPORARILY
;
1165 // Use configured 3xx reply status if set.
1167 status
= httpStatus
;
1169 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1170 if (request
->method
!= METHOD_GET
&& request
->method
!= METHOD_HEAD
&& request
->http_ver
>= HttpVersion(1,1))
1171 status
= HTTP_TEMPORARY_REDIRECT
;
1174 rep
->setHeaders(status
, NULL
, "text/html", 0, 0, -1);
1177 MemBuf redirect_location
;
1178 redirect_location
.init();
1179 DenyInfoLocation(name
, request
, redirect_location
);
1180 httpHeaderPutStrf(&rep
->header
, HDR_LOCATION
, "%s", redirect_location
.content() );
1183 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
1185 MemBuf
*content
= BuildContent();
1186 rep
->setHeaders(httpStatus
, NULL
, "text/html", content
->contentSize(), 0, -1);
1188 * include some information for downstream caches. Implicit
1189 * replaceable content. This isn't quite sufficient. xerrno is not
1190 * necessarily meaningful to another system, so we really should
1191 * expand it. Additionally, we should identify ourselves. Someone
1192 * might want to know. Someone _will_ want to know OTOH, the first
1193 * X-CACHE-MISS entry should tell us who.
1195 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%s %d", name
, xerrno
);
1199 * If error page auto-negotiate is enabled in any way, send the Vary.
1200 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1201 * We have even better reasons though:
1202 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1204 if (!Config
.errorDirectory
) {
1205 /* We 'negotiated' this ONLY from the Accept-Language. */
1206 rep
->header
.delById(HDR_VARY
);
1207 rep
->header
.putStr(HDR_VARY
, "Accept-Language");
1210 /* add the Content-Language header according to RFC section 14.12 */
1212 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, err_language
);
1214 #endif /* USE_ERROR_LOCALES */
1216 /* default templates are in English */
1217 /* language is known unless error_directory override used */
1218 if (!Config
.errorDirectory
)
1219 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, "en");
1222 rep
->body
.setMb(content
);
1223 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1226 // Make sure error codes get back to the client side for logging and
1229 int edc
= ERR_DETAIL_NONE
; // error detail code
1232 edc
= detail
->errorNo();
1239 request
->detailError(type
, edc
);
1246 ErrorState::BuildContent()
1248 const char *m
= NULL
;
1250 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
1253 ErrorPageFile
*localeTmpl
= NULL
;
1255 /** error_directory option in squid.conf overrides translations.
1256 * Custom errors are always found either in error_directory or the templates directory.
1257 * Otherwise locate the Accept-Language header
1259 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
) {
1260 if (err_language
&& err_language
!= Config
.errorDefaultLanguage
)
1261 safe_free(err_language
);
1263 localeTmpl
= new ErrorPageFile(err_type_str
[page_id
], static_cast<err_type
>(page_id
));
1264 if (localeTmpl
->loadFor(request
)) {
1265 m
= localeTmpl
->text();
1266 assert(localeTmpl
->language());
1267 err_language
= xstrdup(localeTmpl
->language());
1270 #endif /* USE_ERR_LOCALES */
1273 * If client-specific error templates are not enabled or available.
1274 * fall back to the old style squid.conf settings.
1277 m
= error_text
[page_id
];
1279 if (!Config
.errorDirectory
)
1280 err_language
= Config
.errorDefaultLanguage
;
1282 debugs(4, 2, HERE
<< "No existing error page language negotiated for " << errorPageName(page_id
) << ". Using default error file.");
1285 MemBuf
*result
= ConvertText(m
, true);
1293 MemBuf
*ErrorState::ConvertText(const char *text
, bool allowRecursion
)
1295 MemBuf
*content
= new MemBuf
;
1297 const char *m
= text
;
1301 while ((p
= strchr(m
, '%'))) {
1302 content
->append(m
, p
- m
); /* copy */
1303 const char *t
= Convert(*++p
, false, allowRecursion
); /* convert */
1304 content
->Printf("%s", t
); /* copy */
1305 m
= p
+ 1; /* advance */
1309 content
->Printf("%s", m
); /* copy tail */
1311 assert((size_t)content
->contentSize() == strlen(content
->content()));