4 * DEBUG: section 04 Error Generation
5 * AUTHOR: Duane Wessels
7 * SQUID Web Proxy Cache http://www.squid-cache.org/
8 * ----------------------------------------------------------
10 * Squid is the result of efforts by numerous individuals from
11 * the Internet community; see the CONTRIBUTORS file for full
12 * details. Many organizations have provided support for Squid's
13 * development; see the SPONSORS file for full details. Squid is
14 * Copyrighted (C) 2001 by the Regents of the University of
15 * California; see the COPYRIGHT file for full details. Squid
16 * incorporates software developed and/or copyrighted by other
17 * sources; see the CREDITS file for full details.
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
35 #include "comm/Connection.h"
36 #include "comm/Write.h"
37 #include "errorpage.h"
39 #include "auth/UserRequest.h"
41 #include "SquidTime.h"
43 #include "ssl/ErrorDetailManager.h"
46 #include "html_quote.h"
47 #include "HttpReply.h"
48 #include "HttpRequest.h"
49 #include "MemObject.h"
53 #include "URLScheme.h"
55 #include "err_detail_type.h"
58 \defgroup ErrorPageInternal Error Page Internals
61 \section Abstract Abstract:
62 * These routines are used to generate error messages to be
63 * sent to clients. The error type is used to select between
64 * the various message formats. (formats are stored in the
65 * Config.errorDirectory)
69 #if !defined(DEFAULT_SQUID_ERROR_DIR)
70 /** Where to look for errors if config path fails.
71 \note Please use ./configure --datadir=/path instead of patching
73 #define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
76 /// \ingroup ErrorPageInternal
77 CBDATA_CLASS_INIT(ErrorState
);
81 /// \ingroup ErrorPageInternal
85 http_status page_redirect
;
86 } ErrorDynamicPageInfo
;
88 /* local constant and vars */
91 \ingroup ErrorPageInternal
93 \note hard coded error messages are not appended with %S
94 * automagically to give you more control on the format
97 int type
; /* and page_id */
101 error_hard_text
[] = {
107 "<div id=\"footer\">\n"
108 "Generated %T by %h (%s)\n"
118 /// \ingroup ErrorPageInternal
119 static Vector
<ErrorDynamicPageInfo
*> ErrorDynamicPages
;
121 /* local prototypes */
123 /// \ingroup ErrorPageInternal
124 static const int error_hard_text_count
= sizeof(error_hard_text
) / sizeof(*error_hard_text
);
126 /// \ingroup ErrorPageInternal
127 static char **error_text
= NULL
;
129 /// \ingroup ErrorPageInternal
130 static int error_page_count
= 0;
132 /// \ingroup ErrorPageInternal
133 static MemBuf error_stylesheet
;
135 static const char *errorFindHardText(err_type type
);
136 static ErrorDynamicPageInfo
*errorDynamicPageInfoCreate(int id
, const char *page_name
);
137 static void errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
);
138 static IOCB errorSendComplete
;
140 /// \ingroup ErrorPageInternal
141 /// manages an error page template
142 class ErrorPageFile
: public TemplateFile
145 ErrorPageFile(const char *name
, const err_type code
): TemplateFile(name
,code
) { textBuf
.init();}
147 /// The template text data read from disk
148 const char *text() { return textBuf
.content(); }
151 /// stores the data read from disk to a local buffer
152 virtual bool parse(const char *buf
, int len
, bool eof
) {
154 textBuf
.append(buf
, len
);
158 MemBuf textBuf
; ///< A buffer to store the error page
161 /// \ingroup ErrorPageInternal
162 err_type
&operator++ (err_type
&anErr
)
164 int tmp
= (int)anErr
;
165 anErr
= (err_type
)(++tmp
);
169 /// \ingroup ErrorPageInternal
170 int operator - (err_type
const &anErr
, err_type
const &anErr2
)
172 return (int)anErr
- (int)anErr2
;
176 errorInitialize(void)
180 error_page_count
= ERR_MAX
+ ErrorDynamicPages
.size();
181 error_text
= static_cast<char **>(xcalloc(error_page_count
, sizeof(char *)));
183 for (i
= ERR_NONE
, ++i
; i
< error_page_count
; ++i
) {
184 safe_free(error_text
[i
]);
186 if ((text
= errorFindHardText(i
))) {
188 * Index any hard-coded error text into defaults.
190 error_text
[i
] = xstrdup(text
);
192 } else if (i
< ERR_MAX
) {
194 * Index precompiled fixed template files from one of two sources:
195 * (a) default language translation directory (error_default_language)
196 * (b) admin specified custom directory (error_directory)
198 ErrorPageFile
errTmpl(err_type_str
[i
], i
);
199 error_text
[i
] = errTmpl
.loadDefault() ? xstrdup(errTmpl
.text()) : NULL
;
202 * Index any unknown file names used by deny_info.
204 ErrorDynamicPageInfo
*info
= ErrorDynamicPages
.items
[i
- ERR_MAX
];
205 assert(info
&& info
->id
== i
&& info
->page_name
);
207 const char *pg
= info
->page_name
;
208 if (info
->page_redirect
!= HTTP_STATUS_NONE
)
209 pg
= info
->page_name
+4;
211 if (strchr(pg
, ':') == NULL
) {
212 /** But only if they are not redirection URL. */
213 ErrorPageFile
errTmpl(pg
, ERR_MAX
);
214 error_text
[i
] = errTmpl
.loadDefault() ? xstrdup(errTmpl
.text()) : NULL
;
219 error_stylesheet
.reset();
221 // look for and load stylesheet into global MemBuf for it.
222 if (Config
.errorStylesheet
) {
223 ErrorPageFile
tmpl("StylesSheet", ERR_MAX
);
224 tmpl
.loadFromFile(Config
.errorStylesheet
);
225 error_stylesheet
.Printf("%s",tmpl
.text());
229 Ssl::errorDetailInitialize();
239 for (i
= ERR_NONE
+ 1; i
< error_page_count
; i
++)
240 safe_free(error_text
[i
]);
242 safe_free(error_text
);
245 while (ErrorDynamicPages
.size())
246 errorDynamicPageInfoDestroy(ErrorDynamicPages
.pop_back());
248 error_page_count
= 0;
251 Ssl::errorDetailClean();
255 /// \ingroup ErrorPageInternal
257 errorFindHardText(err_type type
)
261 for (i
= 0; i
< error_hard_text_count
; i
++)
262 if (error_hard_text
[i
].type
== type
)
263 return error_hard_text
[i
].text
;
268 TemplateFile::TemplateFile(const char *name
, const err_type code
): silent(false), wasLoaded(false), templateName(name
), templateCode(code
)
274 TemplateFile::loadDefault()
276 if (loaded()) // already loaded?
279 /** test error_directory configured location */
280 if (Config
.errorDirectory
) {
281 char path
[MAXPATHLEN
];
282 snprintf(path
, sizeof(path
), "%s/%s", Config
.errorDirectory
, templateName
.termedBuf());
287 /** test error_default_language location */
288 if (!loaded() && Config
.errorDefaultLanguage
) {
289 if (!tryLoadTemplate(Config
.errorDefaultLanguage
)) {
290 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "Unable to load default error language files. Reset to backups.");
295 /* test default location if failed (templates == English translation base templates) */
297 tryLoadTemplate("templates");
300 /* giving up if failed */
302 debugs(1, (templateCode
< TCP_RESET
? DBG_CRITICAL
: 3), "WARNING: failed to find or read error text file " << templateName
);
303 parse("Internal Error: Missing Template ", 33, '\0');
304 parse(templateName
.termedBuf(), templateName
.size(), '\0');
311 TemplateFile::tryLoadTemplate(const char *lang
)
315 char path
[MAXPATHLEN
];
316 /* TODO: prep the directory path string to prevent snprintf ... */
317 snprintf(path
, sizeof(path
), "%s/%s/%s",
318 DEFAULT_SQUID_ERROR_DIR
, lang
, templateName
.termedBuf());
319 path
[MAXPATHLEN
-1] = '\0';
321 if (loadFromFile(path
))
325 if ( strlen(lang
) == 2) {
326 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
327 /* use first result. */
328 debugs(4,2, HERE
<< "wildcard fallback errors not coded yet.");
336 TemplateFile::loadFromFile(const char *path
)
342 if (loaded()) // already loaded?
345 fd
= file_open(path
, O_RDONLY
| O_TEXT
);
348 /* with dynamic locale negotiation we may see some failures before a success. */
349 if (!silent
&& templateCode
< TCP_RESET
)
350 debugs(4, DBG_CRITICAL
, HERE
<< "'" << path
<< "': " << xstrerror());
355 while ((len
= FD_READ_METHOD(fd
, buf
, sizeof(buf
))) > 0) {
356 if (!parse(buf
, len
, false)) {
357 debugs(4, DBG_CRITICAL
, HERE
<< " parse error while reading template file: " << path
);
365 debugs(4, DBG_CRITICAL
, HERE
<< "failed to fully read: '" << path
<< "': " << xstrerror());
374 bool strHdrAcptLangGetItem(const String
&hdr
, char *lang
, int langLen
, size_t &pos
)
376 while (pos
< hdr
.size()) {
380 /* skip any initial whitespace. */
381 while (pos
< hdr
.size() && xisspace(hdr
[pos
])) pos
++;
383 // IFF we terminated the tag on whitespace or ';' we need to skip to the next ',' or end of header.
384 while (pos
< hdr
.size() && hdr
[pos
] != ',') pos
++;
385 if (hdr
[pos
] == ',') 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.
416 debugs(4, 9, HERE
<< "STATE: dt='" << dt
<< "', lang='" << lang
<< "', pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
418 /* if we found anything we might use, try it. */
419 if (*lang
!= '\0' && !invalid_byte
)
426 TemplateFile::loadFor(HttpRequest
*request
)
431 if (loaded()) // already loaded?
434 if (!request
|| !request
->header
.getList(HDR_ACCEPT_LANGUAGE
, &hdr
) )
438 size_t pos
= 0; // current parsing position in header string
440 debugs(4, 6, HERE
<< "Testing Header: '" << hdr
<< "'");
442 while ( strHdrAcptLangGetItem(hdr
, lang
, 256, pos
) ) {
444 /* wildcard uses the configured default language */
445 if (lang
[0] == '*' && lang
[1] == '\0') {
446 debugs(4, 6, HERE
<< "Found language '" << lang
<< "'. Using configured default.");
450 debugs(4, 6, HERE
<< "Found language '" << lang
<< "', testing for available template");
452 if (tryLoadTemplate(lang
)) {
453 /* store the language we found for the Content-Language reply header */
456 } else if (Config
.errorLogMissingLanguages
) {
457 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << lang
);
465 /// \ingroup ErrorPageInternal
466 static ErrorDynamicPageInfo
*
467 errorDynamicPageInfoCreate(int id
, const char *page_name
)
469 ErrorDynamicPageInfo
*info
= new ErrorDynamicPageInfo
;
471 info
->page_name
= xstrdup(page_name
);
472 info
->page_redirect
= static_cast<http_status
>(atoi(page_name
));
474 /* WARNING on redirection status:
475 * 2xx are permitted, but not documented officially.
476 * - might be useful for serving static files (PAC etc) in special cases
477 * 3xx require a URL suitable for Location: header.
478 * - the current design does not allow for a Location: URI as well as a local file template
479 * although this possibility is explicitly permitted in the specs.
480 * 4xx-5xx require a local file template.
481 * - sending Location: on these codes with no body is invalid by the specs.
482 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
483 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
485 if (info
->page_redirect
== HTTP_STATUS_NONE
)
486 ; // special case okay.
487 else if (info
->page_redirect
< 200 || info
->page_redirect
> 599) {
489 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
491 } else if ( /* >= 200 && */ info
->page_redirect
< 300 && strchr(&(page_name
[4]), ':')) {
492 // 2xx require a local template file
493 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
495 } else if (info
->page_redirect
>= 300 && info
->page_redirect
<= 399 && !strchr(&(page_name
[4]), ':')) {
496 // 3xx require an absolute URL
497 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a URL on '" << page_name
<< "'");
499 } else if (info
->page_redirect
>= 400 /* && <= 599 */ && strchr(&(page_name
[4]), ':')) {
500 // 4xx/5xx require a local template file
501 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
509 /// \ingroup ErrorPageInternal
511 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
)
514 safe_free(info
->page_name
);
518 /// \ingroup ErrorPageInternal
520 errorPageId(const char *page_name
)
522 for (int i
= 0; i
< ERR_MAX
; i
++) {
523 if (strcmp(err_type_str
[i
], page_name
) == 0)
527 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); j
++) {
528 if (strcmp(ErrorDynamicPages
.items
[j
]->page_name
, page_name
) == 0)
536 errorReservePageId(const char *page_name
)
538 ErrorDynamicPageInfo
*info
;
539 int id
= errorPageId(page_name
);
541 if (id
== ERR_NONE
) {
542 info
= errorDynamicPageInfoCreate(ERR_MAX
+ ErrorDynamicPages
.size(), page_name
);
543 ErrorDynamicPages
.push_back(info
);
550 /// \ingroup ErrorPageInternal
552 errorPageName(int pageId
)
554 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
555 return err_type_str
[pageId
];
557 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
558 return ErrorDynamicPages
.items
[pageId
- ERR_MAX
]->page_name
;
560 return "ERR_UNKNOWN"; /* should not happen */
563 ErrorState::ErrorState(err_type t
, http_status status
, HttpRequest
* req
) :
569 auth_user_request (NULL
),
586 detailCode(ERR_DETAIL_NONE
)
588 memset(&flags
, 0, sizeof(flags
));
589 memset(&ftp
, 0, sizeof(ftp
));
591 if (page_id
>= ERR_MAX
&& ErrorDynamicPages
.items
[page_id
- ERR_MAX
]->page_redirect
!= HTTP_STATUS_NONE
)
592 httpStatus
= ErrorDynamicPages
.items
[page_id
- ERR_MAX
]->page_redirect
;
595 request
= HTTPMSGLOCK(req
);
596 src_addr
= req
->client_addr
;
601 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
603 assert(entry
->mem_obj
!= NULL
);
604 assert (entry
->isEmpty());
605 debugs(4, 4, "Creating an error page for entry " << entry
<<
606 " with errorstate " << err
<<
607 " page id " << err
->page_id
);
609 if (entry
->store_status
!= STORE_PENDING
) {
610 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
612 * If the entry is not STORE_PENDING, then no clients
613 * care about it, and we don't need to generate an
616 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
617 assert(entry
->mem_obj
->nclients
== 0);
622 if (err
->page_id
== TCP_RESET
) {
624 debugs(4, 2, "RSTing this reply");
625 err
->request
->flags
.setResetTCP();
631 entry
->replaceHttpReply( err
->BuildHttpReply() );
632 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
635 entry
->negativeCache();
636 entry
->releaseRequest();
642 errorSend(const Comm::ConnectionPointer
&conn
, ErrorState
* err
)
645 debugs(4, 3, HERE
<< conn
<< ", err=" << err
);
646 assert(Comm::IsConnOpen(conn
));
648 /* moved in front of errorBuildBuf @?@ */
649 err
->flags
.flag_cbdata
= 1;
651 rep
= err
->BuildHttpReply();
653 MemBuf
*mb
= rep
->pack();
654 AsyncCall::Pointer call
= commCbCall(78, 5, "errorSendComplete",
655 CommIoCbPtrFun(&errorSendComplete
, err
));
656 Comm::Write(conn
, mb
, call
);
663 \ingroup ErrorPageAPI
665 * Called by commHandleWrite() after data has been written
666 * to the client socket.
668 \note If there is a callback, the callback is responsible for
669 * closing the FD, otherwise we do it ourselves.
672 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
674 ErrorState
*err
= static_cast<ErrorState
*>(data
);
675 debugs(4, 3, HERE
<< conn
<< ", size=" << size
);
677 if (errflag
!= COMM_ERR_CLOSING
) {
679 debugs(4, 3, "errorSendComplete: callback");
680 err
->callback(conn
->fd
, err
->callback_data
, size
);
682 debugs(4, 3, "errorSendComplete: comm_close");
690 ErrorState::~ErrorState()
692 HTTPMSGUNLOCK(request
);
693 safe_free(redirect_url
);
695 safe_free(request_hdrs
);
696 wordlistDestroy(&ftp
.server_msg
);
697 safe_free(ftp
.request
);
698 safe_free(ftp
.reply
);
700 auth_user_request
= NULL
;
704 if (err_language
!= Config
.errorDefaultLanguage
)
706 safe_free(err_language
);
713 ErrorState::Dump(MemBuf
* mb
)
716 char ntoabuf
[MAX_IPSTRLEN
];
719 /* email subject line */
720 str
.Printf("CacheErrorInfo - %s", errorPageName(type
));
721 mb
->Printf("?subject=%s", rfc1738_escape_part(str
.buf
));
724 str
.Printf("CacheHost: %s\r\n", getMyHostname());
726 str
.Printf("ErrPage: %s\r\n", errorPageName(type
));
729 str
.Printf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
731 str
.Printf("Err: [none]\r\n");
734 if (auth_user_request
->denyMessage())
735 str
.Printf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
737 if (dnsError
.size() > 0)
738 str
.Printf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
741 str
.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
744 str
.Printf("ClientIP: %s\r\n", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
746 if (request
&& request
->hier
.host
[0] != '\0') {
747 str
.Printf("ServerIP: %s\r\n", request
->hier
.host
);
752 str
.Printf("HTTP Request:\r\n");
754 if (NULL
!= request
) {
756 String urlpath_or_slash
;
758 if (request
->urlpath
.size() != 0)
759 urlpath_or_slash
= request
->urlpath
;
761 urlpath_or_slash
= "/";
763 str
.Printf("%s " SQUIDSTRINGPH
" %s/%d.%d\n",
764 RequestMethodStr(request
->method
),
765 SQUIDSTRINGPRINT(urlpath_or_slash
),
766 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
767 request
->http_ver
.major
, request
->http_ver
.minor
);
768 packerToMemInit(&pck
, &str
);
769 request
->header
.packInto(&pck
);
777 str
.Printf("FTP Request: %s\r\n", ftp
.request
);
778 str
.Printf("FTP Reply: %s\r\n", (ftp
.reply
? ftp
.reply
:"[none]"));
779 str
.Printf("FTP Msg: ");
780 wordlistCat(ftp
.server_msg
, &str
);
785 mb
->Printf("&body=%s", rfc1738_escape_part(str
.buf
));
790 /// \ingroup ErrorPageInternal
791 #define CVT_BUF_SZ 512
794 ErrorState::Convert(char token
, bool building_deny_info_url
, bool allowRecursion
)
797 const char *p
= NULL
; /* takes priority over mb if set */
799 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
800 char ntoabuf
[MAX_IPSTRLEN
];
808 if (request
&& request
->auth_user_request
!= NULL
)
809 p
= request
->auth_user_request
->username();
816 mb
.Printf("%d", getMyPort());
820 if (building_deny_info_url
) break;
821 p
= request
? ftpUrlWith2f(request
) : "[no URL]";
825 if (building_deny_info_url
) break;
826 p
= errorPageName(type
);
831 p
= "%D"; // if recursion is not allowed, do not convert
833 // currently only SSL error details implemented
835 detail
->useRequest(request
);
836 const String
&errDetail
= detail
->toString();
837 if (errDetail
.defined()) {
838 MemBuf
*detail_mb
= ConvertText(errDetail
.termedBuf(), false);
839 mb
.append(detail_mb
->content(), detail_mb
->contentSize());
845 if (!mb
.contentSize())
846 mb
.Printf("[No Error Detail]");
850 mb
.Printf("%d", xerrno
);
855 mb
.Printf("(%d) %s", xerrno
, strerror(xerrno
));
857 mb
.Printf("[No Error]");
861 if (building_deny_info_url
) break;
862 /* FTP REQUEST LINE */
870 if (building_deny_info_url
) break;
879 if (building_deny_info_url
) break;
880 /* FTP SERVER RESPONSE */
882 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
884 } else if (ftp
.server_msg
) {
885 wordlistCat(ftp
.server_msg
, &mb
);
890 mb
.Printf("%s", getMyHostname());
895 if (request
->hier
.host
[0] != '\0') // if non-empty string.
896 p
= request
->hier
.host
;
898 p
= request
->GetHost();
899 } else if (!building_deny_info_url
)
900 p
= "[unknown host]";
904 mb
.Printf("%s", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
908 if (request
&& request
->hier
.tcpServer
!= NULL
)
909 p
= request
->hier
.tcpServer
->remote
.NtoA(ntoabuf
,MAX_IPSTRLEN
);
910 else if (!building_deny_info_url
)
915 if (building_deny_info_url
) break;
916 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
921 if (building_deny_info_url
) break;
922 if (Config
.errHtmlText
) {
923 mb
.Printf("%s", Config
.errHtmlText
);
926 p
= "[not available]";
930 if (building_deny_info_url
) break;
932 p
= auth_user_request
->denyMessage("[not available]");
940 p
= RequestMethodStr(request
->method
);
941 else if (!building_deny_info_url
)
942 p
= "[unknown method]";
946 p
= request
? request
->extacl_message
.termedBuf() : external_acl_message
;
947 if (!p
&& !building_deny_info_url
)
948 p
= "[not available]";
953 mb
.Printf("%d", (int) request
->port
);
954 } else if (!building_deny_info_url
) {
955 p
= "[unknown port]";
961 p
= AnyP::ProtocolType_str
[request
->protocol
];
962 } else if (!building_deny_info_url
) {
963 p
= "[unknown protocol]";
968 if (building_deny_info_url
) {
969 p
= (request
->urlpath
.size() != 0 ? request
->urlpath
.termedBuf() : "/");
973 if (NULL
!= request
) {
975 String urlpath_or_slash
;
977 if (request
->urlpath
.size() != 0)
978 urlpath_or_slash
= request
->urlpath
;
980 urlpath_or_slash
= "/";
982 mb
.Printf("%s " SQUIDSTRINGPH
" %s/%d.%d\n",
983 RequestMethodStr(request
->method
),
984 SQUIDSTRINGPRINT(urlpath_or_slash
),
985 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
986 request
->http_ver
.major
, request
->http_ver
.minor
);
987 packerToMemInit(&pck
, &mb
);
988 request
->header
.packInto(&pck
, true); //hide authorization data
990 } else if (request_hdrs
) {
998 /* for backward compat we make %s show the full URL. Drop this in some future release. */
999 if (building_deny_info_url
) {
1000 p
= request
? urlCanonical(request
) : url
;
1001 debugs(0,0, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
1003 p
= visible_appname_string
;
1007 if (building_deny_info_url
) {
1008 p
= visible_appname_string
;
1011 /* signature may contain %-escapes, recursion */
1012 if (page_id
!= ERR_SQUID_SIGNATURE
) {
1013 const int saved_id
= page_id
;
1014 page_id
= ERR_SQUID_SIGNATURE
;
1015 MemBuf
*sign_mb
= BuildContent();
1016 mb
.Printf("%s", sign_mb
->content());
1022 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1028 mb
.Printf("%s", Time::FormatHttpd(squid_curtime
));
1032 mb
.Printf("%s", mkrfc1123(squid_curtime
));
1036 /* Using the fake-https version of canonical so error pages see https:// */
1037 /* even when the url-path cannot be shown as more than '*' */
1039 p
= urlCanonicalFakeHttps(request
);
1042 else if (!building_deny_info_url
)
1048 p
= urlCanonical(request
);
1051 else if (!building_deny_info_url
)
1056 if (Config
.adminEmail
)
1057 mb
.Printf("%s", Config
.adminEmail
);
1058 else if (!building_deny_info_url
)
1063 if (building_deny_info_url
) break;
1064 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
1072 mb
.Printf("%s", detail
->errorName());
1075 if (!building_deny_info_url
)
1076 p
= "[Unknown Error Code]";
1080 if (building_deny_info_url
) break;
1081 if (dnsError
.size() > 0)
1082 p
= dnsError
.termedBuf();
1083 else if (ftp
.cwd_msg
)
1090 if (building_deny_info_url
) break;
1102 mb
.Printf("%%%c", token
);
1108 p
= mb
.buf
; /* do not use mb after this assignment! */
1112 debugs(4, 3, "errorConvert: %%" << token
<< " --> '" << p
<< "'" );
1117 if (building_deny_info_url
&& !no_urlescape
)
1118 p
= rfc1738_escape_part(p
);
1124 ErrorState::DenyInfoLocation(const char *name
, HttpRequest
*aRequest
, MemBuf
&result
)
1126 char const *m
= name
;
1131 m
+= 4; // skip "3xx:"
1133 while ((p
= strchr(m
, '%'))) {
1134 result
.append(m
, p
- m
); /* copy */
1135 t
= Convert(*++p
, true, true); /* convert */
1136 result
.Printf("%s", t
); /* copy */
1137 m
= p
+ 1; /* advance */
1141 result
.Printf("%s", m
); /* copy tail */
1143 assert((size_t)result
.contentSize() == strlen(result
.content()));
1147 ErrorState::BuildHttpReply()
1149 HttpReply
*rep
= new HttpReply
;
1150 const char *name
= errorPageName(page_id
);
1151 /* no LMT for error pages; error pages expire immediately */
1153 if (name
[0] == '3' || (name
[0] != '2' && name
[0] != '4' && name
[0] != '5' && strchr(name
, ':'))) {
1155 http_status status
= HTTP_MOVED_TEMPORARILY
;
1156 // Use configured 3xx reply status if set.
1158 status
= httpStatus
;
1160 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1161 if (request
->method
!= METHOD_GET
&& request
->method
!= METHOD_HEAD
&& request
->http_ver
>= HttpVersion(1,1))
1162 status
= HTTP_TEMPORARY_REDIRECT
;
1165 rep
->setHeaders(status
, NULL
, "text/html", 0, 0, -1);
1168 MemBuf redirect_location
;
1169 redirect_location
.init();
1170 DenyInfoLocation(name
, request
, redirect_location
);
1171 httpHeaderPutStrf(&rep
->header
, HDR_LOCATION
, "%s", redirect_location
.content() );
1174 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
1176 MemBuf
*content
= BuildContent();
1177 rep
->setHeaders(httpStatus
, NULL
, "text/html", content
->contentSize(), 0, -1);
1179 * include some information for downstream caches. Implicit
1180 * replaceable content. This isn't quite sufficient. xerrno is not
1181 * necessarily meaningful to another system, so we really should
1182 * expand it. Additionally, we should identify ourselves. Someone
1183 * might want to know. Someone _will_ want to know OTOH, the first
1184 * X-CACHE-MISS entry should tell us who.
1186 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%s %d", name
, xerrno
);
1190 * If error page auto-negotiate is enabled in any way, send the Vary.
1191 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1192 * We have even better reasons though:
1193 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1195 if (!Config
.errorDirectory
) {
1196 /* We 'negotiated' this ONLY from the Accept-Language. */
1197 rep
->header
.delById(HDR_VARY
);
1198 rep
->header
.putStr(HDR_VARY
, "Accept-Language");
1201 /* add the Content-Language header according to RFC section 14.12 */
1203 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, err_language
);
1205 #endif /* USE_ERROR_LOCALES */
1207 /* default templates are in English */
1208 /* language is known unless error_directory override used */
1209 if (!Config
.errorDirectory
)
1210 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, "en");
1213 rep
->body
.setMb(content
);
1214 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1217 // Make sure error codes get back to the client side for logging and
1220 int edc
= ERR_DETAIL_NONE
; // error detail code
1223 edc
= detail
->errorNo();
1230 request
->detailError(type
, edc
);
1237 ErrorState::BuildContent()
1239 const char *m
= NULL
;
1241 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
1244 ErrorPageFile
*localeTmpl
= NULL
;
1246 /** error_directory option in squid.conf overrides translations.
1247 * Custom errors are always found either in error_directory or the templates directory.
1248 * Otherwise locate the Accept-Language header
1250 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
) {
1251 if (err_language
&& err_language
!= Config
.errorDefaultLanguage
)
1252 safe_free(err_language
);
1254 localeTmpl
= new ErrorPageFile(err_type_str
[page_id
], static_cast<err_type
>(page_id
));
1255 if (localeTmpl
->loadFor(request
)) {
1256 m
= localeTmpl
->text();
1257 assert(localeTmpl
->language());
1258 err_language
= xstrdup(localeTmpl
->language());
1261 #endif /* USE_ERR_LOCALES */
1264 * If client-specific error templates are not enabled or available.
1265 * fall back to the old style squid.conf settings.
1268 m
= error_text
[page_id
];
1270 if (!Config
.errorDirectory
)
1271 err_language
= Config
.errorDefaultLanguage
;
1273 debugs(4, 2, HERE
<< "No existing error page language negotiated for " << errorPageName(page_id
) << ". Using default error file.");
1276 MemBuf
*result
= ConvertText(m
, true);
1284 MemBuf
*ErrorState::ConvertText(const char *text
, bool allowRecursion
)
1286 MemBuf
*content
= new MemBuf
;
1288 const char *m
= text
;
1292 while ((p
= strchr(m
, '%'))) {
1293 content
->append(m
, p
- m
); /* copy */
1294 const char *t
= Convert(*++p
, false, allowRecursion
); /* convert */
1295 content
->Printf("%s", t
); /* copy */
1296 m
= p
+ 1; /* advance */
1300 content
->Printf("%s", m
); /* copy tail */
1302 assert((size_t)content
->contentSize() == strlen(content
->content()));