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 #ifndef 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
): TemplateFile(name
) { 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
]);
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
);
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");
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
): silent(false), wasLoaded(false), templateName(name
)
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, DBG_CRITICAL
, "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 fatal("failed to find or read error text file.");
308 TemplateFile::tryLoadTemplate(const char *lang
)
312 char path
[MAXPATHLEN
];
313 /* TODO: prep the directory path string to prevent snprintf ... */
314 snprintf(path
, sizeof(path
), "%s/%s/%s",
315 DEFAULT_SQUID_ERROR_DIR
, lang
, templateName
.termedBuf());
316 path
[MAXPATHLEN
-1] = '\0';
318 if (loadFromFile(path
))
322 if ( strlen(lang
) == 2) {
323 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
324 /* use first result. */
325 debugs(4,2, HERE
<< "wildcard fallback errors not coded yet.");
333 TemplateFile::loadFromFile(const char *path
)
339 if (loaded()) // already loaded?
342 fd
= file_open(path
, O_RDONLY
| O_TEXT
);
345 /* with dynamic locale negotiation we may see some failures before a success. */
347 debugs(4, DBG_CRITICAL
, HERE
<< "'" << path
<< "': " << xstrerror());
352 while ((len
= FD_READ_METHOD(fd
, buf
, sizeof(buf
))) > 0) {
353 if (!parse(buf
, len
, false)) {
354 debugs(4, DBG_CRITICAL
, HERE
<< " parse error while reading template file: " << path
);
362 debugs(4, DBG_CRITICAL
, HERE
<< "failed to fully read: '" << path
<< "': " << xstrerror());
371 bool strHdrAcptLangGetItem(const String
&hdr
, char *lang
, int langLen
, size_t &pos
)
373 while (pos
< hdr
.size()) {
377 /* skip any initial whitespace. */
378 while (pos
< hdr
.size() && xisspace(hdr
[pos
])) pos
++;
380 // IFF we terminated the tag on whitespace or ';' we need to skip to the next ',' or end of header.
381 while (pos
< hdr
.size() && hdr
[pos
] != ',') pos
++;
382 if (hdr
[pos
] == ',') pos
++;
386 * Header value format:
387 * - sequence of whitespace delimited tags
388 * - each tag may suffix with ';'.* which we can ignore.
389 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
390 * with preference given to an exact match.
392 bool invalid_byte
= false;
393 while (pos
< hdr
.size() && hdr
[pos
] != ';' && hdr
[pos
] != ',' && !xisspace(hdr
[pos
]) && dt
< (lang
+ (langLen
-1)) ) {
395 #if USE_HTTP_VIOLATIONS
396 // if accepting violations we may as well accept some broken browsers
397 // which may send us the right code, wrong ISO formatting.
402 *dt
= xtolower(hdr
[pos
]);
403 // valid codes only contain A-Z, hyphen (-) and *
404 if (*dt
!= '-' && *dt
!= '*' && (*dt
< 'a' || *dt
> 'z') )
407 dt
++; // move to next destination byte.
411 *dt
++ = '\0'; // nul-terminated the filename content string before system use.
413 debugs(4, 9, HERE
<< "STATE: dt='" << dt
<< "', lang='" << lang
<< "', pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
415 /* if we found anything we might use, try it. */
416 if (*lang
!= '\0' && !invalid_byte
)
423 TemplateFile::loadFor(HttpRequest
*request
)
428 if (loaded()) // already loaded?
431 if (!request
|| !request
->header
.getList(HDR_ACCEPT_LANGUAGE
, &hdr
) )
435 size_t pos
= 0; // current parsing position in header string
437 debugs(4, 6, HERE
<< "Testing Header: '" << hdr
<< "'");
439 while ( strHdrAcptLangGetItem(hdr
, lang
, 256, pos
) ) {
441 /* wildcard uses the configured default language */
442 if (lang
[0] == '*' && lang
[1] == '\0') {
443 debugs(4, 6, HERE
<< "Found language '" << lang
<< "'. Using configured default.");
447 debugs(4, 6, HERE
<< "Found language '" << lang
<< "', testing for available template");
449 if (tryLoadTemplate(lang
)) {
450 /* store the language we found for the Content-Language reply header */
453 } else if (Config
.errorLogMissingLanguages
) {
454 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << lang
);
462 /// \ingroup ErrorPageInternal
463 static ErrorDynamicPageInfo
*
464 errorDynamicPageInfoCreate(int id
, const char *page_name
)
466 ErrorDynamicPageInfo
*info
= new ErrorDynamicPageInfo
;
468 info
->page_name
= xstrdup(page_name
);
469 info
->page_redirect
= static_cast<http_status
>(atoi(page_name
));
471 /* WARNING on redirection status:
472 * 2xx are permitted, but not documented officially.
473 * - might be useful for serving static files (PAC etc) in special cases
474 * 3xx require a URL suitable for Location: header.
475 * - the current design does not allow for a Location: URI as well as a local file template
476 * although this possibility is explicitly permitted in the specs.
477 * 4xx-5xx require a local file template.
478 * - sending Location: on these codes with no body is invalid by the specs.
479 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
480 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
482 if (info
->page_redirect
== HTTP_STATUS_NONE
)
483 ; // special case okay.
484 else if (info
->page_redirect
< 200 || info
->page_redirect
> 599) {
486 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
488 } else if ( /* >= 200 && */ info
->page_redirect
< 300 && strchr(&(page_name
[4]), ':')) {
489 // 2xx require a local template file
490 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
492 } else if (info
->page_redirect
>= 300 && info
->page_redirect
<= 399 && !strchr(&(page_name
[4]), ':')) {
493 // 3xx require an absolute URL
494 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a URL on '" << page_name
<< "'");
496 } else if (info
->page_redirect
>= 400 /* && <= 599 */ && strchr(&(page_name
[4]), ':')) {
497 // 4xx/5xx require a local template file
498 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " requires a template on '" << page_name
<< "'");
506 /// \ingroup ErrorPageInternal
508 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
)
511 safe_free(info
->page_name
);
515 /// \ingroup ErrorPageInternal
517 errorPageId(const char *page_name
)
519 for (int i
= 0; i
< ERR_MAX
; i
++) {
520 if (strcmp(err_type_str
[i
], page_name
) == 0)
524 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); j
++) {
525 if (strcmp(ErrorDynamicPages
.items
[j
]->page_name
, page_name
) == 0)
533 errorReservePageId(const char *page_name
)
535 ErrorDynamicPageInfo
*info
;
536 int id
= errorPageId(page_name
);
538 if (id
== ERR_NONE
) {
539 info
= errorDynamicPageInfoCreate(ERR_MAX
+ ErrorDynamicPages
.size(), page_name
);
540 ErrorDynamicPages
.push_back(info
);
547 /// \ingroup ErrorPageInternal
549 errorPageName(int pageId
)
551 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
552 return err_type_str
[pageId
];
554 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
555 return ErrorDynamicPages
.items
[pageId
- ERR_MAX
]->page_name
;
557 return "ERR_UNKNOWN"; /* should not happen */
561 errorCon(err_type type
, http_status status
, HttpRequest
* request
)
563 ErrorState
*err
= new ErrorState
;
564 err
->page_id
= type
; /* has to be reset manually if needed */
565 err
->err_language
= NULL
;
567 err
->httpStatus
= status
;
568 if (err
->page_id
>= ERR_MAX
&& ErrorDynamicPages
.items
[err
->page_id
- ERR_MAX
]->page_redirect
!= HTTP_STATUS_NONE
)
569 err
->httpStatus
= ErrorDynamicPages
.items
[err
->page_id
- ERR_MAX
]->page_redirect
;
571 if (request
!= NULL
) {
572 err
->request
= HTTPMSGLOCK(request
);
573 err
->src_addr
= request
->client_addr
;
574 request
->detailError(type
, ERR_DETAIL_NONE
);
581 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
583 assert(entry
->mem_obj
!= NULL
);
584 assert (entry
->isEmpty());
585 debugs(4, 4, "Creating an error page for entry " << entry
<<
586 " with errorstate " << err
<<
587 " page id " << err
->page_id
);
589 if (entry
->store_status
!= STORE_PENDING
) {
590 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
592 * If the entry is not STORE_PENDING, then no clients
593 * care about it, and we don't need to generate an
596 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
597 assert(entry
->mem_obj
->nclients
== 0);
602 if (err
->page_id
== TCP_RESET
) {
604 debugs(4, 2, "RSTing this reply");
605 err
->request
->flags
.setResetTCP();
611 entry
->replaceHttpReply( err
->BuildHttpReply() );
612 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
615 entry
->negativeCache();
616 entry
->releaseRequest();
622 errorSend(const Comm::ConnectionPointer
&conn
, ErrorState
* err
)
625 debugs(4, 3, HERE
<< conn
<< ", err=" << err
);
626 assert(Comm::IsConnOpen(conn
));
628 * ugh, this is how we make sure error codes get back to
629 * the client side for logging and error tracking.
633 err
->request
->detailError(err
->type
, err
->xerrno
);
635 /* moved in front of errorBuildBuf @?@ */
636 err
->flags
.flag_cbdata
= 1;
638 rep
= err
->BuildHttpReply();
640 MemBuf
*mb
= rep
->pack();
641 AsyncCall::Pointer call
= commCbCall(78, 5, "errorSendComplete",
642 CommIoCbPtrFun(&errorSendComplete
, err
));
643 Comm::Write(conn
, mb
, call
);
650 \ingroup ErrorPageAPI
652 * Called by commHandleWrite() after data has been written
653 * to the client socket.
655 \note If there is a callback, the callback is responsible for
656 * closing the FD, otherwise we do it ourselves.
659 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
661 ErrorState
*err
= static_cast<ErrorState
*>(data
);
662 debugs(4, 3, HERE
<< conn
<< ", size=" << size
);
664 if (errflag
!= COMM_ERR_CLOSING
) {
666 debugs(4, 3, "errorSendComplete: callback");
667 err
->callback(conn
->fd
, err
->callback_data
, size
);
669 debugs(4, 3, "errorSendComplete: comm_close");
678 errorStateFree(ErrorState
* err
)
680 HTTPMSGUNLOCK(err
->request
);
681 safe_free(err
->redirect_url
);
683 safe_free(err
->request_hdrs
);
684 wordlistDestroy(&err
->ftp
.server_msg
);
685 safe_free(err
->ftp
.request
);
686 safe_free(err
->ftp
.reply
);
688 err
->auth_user_request
= NULL
;
690 safe_free(err
->err_msg
);
692 if (err
->err_language
!= Config
.errorDefaultLanguage
)
694 safe_free(err
->err_language
);
702 ErrorState::Dump(MemBuf
* mb
)
705 char ntoabuf
[MAX_IPSTRLEN
];
708 /* email subject line */
709 str
.Printf("CacheErrorInfo - %s", errorPageName(type
));
710 mb
->Printf("?subject=%s", rfc1738_escape_part(str
.buf
));
713 str
.Printf("CacheHost: %s\r\n", getMyHostname());
715 str
.Printf("ErrPage: %s\r\n", errorPageName(type
));
718 str
.Printf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
720 str
.Printf("Err: [none]\r\n");
723 if (auth_user_request
->denyMessage())
724 str
.Printf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
726 if (dnsError
.size() > 0)
727 str
.Printf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
730 str
.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
733 str
.Printf("ClientIP: %s\r\n", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
735 if (request
&& request
->hier
.host
[0] != '\0') {
736 str
.Printf("ServerIP: %s\r\n", request
->hier
.host
);
741 str
.Printf("HTTP Request:\r\n");
743 if (NULL
!= request
) {
745 String urlpath_or_slash
;
747 if (request
->urlpath
.size() != 0)
748 urlpath_or_slash
= request
->urlpath
;
750 urlpath_or_slash
= "/";
752 str
.Printf("%s " SQUIDSTRINGPH
" %s/%d.%d\n",
753 RequestMethodStr(request
->method
),
754 SQUIDSTRINGPRINT(urlpath_or_slash
),
755 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
756 request
->http_ver
.major
, request
->http_ver
.minor
);
757 packerToMemInit(&pck
, &str
);
758 request
->header
.packInto(&pck
);
766 str
.Printf("FTP Request: %s\r\n", ftp
.request
);
767 str
.Printf("FTP Reply: %s\r\n", ftp
.reply
);
768 str
.Printf("FTP Msg: ");
769 wordlistCat(ftp
.server_msg
, &str
);
774 mb
->Printf("&body=%s", rfc1738_escape_part(str
.buf
));
779 /// \ingroup ErrorPageInternal
780 #define CVT_BUF_SZ 512
783 ErrorState::Convert(char token
, bool building_deny_info_url
, bool allowRecursion
)
786 const char *p
= NULL
; /* takes priority over mb if set */
788 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
789 char ntoabuf
[MAX_IPSTRLEN
];
797 if (request
&& request
->auth_user_request
!= NULL
)
798 p
= request
->auth_user_request
->username();
805 mb
.Printf("%d", getMyPort());
809 if (building_deny_info_url
) break;
810 p
= request
? ftpUrlWith2f(request
) : "[no URL]";
814 if (building_deny_info_url
) break;
815 p
= errorPageName(type
);
820 p
= "%D"; // if recursion is not allowed, do not convert
822 // currently only SSL error details implemented
824 detail
->useRequest(request
);
825 const String
&errDetail
= detail
->toString();
826 if (errDetail
.defined()) {
827 MemBuf
*detail_mb
= ConvertText(errDetail
.termedBuf(), false);
828 mb
.append(detail_mb
->content(), detail_mb
->contentSize());
834 if (!mb
.contentSize())
835 mb
.Printf("[No Error Detail]");
839 mb
.Printf("%d", xerrno
);
844 mb
.Printf("(%d) %s", xerrno
, strerror(xerrno
));
846 mb
.Printf("[No Error]");
850 if (building_deny_info_url
) break;
851 /* FTP REQUEST LINE */
859 if (building_deny_info_url
) break;
868 if (building_deny_info_url
) break;
869 /* FTP SERVER RESPONSE */
871 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
873 } else if (ftp
.server_msg
) {
874 wordlistCat(ftp
.server_msg
, &mb
);
879 mb
.Printf("%s", getMyHostname());
884 if (request
->hier
.host
[0] != '\0') // if non-empty string.
885 p
= request
->hier
.host
;
887 p
= request
->GetHost();
888 } else if (!building_deny_info_url
)
889 p
= "[unknown host]";
893 mb
.Printf("%s", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
897 if (request
&& request
->hier
.tcpServer
!= NULL
)
898 p
= request
->hier
.tcpServer
->remote
.NtoA(ntoabuf
,MAX_IPSTRLEN
);
899 else if (!building_deny_info_url
)
904 if (building_deny_info_url
) break;
905 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
910 if (building_deny_info_url
) break;
911 if (Config
.errHtmlText
) {
912 mb
.Printf("%s", Config
.errHtmlText
);
915 p
= "[not available]";
919 if (building_deny_info_url
) break;
921 p
= auth_user_request
->denyMessage("[not available]");
929 p
= RequestMethodStr(request
->method
);
930 else if (!building_deny_info_url
)
931 p
= "[unknown method]";
935 p
= request
? request
->extacl_message
.termedBuf() : external_acl_message
;
936 if (!p
&& !building_deny_info_url
)
937 p
= "[not available]";
942 mb
.Printf("%d", (int) request
->port
);
943 } else if (!building_deny_info_url
) {
944 p
= "[unknown port]";
950 p
= AnyP::ProtocolType_str
[request
->protocol
];
951 } else if (!building_deny_info_url
) {
952 p
= "[unknown protocol]";
957 if (building_deny_info_url
) {
958 p
= (request
->urlpath
.size() != 0 ? request
->urlpath
.termedBuf() : "/");
961 if (NULL
!= request
) {
963 String urlpath_or_slash
;
965 if (request
->urlpath
.size() != 0)
966 urlpath_or_slash
= request
->urlpath
;
968 urlpath_or_slash
= "/";
970 mb
.Printf("%s " SQUIDSTRINGPH
" %s/%d.%d\n",
971 RequestMethodStr(request
->method
),
972 SQUIDSTRINGPRINT(urlpath_or_slash
),
973 AnyP::ProtocolType_str
[request
->http_ver
.protocol
],
974 request
->http_ver
.major
, request
->http_ver
.minor
);
975 packerToMemInit(&pck
, &mb
);
976 request
->header
.packInto(&pck
);
978 } else if (request_hdrs
) {
986 /* for backward compat we make %s show the full URL. Drop this in some future release. */
987 if (building_deny_info_url
) {
988 p
= request
? urlCanonical(request
) : url
;
989 debugs(0,0, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
991 p
= visible_appname_string
;
995 if (building_deny_info_url
) {
996 p
= visible_appname_string
;
999 /* signature may contain %-escapes, recursion */
1000 if (page_id
!= ERR_SQUID_SIGNATURE
) {
1001 const int saved_id
= page_id
;
1002 page_id
= ERR_SQUID_SIGNATURE
;
1003 MemBuf
*sign_mb
= BuildContent();
1004 mb
.Printf("%s", sign_mb
->content());
1010 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1016 mb
.Printf("%s", Time::FormatHttpd(squid_curtime
));
1020 mb
.Printf("%s", mkrfc1123(squid_curtime
));
1024 /* Using the fake-https version of canonical so error pages see https:// */
1025 /* even when the url-path cannot be shown as more than '*' */
1027 p
= urlCanonicalFakeHttps(request
);
1030 else if (!building_deny_info_url
)
1036 p
= urlCanonical(request
);
1039 else if (!building_deny_info_url
)
1044 if (Config
.adminEmail
)
1045 mb
.Printf("%s", Config
.adminEmail
);
1046 else if (!building_deny_info_url
)
1051 if (building_deny_info_url
) break;
1052 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
1060 mb
.Printf("%s", detail
->errorName());
1063 if (!building_deny_info_url
)
1064 p
= "[Unknown Error Code]";
1068 if (building_deny_info_url
) break;
1069 if (dnsError
.size() > 0)
1070 p
= dnsError
.termedBuf();
1071 else if (ftp
.cwd_msg
)
1078 if (building_deny_info_url
) break;
1090 mb
.Printf("%%%c", token
);
1096 p
= mb
.buf
; /* do not use mb after this assignment! */
1100 debugs(4, 3, "errorConvert: %%" << token
<< " --> '" << p
<< "'" );
1105 if (building_deny_info_url
&& !no_urlescape
)
1106 p
= rfc1738_escape_part(p
);
1112 ErrorState::DenyInfoLocation(const char *name
, HttpRequest
*aRequest
, MemBuf
&result
)
1114 char const *m
= name
;
1119 m
+= 4; // skip "3xx:"
1121 while ((p
= strchr(m
, '%'))) {
1122 result
.append(m
, p
- m
); /* copy */
1123 t
= Convert(*++p
, true, true); /* convert */
1124 result
.Printf("%s", t
); /* copy */
1125 m
= p
+ 1; /* advance */
1129 result
.Printf("%s", m
); /* copy tail */
1131 assert((size_t)result
.contentSize() == strlen(result
.content()));
1135 ErrorState::BuildHttpReply()
1137 HttpReply
*rep
= new HttpReply
;
1138 const char *name
= errorPageName(page_id
);
1139 /* no LMT for error pages; error pages expire immediately */
1141 if (name
[0] == '3' || (name
[0] != '2' && name
[0] != '4' && name
[0] != '5' && strchr(name
, ':'))) {
1143 http_status status
= HTTP_MOVED_TEMPORARILY
;
1144 // Use configured 3xx reply status if set.
1146 status
= httpStatus
;
1148 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1149 if (request
->method
!= METHOD_GET
&& request
->method
!= METHOD_HEAD
&& request
->http_ver
>= HttpVersion(1,1))
1150 status
= HTTP_TEMPORARY_REDIRECT
;
1153 rep
->setHeaders(status
, NULL
, "text/html", 0, 0, -1);
1156 MemBuf redirect_location
;
1157 redirect_location
.init();
1158 DenyInfoLocation(name
, request
, redirect_location
);
1159 httpHeaderPutStrf(&rep
->header
, HDR_LOCATION
, "%s", redirect_location
.content() );
1162 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
1164 MemBuf
*content
= BuildContent();
1165 rep
->setHeaders(httpStatus
, NULL
, "text/html", content
->contentSize(), 0, -1);
1167 * include some information for downstream caches. Implicit
1168 * replaceable content. This isn't quite sufficient. xerrno is not
1169 * necessarily meaningful to another system, so we really should
1170 * expand it. Additionally, we should identify ourselves. Someone
1171 * might want to know. Someone _will_ want to know OTOH, the first
1172 * X-CACHE-MISS entry should tell us who.
1174 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%s %d", name
, xerrno
);
1178 * If error page auto-negotiate is enabled in any way, send the Vary.
1179 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1180 * We have even better reasons though:
1181 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1183 if (!Config
.errorDirectory
) {
1184 /* We 'negotiated' this ONLY from the Accept-Language. */
1185 rep
->header
.delById(HDR_VARY
);
1186 rep
->header
.putStr(HDR_VARY
, "Accept-Language");
1189 /* add the Content-Language header according to RFC section 14.12 */
1191 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, err_language
);
1193 #endif /* USE_ERROR_LOCALES */
1195 /* default templates are in English */
1196 /* language is known unless error_directory override used */
1197 if (!Config
.errorDirectory
)
1198 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, "en");
1201 httpBodySet(&rep
->body
, content
);
1202 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1209 ErrorState::BuildContent()
1211 const char *m
= NULL
;
1213 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
1216 ErrorPageFile
*localeTmpl
= NULL
;
1218 /** error_directory option in squid.conf overrides translations.
1219 * Custom errors are always found either in error_directory or the templates directory.
1220 * Otherwise locate the Accept-Language header
1222 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
) {
1223 if (err_language
&& err_language
!= Config
.errorDefaultLanguage
)
1224 safe_free(err_language
);
1226 localeTmpl
= new ErrorPageFile(err_type_str
[page_id
]);
1227 if (localeTmpl
->loadFor(request
)) {
1228 m
= localeTmpl
->text();
1229 assert(localeTmpl
->language());
1230 err_language
= xstrdup(localeTmpl
->language());
1233 #endif /* USE_ERR_LOCALES */
1236 * If client-specific error templates are not enabled or available.
1237 * fall back to the old style squid.conf settings.
1240 m
= error_text
[page_id
];
1242 if (!Config
.errorDirectory
)
1243 err_language
= Config
.errorDefaultLanguage
;
1245 debugs(4, 2, HERE
<< "No existing error page language negotiated for " << errorPageName(page_id
) << ". Using default error file.");
1248 MemBuf
*result
= ConvertText(m
, true);
1256 MemBuf
*ErrorState::ConvertText(const char *text
, bool allowRecursion
)
1258 MemBuf
*content
= new MemBuf
;
1260 const char *m
= text
;
1264 while ((p
= strchr(m
, '%'))) {
1265 content
->append(m
, p
- m
); /* copy */
1266 const char *t
= Convert(*++p
, false, allowRecursion
); /* convert */
1267 content
->Printf("%s", t
); /* copy */
1268 m
= p
+ 1; /* advance */
1272 content
->Printf("%s", m
); /* copy tail */
1274 assert((size_t)content
->contentSize() == strlen(content
->content()));