]>
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 std::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
.at(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
.empty()) {
249 errorDynamicPageInfoDestroy(ErrorDynamicPages
.back());
250 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()) {
384 /* skip any initial whitespace. */
385 while (pos
< hdr
.size() && xisspace(hdr
[pos
]))
389 * Header value format:
390 * - sequence of whitespace delimited tags
391 * - each tag may suffix with ';'.* which we can ignore.
392 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
393 * with preference given to an exact match.
395 bool invalid_byte
= false;
396 while (pos
< hdr
.size() && hdr
[pos
] != ';' && hdr
[pos
] != ',' && !xisspace(hdr
[pos
]) && dt
< (lang
+ (langLen
-1)) ) {
398 #if USE_HTTP_VIOLATIONS
399 // if accepting violations we may as well accept some broken browsers
400 // which may send us the right code, wrong ISO formatting.
405 *dt
= xtolower(hdr
[pos
]);
406 // valid codes only contain A-Z, hyphen (-) and *
407 if (*dt
!= '-' && *dt
!= '*' && (*dt
< 'a' || *dt
> 'z') )
410 ++dt
; // move to next destination byte.
414 *dt
= '\0'; // nul-terminated the filename content string before system use.
417 // if we terminated the tag on garbage or ';' we need to skip to the next ',' or end of header.
418 while (pos
< hdr
.size() && hdr
[pos
] != ',')
421 if (pos
< hdr
.size() && hdr
[pos
] == ',')
424 debugs(4, 9, HERE
<< "STATE: dt='" << dt
<< "', lang='" << lang
<< "', pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
426 /* if we found anything we might use, try it. */
427 if (*lang
!= '\0' && !invalid_byte
)
434 TemplateFile::loadFor(const HttpRequest
*request
)
439 if (loaded()) // already loaded?
442 if (!request
|| !request
->header
.getList(HDR_ACCEPT_LANGUAGE
, &hdr
) )
446 size_t pos
= 0; // current parsing position in header string
448 debugs(4, 6, HERE
<< "Testing Header: '" << hdr
<< "'");
450 while ( strHdrAcptLangGetItem(hdr
, lang
, 256, pos
) ) {
452 /* wildcard uses the configured default language */
453 if (lang
[0] == '*' && lang
[1] == '\0') {
454 debugs(4, 6, HERE
<< "Found language '" << lang
<< "'. Using configured default.");
458 debugs(4, 6, HERE
<< "Found language '" << lang
<< "', testing for available template");
460 if (tryLoadTemplate(lang
)) {
461 /* store the language we found for the Content-Language reply header */
464 } else if (Config
.errorLogMissingLanguages
) {
465 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << lang
);
473 /// \ingroup ErrorPageInternal
474 static ErrorDynamicPageInfo
*
475 errorDynamicPageInfoCreate(int id
, const char *page_name
)
477 ErrorDynamicPageInfo
*info
= new ErrorDynamicPageInfo
;
479 info
->page_name
= xstrdup(page_name
);
480 info
->page_redirect
= static_cast<Http::StatusCode
>(atoi(page_name
));
482 /* WARNING on redirection status:
483 * 2xx are permitted, but not documented officially.
484 * - might be useful for serving static files (PAC etc) in special cases
485 * 3xx require a URL suitable for Location: header.
486 * - the current design does not allow for a Location: URI as well as a local file template
487 * although this possibility is explicitly permitted in the specs.
488 * 4xx-5xx require a local file template.
489 * - sending Location: on these codes with no body is invalid by the specs.
490 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
491 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
493 if (info
->page_redirect
== Http::scNone
)
494 ; // special case okay.
495 else if (info
->page_redirect
< 200 || info
->page_redirect
> 599) {
497 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
499 } else if ( /* >= 200 && */ info
->page_redirect
< 300 && strchr(&(page_name
[4]), ':')) {
500 // 2xx require a local template file
501 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
503 } else if (info
->page_redirect
>= 300 && info
->page_redirect
<= 399 && !strchr(&(page_name
[4]), ':')) {
504 // 3xx require an absolute URL
505 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a URL on '" << page_name
<< "'");
507 } else if (info
->page_redirect
>= 400 /* && <= 599 */ && strchr(&(page_name
[4]), ':')) {
508 // 4xx/5xx require a local template file
509 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
517 /// \ingroup ErrorPageInternal
519 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
)
522 safe_free(info
->page_name
);
526 /// \ingroup ErrorPageInternal
528 errorPageId(const char *page_name
)
530 for (int i
= 0; i
< ERR_MAX
; ++i
) {
531 if (strcmp(err_type_str
[i
], page_name
) == 0)
535 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); ++j
) {
536 if (strcmp(ErrorDynamicPages
[j
]->page_name
, page_name
) == 0)
544 errorReservePageId(const char *page_name
)
546 ErrorDynamicPageInfo
*info
;
547 int id
= errorPageId(page_name
);
549 if (id
== ERR_NONE
) {
550 info
= errorDynamicPageInfoCreate(ERR_MAX
+ ErrorDynamicPages
.size(), page_name
);
551 ErrorDynamicPages
.push_back(info
);
558 /// \ingroup ErrorPageInternal
560 errorPageName(int pageId
)
562 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
563 return err_type_str
[pageId
];
565 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
566 return ErrorDynamicPages
[pageId
- ERR_MAX
]->page_name
;
568 return "ERR_UNKNOWN"; /* should not happen */
572 ErrorState::NewForwarding(err_type type
, HttpRequest
*request
)
575 const Http::StatusCode status
= request
->flags
.needValidation
?
576 Http::scGatewayTimeout
: Http::scServiceUnavailable
;
577 return new ErrorState(type
, status
, request
);
580 ErrorState::ErrorState(err_type t
, Http::StatusCode status
, HttpRequest
* req
) :
586 auth_user_request (NULL
),
603 detailCode(ERR_DETAIL_NONE
)
605 memset(&ftp
, 0, sizeof(ftp
));
607 if (page_id
>= ERR_MAX
&& ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
!= Http::scNone
)
608 httpStatus
= ErrorDynamicPages
[page_id
- ERR_MAX
]->page_redirect
;
612 HTTPMSGLOCK(request
);
613 src_addr
= req
->client_addr
;
618 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
620 assert(entry
->mem_obj
!= NULL
);
621 assert (entry
->isEmpty());
622 debugs(4, 4, "Creating an error page for entry " << entry
<<
623 " with errorstate " << err
<<
624 " page id " << err
->page_id
);
626 if (entry
->store_status
!= STORE_PENDING
) {
627 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
629 * If the entry is not STORE_PENDING, then no clients
630 * care about it, and we don't need to generate an
633 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
634 assert(entry
->mem_obj
->nclients
== 0);
639 if (err
->page_id
== TCP_RESET
) {
641 debugs(4, 2, "RSTing this reply");
642 err
->request
->flags
.resetTcp
= true;
646 entry
->lock("errorAppendEntry");
648 entry
->replaceHttpReply( err
->BuildHttpReply() );
651 entry
->negativeCache();
652 entry
->releaseRequest();
653 entry
->unlock("errorAppendEntry");
658 errorSend(const Comm::ConnectionPointer
&conn
, ErrorState
* err
)
661 debugs(4, 3, HERE
<< conn
<< ", err=" << err
);
662 assert(Comm::IsConnOpen(conn
));
664 rep
= err
->BuildHttpReply();
666 MemBuf
*mb
= rep
->pack();
667 AsyncCall::Pointer call
= commCbCall(78, 5, "errorSendComplete",
668 CommIoCbPtrFun(&errorSendComplete
, err
));
669 Comm::Write(conn
, mb
, call
);
676 \ingroup ErrorPageAPI
678 * Called by commHandleWrite() after data has been written
679 * to the client socket.
681 \note If there is a callback, the callback is responsible for
682 * closing the FD, otherwise we do it ourselves.
685 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
687 ErrorState
*err
= static_cast<ErrorState
*>(data
);
688 debugs(4, 3, HERE
<< conn
<< ", size=" << size
);
690 if (errflag
!= COMM_ERR_CLOSING
) {
692 debugs(4, 3, "errorSendComplete: callback");
693 err
->callback(conn
->fd
, err
->callback_data
, size
);
695 debugs(4, 3, "errorSendComplete: comm_close");
703 ErrorState::~ErrorState()
705 HTTPMSGUNLOCK(request
);
706 safe_free(redirect_url
);
708 safe_free(request_hdrs
);
709 wordlistDestroy(&ftp
.server_msg
);
710 safe_free(ftp
.request
);
711 safe_free(ftp
.reply
);
713 auth_user_request
= NULL
;
717 if (err_language
!= Config
.errorDefaultLanguage
)
719 safe_free(err_language
);
726 ErrorState::Dump(MemBuf
* mb
)
729 char ntoabuf
[MAX_IPSTRLEN
];
732 /* email subject line */
733 str
.Printf("CacheErrorInfo - %s", errorPageName(type
));
734 mb
->Printf("?subject=%s", rfc1738_escape_part(str
.buf
));
737 str
.Printf("CacheHost: %s\r\n", getMyHostname());
739 str
.Printf("ErrPage: %s\r\n", errorPageName(type
));
742 str
.Printf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
744 str
.Printf("Err: [none]\r\n");
747 if (auth_user_request
->denyMessage())
748 str
.Printf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
750 if (dnsError
.size() > 0)
751 str
.Printf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
754 str
.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
757 str
.Printf("ClientIP: %s\r\n", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
759 if (request
&& request
->hier
.host
[0] != '\0') {
760 str
.Printf("ServerIP: %s\r\n", request
->hier
.host
);
765 str
.Printf("HTTP Request:\r\n");
767 if (NULL
!= request
) {
769 String urlpath_or_slash
;
771 if (request
->urlpath
.size() != 0)
772 urlpath_or_slash
= request
->urlpath
;
774 urlpath_or_slash
= "/";
776 str
.Printf(SQUIDSBUFPH
" " SQUIDSTRINGPH
" %s/%d.%d\n",
777 SQUIDSBUFPRINT(request
->method
.image()),
778 SQUIDSTRINGPRINT(urlpath_or_slash
),
779 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
780 request
->http_ver
.major
, request
->http_ver
.minor
);
781 packerToMemInit(&pck
, &str
);
782 request
->header
.packInto(&pck
);
790 str
.Printf("FTP Request: %s\r\n", ftp
.request
);
791 str
.Printf("FTP Reply: %s\r\n", (ftp
.reply
? ftp
.reply
:"[none]"));
792 str
.Printf("FTP Msg: ");
793 wordlistCat(ftp
.server_msg
, &str
);
798 mb
->Printf("&body=%s", rfc1738_escape_part(str
.buf
));
803 /// \ingroup ErrorPageInternal
804 #define CVT_BUF_SZ 512
807 ErrorState::Convert(char token
, bool building_deny_info_url
, bool allowRecursion
)
810 const char *p
= NULL
; /* takes priority over mb if set */
812 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
813 char ntoabuf
[MAX_IPSTRLEN
];
821 if (request
&& request
->auth_user_request
!= NULL
)
822 p
= request
->auth_user_request
->username();
829 mb
.Printf("%d", getMyPort());
833 if (building_deny_info_url
) break;
834 p
= request
? ftpUrlWith2f(request
) : "[no URL]";
838 if (building_deny_info_url
) break;
839 p
= errorPageName(type
);
844 p
= "%D"; // if recursion is not allowed, do not convert
846 // currently only SSL error details implemented
848 detail
->useRequest(request
);
849 const String
&errDetail
= detail
->toString();
850 if (errDetail
.size() > 0) {
851 MemBuf
*detail_mb
= ConvertText(errDetail
.termedBuf(), false);
852 mb
.append(detail_mb
->content(), detail_mb
->contentSize());
858 if (!mb
.contentSize())
859 mb
.Printf("[No Error Detail]");
863 mb
.Printf("%d", xerrno
);
868 mb
.Printf("(%d) %s", xerrno
, strerror(xerrno
));
870 mb
.Printf("[No Error]");
874 if (building_deny_info_url
) break;
875 /* FTP REQUEST LINE */
883 if (building_deny_info_url
) break;
892 if (building_deny_info_url
) break;
893 /* FTP SERVER RESPONSE */
895 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
897 } else if (ftp
.server_msg
) {
898 wordlistCat(ftp
.server_msg
, &mb
);
903 mb
.Printf("%s", getMyHostname());
908 if (request
->hier
.host
[0] != '\0') // if non-empty string.
909 p
= request
->hier
.host
;
911 p
= request
->GetHost();
912 } else if (!building_deny_info_url
)
913 p
= "[unknown host]";
917 mb
.Printf("%s", src_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
));
921 if (request
&& request
->hier
.tcpServer
!= NULL
)
922 p
= request
->hier
.tcpServer
->remote
.toStr(ntoabuf
,MAX_IPSTRLEN
);
923 else if (!building_deny_info_url
)
928 if (building_deny_info_url
) break;
929 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
934 if (building_deny_info_url
) break;
935 if (Config
.errHtmlText
) {
936 mb
.Printf("%s", Config
.errHtmlText
);
939 p
= "[not available]";
943 if (building_deny_info_url
) break;
945 p
= auth_user_request
->denyMessage("[not available]");
953 const SBuf
&m
= request
->method
.image();
954 mb
.append(m
.rawContent(), m
.length());
955 } else if (!building_deny_info_url
)
956 p
= "[unknown method]";
960 p
= request
? request
->extacl_message
.termedBuf() : external_acl_message
;
961 if (!p
&& !building_deny_info_url
)
962 p
= "[not available]";
967 mb
.Printf("%d", (int) request
->port
);
968 } else if (!building_deny_info_url
) {
969 p
= "[unknown port]";
975 p
= request
->url
.getScheme().c_str();
976 } else if (!building_deny_info_url
) {
977 p
= "[unknown protocol]";
982 if (building_deny_info_url
) {
983 p
= (request
->urlpath
.size() != 0 ? request
->urlpath
.termedBuf() : "/");
987 if (NULL
!= request
) {
989 String urlpath_or_slash
;
991 if (request
->urlpath
.size() != 0)
992 urlpath_or_slash
= request
->urlpath
;
994 urlpath_or_slash
= "/";
996 mb
.Printf(SQUIDSBUFPH
" " SQUIDSTRINGPH
" %s/%d.%d\n",
997 SQUIDSBUFPRINT(request
->method
.image()),
998 SQUIDSTRINGPRINT(urlpath_or_slash
),
999 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
1000 request
->http_ver
.major
, request
->http_ver
.minor
);
1001 packerToMemInit(&pck
, &mb
);
1002 request
->header
.packInto(&pck
, true); //hide authorization data
1004 } else if (request_hdrs
) {
1012 /* for backward compat we make %s show the full URL. Drop this in some future release. */
1013 if (building_deny_info_url
) {
1014 p
= request
? urlCanonical(request
) : url
;
1015 debugs(0, DBG_CRITICAL
, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
1017 p
= visible_appname_string
;
1021 if (building_deny_info_url
) {
1022 p
= visible_appname_string
;
1025 /* signature may contain %-escapes, recursion */
1026 if (page_id
!= ERR_SQUID_SIGNATURE
) {
1027 const int saved_id
= page_id
;
1028 page_id
= ERR_SQUID_SIGNATURE
;
1029 MemBuf
*sign_mb
= BuildContent();
1030 mb
.Printf("%s", sign_mb
->content());
1036 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1042 mb
.Printf("%s", Time::FormatHttpd(squid_curtime
));
1046 mb
.Printf("%s", mkrfc1123(squid_curtime
));
1050 /* Using the fake-https version of canonical so error pages see https:// */
1051 /* even when the url-path cannot be shown as more than '*' */
1053 p
= urlCanonicalFakeHttps(request
);
1056 else if (!building_deny_info_url
)
1062 p
= urlCanonical(request
);
1065 else if (!building_deny_info_url
)
1070 if (Config
.adminEmail
)
1071 mb
.Printf("%s", Config
.adminEmail
);
1072 else if (!building_deny_info_url
)
1077 if (building_deny_info_url
) break;
1078 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
1086 mb
.Printf("%s", detail
->errorName());
1089 if (!building_deny_info_url
)
1090 p
= "[Unknown Error Code]";
1094 if (building_deny_info_url
) break;
1095 if (dnsError
.size() > 0)
1096 p
= dnsError
.termedBuf();
1097 else if (ftp
.cwd_msg
)
1104 if (building_deny_info_url
) break;
1116 mb
.Printf("%%%c", token
);
1122 p
= mb
.buf
; /* do not use mb after this assignment! */
1126 debugs(4, 3, "errorConvert: %%" << token
<< " --> '" << p
<< "'" );
1131 if (building_deny_info_url
&& !no_urlescape
)
1132 p
= rfc1738_escape_part(p
);
1138 ErrorState::DenyInfoLocation(const char *name
, HttpRequest
*aRequest
, MemBuf
&result
)
1140 char const *m
= name
;
1145 m
+= 4; // skip "3xx:"
1147 while ((p
= strchr(m
, '%'))) {
1148 result
.append(m
, p
- m
); /* copy */
1149 t
= Convert(*++p
, true, true); /* convert */
1150 result
.Printf("%s", t
); /* copy */
1151 m
= p
+ 1; /* advance */
1155 result
.Printf("%s", m
); /* copy tail */
1157 assert((size_t)result
.contentSize() == strlen(result
.content()));
1161 ErrorState::BuildHttpReply()
1163 HttpReply
*rep
= new HttpReply
;
1164 const char *name
= errorPageName(page_id
);
1165 /* no LMT for error pages; error pages expire immediately */
1167 if (name
[0] == '3' || (name
[0] != '2' && name
[0] != '4' && name
[0] != '5' && strchr(name
, ':'))) {
1169 Http::StatusCode status
= Http::scFound
;
1170 // Use configured 3xx reply status if set.
1172 status
= httpStatus
;
1174 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1175 if (request
->method
!= Http::METHOD_GET
&& request
->method
!= Http::METHOD_HEAD
&& request
->http_ver
>= Http::ProtocolVersion(1,1))
1176 status
= Http::scTemporaryRedirect
;
1179 rep
->setHeaders(status
, NULL
, "text/html;charset=utf-8", 0, 0, -1);
1182 MemBuf redirect_location
;
1183 redirect_location
.init();
1184 DenyInfoLocation(name
, request
, redirect_location
);
1185 httpHeaderPutStrf(&rep
->header
, HDR_LOCATION
, "%s", redirect_location
.content() );
1188 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
1190 MemBuf
*content
= BuildContent();
1191 rep
->setHeaders(httpStatus
, NULL
, "text/html;charset=utf-8", content
->contentSize(), 0, -1);
1193 * include some information for downstream caches. Implicit
1194 * replaceable content. This isn't quite sufficient. xerrno is not
1195 * necessarily meaningful to another system, so we really should
1196 * expand it. Additionally, we should identify ourselves. Someone
1197 * might want to know. Someone _will_ want to know OTOH, the first
1198 * X-CACHE-MISS entry should tell us who.
1200 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%s %d", name
, xerrno
);
1204 * If error page auto-negotiate is enabled in any way, send the Vary.
1205 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1206 * We have even better reasons though:
1207 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1209 if (!Config
.errorDirectory
) {
1210 /* We 'negotiated' this ONLY from the Accept-Language. */
1211 rep
->header
.delById(HDR_VARY
);
1212 rep
->header
.putStr(HDR_VARY
, "Accept-Language");
1215 /* add the Content-Language header according to RFC section 14.12 */
1217 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, err_language
);
1219 #endif /* USE_ERROR_LOCALES */
1221 /* default templates are in English */
1222 /* language is known unless error_directory override used */
1223 if (!Config
.errorDirectory
)
1224 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, "en");
1227 rep
->body
.setMb(content
);
1228 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1231 // Make sure error codes get back to the client side for logging and
1234 int edc
= ERR_DETAIL_NONE
; // error detail code
1237 edc
= detail
->errorNo();
1244 request
->detailError(type
, edc
);
1251 ErrorState::BuildContent()
1253 const char *m
= NULL
;
1255 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
1258 ErrorPageFile
*localeTmpl
= NULL
;
1260 /** error_directory option in squid.conf overrides translations.
1261 * Custom errors are always found either in error_directory or the templates directory.
1262 * Otherwise locate the Accept-Language header
1264 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
) {
1265 if (err_language
&& err_language
!= Config
.errorDefaultLanguage
)
1266 safe_free(err_language
);
1268 localeTmpl
= new ErrorPageFile(err_type_str
[page_id
], static_cast<err_type
>(page_id
));
1269 if (localeTmpl
->loadFor(request
)) {
1270 m
= localeTmpl
->text();
1271 assert(localeTmpl
->language());
1272 err_language
= xstrdup(localeTmpl
->language());
1275 #endif /* USE_ERR_LOCALES */
1278 * If client-specific error templates are not enabled or available.
1279 * fall back to the old style squid.conf settings.
1282 m
= error_text
[page_id
];
1284 if (!Config
.errorDirectory
)
1285 err_language
= Config
.errorDefaultLanguage
;
1287 debugs(4, 2, HERE
<< "No existing error page language negotiated for " << errorPageName(page_id
) << ". Using default error file.");
1290 MemBuf
*result
= ConvertText(m
, true);
1298 MemBuf
*ErrorState::ConvertText(const char *text
, bool allowRecursion
)
1300 MemBuf
*content
= new MemBuf
;
1302 const char *m
= text
;
1306 while ((p
= strchr(m
, '%'))) {
1307 content
->append(m
, p
- m
); /* copy */
1308 const char *t
= Convert(*++p
, false, allowRecursion
); /* convert */
1309 content
->Printf("%s", t
); /* copy */
1310 m
= p
+ 1; /* advance */
1314 content
->Printf("%s", m
); /* copy tail */
1316 content
->terminate();
1318 assert((size_t)content
->contentSize() == strlen(content
->content()));