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 "html_quote.h"
44 #include "HttpReply.h"
45 #include "HttpRequest.h"
46 #include "MemObject.h"
50 #include "URLScheme.h"
52 #include "err_detail_type.h"
55 \defgroup ErrorPageInternal Error Page Internals
58 \section Abstract Abstract:
59 * These routines are used to generate error messages to be
60 * sent to clients. The error type is used to select between
61 * the various message formats. (formats are stored in the
62 * Config.errorDirectory)
66 #ifndef DEFAULT_SQUID_ERROR_DIR
67 /** Where to look for errors if config path fails.
68 \note Please use ./configure --datadir=/path instead of patching
70 #define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
73 /// \ingroup ErrorPageInternal
74 CBDATA_CLASS_INIT(ErrorState
);
78 /// \ingroup ErrorPageInternal
82 http_status page_redirect
;
83 } ErrorDynamicPageInfo
;
85 /* local constant and vars */
88 \ingroup ErrorPageInternal
90 \note hard coded error messages are not appended with %S
91 * automagically to give you more control on the format
94 int type
; /* and page_id */
104 "<div id=\"footer\">\n"
105 "Generated %T by %h (%s)\n"
115 /// \ingroup ErrorPageInternal
116 static Vector
<ErrorDynamicPageInfo
*> ErrorDynamicPages
;
118 /* local prototypes */
120 /// \ingroup ErrorPageInternal
121 static const int error_hard_text_count
= sizeof(error_hard_text
) / sizeof(*error_hard_text
);
123 /// \ingroup ErrorPageInternal
124 static char **error_text
= NULL
;
126 /// \ingroup ErrorPageInternal
127 static int error_page_count
= 0;
129 /// \ingroup ErrorPageInternal
130 static MemBuf error_stylesheet
;
132 static const char *errorFindHardText(err_type type
);
133 static ErrorDynamicPageInfo
*errorDynamicPageInfoCreate(int id
, const char *page_name
);
134 static void errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
);
135 static IOCB errorSendComplete
;
137 /// \ingroup ErrorPageInternal
138 /// manages an error page template
139 class ErrorPageFile
: public TemplateFile
{
141 ErrorPageFile(const char *name
): TemplateFile(name
) { textBuf
.init();}
143 /// The template text data read from disk
144 const char *text() { return textBuf
.content(); }
147 /// stores the data read from disk to a local buffer
148 virtual bool parse(const char *buf
, int len
, bool eof
) {
150 textBuf
.append(buf
, len
);
154 MemBuf textBuf
; ///< A buffer to store the error page
157 /// \ingroup ErrorPageInternal
158 err_type
&operator++ (err_type
&anErr
)
160 int tmp
= (int)anErr
;
161 anErr
= (err_type
)(++tmp
);
165 /// \ingroup ErrorPageInternal
166 int operator - (err_type
const &anErr
, err_type
const &anErr2
)
168 return (int)anErr
- (int)anErr2
;
172 errorInitialize(void)
176 error_page_count
= ERR_MAX
+ ErrorDynamicPages
.size();
177 error_text
= static_cast<char **>(xcalloc(error_page_count
, sizeof(char *)));
179 for (i
= ERR_NONE
, ++i
; i
< error_page_count
; ++i
) {
180 safe_free(error_text
[i
]);
182 if ((text
= errorFindHardText(i
))) {
184 * Index any hard-coded error text into defaults.
186 error_text
[i
] = xstrdup(text
);
188 } else if (i
< ERR_MAX
) {
190 * Index precompiled fixed template files from one of two sources:
191 * (a) default language translation directory (error_default_language)
192 * (b) admin specified custom directory (error_directory)
194 ErrorPageFile
errTmpl(err_type_str
[i
]);
195 error_text
[i
] = errTmpl
.loadDefault() ? xstrdup(errTmpl
.text()) : NULL
;
198 * Index any unknown file names used by deny_info.
200 ErrorDynamicPageInfo
*info
= ErrorDynamicPages
.items
[i
- ERR_MAX
];
201 assert(info
&& info
->id
== i
&& info
->page_name
);
203 const char *pg
= info
->page_name
;
204 if (info
->page_redirect
!= HTTP_STATUS_NONE
)
205 pg
= info
->page_name
+4;
207 if (strchr(pg
, ':') == NULL
) {
208 /** But only if they are not redirection URL. */
209 ErrorPageFile
errTmpl(pg
);
210 error_text
[i
] = errTmpl
.loadDefault() ? xstrdup(errTmpl
.text()) : NULL
;
215 error_stylesheet
.reset();
217 // look for and load stylesheet into global MemBuf for it.
218 if (Config
.errorStylesheet
) {
219 ErrorPageFile
tmpl("StylesSheet");
220 tmpl
.loadFromFile(Config
.errorStylesheet
);
221 error_stylesheet
.Printf("%s",tmpl
.text());
225 Ssl::errorDetailInitialize();
235 for (i
= ERR_NONE
+ 1; i
< error_page_count
; i
++)
236 safe_free(error_text
[i
]);
238 safe_free(error_text
);
241 while (ErrorDynamicPages
.size())
242 errorDynamicPageInfoDestroy(ErrorDynamicPages
.pop_back());
244 error_page_count
= 0;
247 Ssl::errorDetailClean();
251 /// \ingroup ErrorPageInternal
253 errorFindHardText(err_type type
)
257 for (i
= 0; i
< error_hard_text_count
; i
++)
258 if (error_hard_text
[i
].type
== type
)
259 return error_hard_text
[i
].text
;
264 TemplateFile::TemplateFile(const char *name
): silent(false), wasLoaded(false), templateName(name
)
270 TemplateFile::loadDefault()
272 if (loaded()) // already loaded?
275 /** test error_directory configured location */
276 if (Config
.errorDirectory
) {
277 char path
[MAXPATHLEN
];
278 snprintf(path
, sizeof(path
), "%s/%s", Config
.errorDirectory
, templateName
.termedBuf());
283 /** test error_default_language location */
284 if (!loaded() && Config
.errorDefaultLanguage
) {
285 if (!tryLoadTemplate(Config
.errorDefaultLanguage
)) {
286 debugs(1, DBG_CRITICAL
, "Unable to load default error language files. Reset to backups.");
291 /* test default location if failed (templates == English translation base templates) */
293 tryLoadTemplate("templates");
296 /* giving up if failed */
298 fatal("failed to find or read error text file.");
304 TemplateFile::tryLoadTemplate(const char *lang
)
308 char path
[MAXPATHLEN
];
309 /* TODO: prep the directory path string to prevent snprintf ... */
310 snprintf(path
, sizeof(path
), "%s/%s/%s",
311 DEFAULT_SQUID_ERROR_DIR
, lang
, templateName
.termedBuf());
312 path
[MAXPATHLEN
-1] = '\0';
314 if (loadFromFile(path
))
318 if ( strlen(lang
) == 2) {
319 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
320 /* use first result. */
321 debugs(4,2, HERE
<< "wildcard fallback errors not coded yet.");
329 TemplateFile::loadFromFile(const char *path
)
335 if (loaded()) // already loaded?
338 fd
= file_open(path
, O_RDONLY
| O_TEXT
);
341 /* with dynamic locale negotiation we may see some failures before a success. */
343 debugs(4, DBG_CRITICAL
, HERE
<< "'" << path
<< "': " << xstrerror());
348 while ((len
= FD_READ_METHOD(fd
, buf
, sizeof(buf
))) > 0) {
349 if (!parse(buf
, len
, false)) {
350 debugs(4, DBG_CRITICAL
, HERE
<< " parse error while reading template file: " << path
);
358 debugs(4, DBG_CRITICAL
, HERE
<< "failed to fully read: '" << path
<< "': " << xstrerror());
367 bool strHdrAcptLangGetItem(const String
&hdr
, char *lang
, int langLen
, size_t &pos
)
369 while(pos
< hdr
.size()) {
373 /* skip any initial whitespace. */
374 while (pos
< hdr
.size() && xisspace(hdr
[pos
])) pos
++;
377 // IFF we terminated the tag on whitespace or ';' we need to skip to the next ',' or end of header.
378 while (pos
< hdr
.size() && hdr
[pos
] != ',') pos
++;
379 if (hdr
[pos
] == ',') pos
++;
383 * Header value format:
384 * - sequence of whitespace delimited tags
385 * - each tag may suffix with ';'.* which we can ignore.
386 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
387 * with preference given to an exact match.
389 bool invalid_byte
= false;
390 while (pos
< hdr
.size() && hdr
[pos
] != ';' && hdr
[pos
] != ',' && !xisspace(hdr
[pos
]) && dt
< (lang
+ (langLen
-1)) ) {
392 #if USE_HTTP_VIOLATIONS
393 // if accepting violations we may as well accept some broken browsers
394 // which may send us the right code, wrong ISO formatting.
399 *dt
= xtolower(hdr
[pos
]);
400 // valid codes only contain A-Z, hyphen (-) and *
401 if (*dt
!= '-' && *dt
!= '*' && (*dt
< 'a' || *dt
> 'z') )
404 dt
++; // move to next destination byte.
408 *dt
++ = '\0'; // nul-terminated the filename content string before system use.
410 debugs(4, 9, HERE
<< "STATE: dt='" << dt
<< "', lang='" << lang
<< "', pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
412 /* if we found anything we might use, try it. */
413 if (*lang
!= '\0' && !invalid_byte
)
420 TemplateFile::loadFor(HttpRequest
*request
)
425 if (loaded()) // already loaded?
428 if (!request
|| !request
->header
.getList(HDR_ACCEPT_LANGUAGE
, &hdr
) )
432 size_t pos
= 0; // current parsing position in header string
434 debugs(4, 6, HERE
<< "Testing Header: '" << hdr
<< "'");
436 while ( strHdrAcptLangGetItem(hdr
, lang
, 256, pos
) ) {
438 /* wildcard uses the configured default language */
439 if (lang
[0] == '*' && lang
[1] == '\0') {
440 debugs(4, 6, HERE
<< "Found language '" << lang
<< "'. Using configured default.");
444 debugs(4, 6, HERE
<< "Found language '" << lang
<< "', testing for available template");
446 if (tryLoadTemplate(lang
)) {
447 /* store the language we found for the Content-Language reply header */
450 } else if (Config
.errorLogMissingLanguages
) {
451 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << lang
);
459 /// \ingroup ErrorPageInternal
460 static ErrorDynamicPageInfo
*
461 errorDynamicPageInfoCreate(int id
, const char *page_name
)
463 ErrorDynamicPageInfo
*info
= new ErrorDynamicPageInfo
;
465 info
->page_name
= xstrdup(page_name
);
466 info
->page_redirect
= static_cast<http_status
>(atoi(page_name
));
468 /* WARNING on redirection status:
469 * 2xx are permitted, but not documented officially.
470 * - might be useful for serving static files (PAC etc) in special cases
471 * 3xx require a URL suitable for Location: header.
472 * - the current design does not allow for a Location: URI as well as a local file template
473 * although this possibility is explicitly permitted in the specs.
474 * 4xx-5xx require a local file template.
475 * - sending Location: on these codes with no body is invalid by the specs.
476 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
477 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
479 if (info
->page_redirect
== HTTP_STATUS_NONE
)
480 ; // special case okay.
481 else if (info
->page_redirect
< 200 || info
->page_redirect
> 599) {
483 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
485 } else if ( /* >= 200 && */ info
->page_redirect
< 300 && strchr(&(page_name
[4]), ':')) {
486 // 2xx require a local template file
487 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
489 } else if (/* >= 300 && */ info
->page_redirect
<= 399 && !strchr(&(page_name
[4]), ':')) {
490 // 3xx require an absolute URL
491 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
493 } else if (info
->page_redirect
>= 400 /* && <= 599 */ && strchr(&(page_name
[4]), ':')) {
494 // 4xx/5xx require a local template file
495 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
503 /// \ingroup ErrorPageInternal
505 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
)
508 safe_free(info
->page_name
);
512 /// \ingroup ErrorPageInternal
514 errorPageId(const char *page_name
)
516 for (int i
= 0; i
< ERR_MAX
; i
++) {
517 if (strcmp(err_type_str
[i
], page_name
) == 0)
521 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); j
++) {
522 if (strcmp(ErrorDynamicPages
.items
[j
]->page_name
, page_name
) == 0)
530 errorReservePageId(const char *page_name
)
532 ErrorDynamicPageInfo
*info
;
533 int id
= errorPageId(page_name
);
535 if (id
== ERR_NONE
) {
536 info
= errorDynamicPageInfoCreate(ERR_MAX
+ ErrorDynamicPages
.size(), page_name
);
537 ErrorDynamicPages
.push_back(info
);
544 /// \ingroup ErrorPageInternal
546 errorPageName(int pageId
)
548 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
549 return err_type_str
[pageId
];
551 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
552 return ErrorDynamicPages
.items
[pageId
- ERR_MAX
]->page_name
;
554 return "ERR_UNKNOWN"; /* should not happen */
558 errorCon(err_type type
, http_status status
, HttpRequest
* request
)
560 ErrorState
*err
= new ErrorState
;
561 err
->page_id
= type
; /* has to be reset manually if needed */
562 err
->err_language
= NULL
;
564 err
->httpStatus
= status
;
565 if (err
->page_id
>= ERR_MAX
&& ErrorDynamicPages
.items
[err
->page_id
- ERR_MAX
]->page_redirect
!= HTTP_STATUS_NONE
)
566 err
->httpStatus
= ErrorDynamicPages
.items
[err
->page_id
- ERR_MAX
]->page_redirect
;
568 if (request
!= NULL
) {
569 err
->request
= HTTPMSGLOCK(request
);
570 err
->src_addr
= request
->client_addr
;
571 request
->detailError(type
, ERR_DETAIL_NONE
);
578 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
580 assert(entry
->mem_obj
!= NULL
);
581 assert (entry
->isEmpty());
582 debugs(4, 4, "Creating an error page for entry " << entry
<<
583 " with errorstate " << err
<<
584 " page id " << err
->page_id
);
586 if (entry
->store_status
!= STORE_PENDING
) {
587 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
589 * If the entry is not STORE_PENDING, then no clients
590 * care about it, and we don't need to generate an
593 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
594 assert(entry
->mem_obj
->nclients
== 0);
599 if (err
->page_id
== TCP_RESET
) {
601 debugs(4, 2, "RSTing this reply");
602 err
->request
->flags
.setResetTCP();
608 entry
->replaceHttpReply( err
->BuildHttpReply() );
609 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
612 entry
->negativeCache();
613 entry
->releaseRequest();
619 errorSend(const Comm::ConnectionPointer
&conn
, ErrorState
* err
)
622 debugs(4, 3, HERE
<< conn
<< ", err=" << err
);
623 assert(Comm::IsConnOpen(conn
));
625 * ugh, this is how we make sure error codes get back to
626 * the client side for logging and error tracking.
630 err
->request
->detailError(err
->type
, err
->xerrno
);
632 /* moved in front of errorBuildBuf @?@ */
633 err
->flags
.flag_cbdata
= 1;
635 rep
= err
->BuildHttpReply();
637 MemBuf
*mb
= rep
->pack();
638 AsyncCall::Pointer call
= commCbCall(78, 5, "errorSendComplete",
639 CommIoCbPtrFun(&errorSendComplete
, err
));
640 Comm::Write(conn
, mb
, call
);
647 \ingroup ErrorPageAPI
649 * Called by commHandleWrite() after data has been written
650 * to the client socket.
652 \note If there is a callback, the callback is responsible for
653 * closing the FD, otherwise we do it ourselves.
656 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
658 ErrorState
*err
= static_cast<ErrorState
*>(data
);
659 debugs(4, 3, HERE
<< conn
<< ", size=" << size
);
661 if (errflag
!= COMM_ERR_CLOSING
) {
663 debugs(4, 3, "errorSendComplete: callback");
664 err
->callback(conn
->fd
, err
->callback_data
, size
);
666 debugs(4, 3, "errorSendComplete: comm_close");
675 errorStateFree(ErrorState
* err
)
677 HTTPMSGUNLOCK(err
->request
);
678 safe_free(err
->redirect_url
);
680 safe_free(err
->request_hdrs
);
681 wordlistDestroy(&err
->ftp
.server_msg
);
682 safe_free(err
->ftp
.request
);
683 safe_free(err
->ftp
.reply
);
685 err
->auth_user_request
= NULL
;
687 safe_free(err
->err_msg
);
689 if (err
->err_language
!= Config
.errorDefaultLanguage
)
691 safe_free(err
->err_language
);
699 ErrorState::Dump(MemBuf
* mb
)
702 char ntoabuf
[MAX_IPSTRLEN
];
705 /* email subject line */
706 str
.Printf("CacheErrorInfo - %s", errorPageName(type
));
707 mb
->Printf("?subject=%s", rfc1738_escape_part(str
.buf
));
710 str
.Printf("CacheHost: %s\r\n", getMyHostname());
712 str
.Printf("ErrPage: %s\r\n", errorPageName(type
));
715 str
.Printf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
717 str
.Printf("Err: [none]\r\n");
720 if (auth_user_request
->denyMessage())
721 str
.Printf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
723 if (dnsError
.size() > 0)
724 str
.Printf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
727 str
.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
730 str
.Printf("ClientIP: %s\r\n", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
732 if (request
&& request
->hier
.host
[0] != '\0') {
733 str
.Printf("ServerIP: %s\r\n", request
->hier
.host
);
738 str
.Printf("HTTP Request:\r\n");
740 if (NULL
!= request
) {
742 String urlpath_or_slash
;
744 if (request
->urlpath
.size() != 0)
745 urlpath_or_slash
= request
->urlpath
;
747 urlpath_or_slash
= "/";
749 str
.Printf("%s " SQUIDSTRINGPH
" HTTP/%d.%d\n",
750 RequestMethodStr(request
->method
),
751 SQUIDSTRINGPRINT(urlpath_or_slash
),
752 request
->http_ver
.major
, request
->http_ver
.minor
);
753 packerToMemInit(&pck
, &str
);
754 request
->header
.packInto(&pck
);
762 str
.Printf("FTP Request: %s\r\n", ftp
.request
);
763 str
.Printf("FTP Reply: %s\r\n", ftp
.reply
);
764 str
.Printf("FTP Msg: ");
765 wordlistCat(ftp
.server_msg
, &str
);
770 mb
->Printf("&body=%s", rfc1738_escape_part(str
.buf
));
775 /// \ingroup ErrorPageInternal
776 #define CVT_BUF_SZ 512
779 ErrorState::Convert(char token
, bool building_deny_info_url
, bool allowRecursion
)
782 const char *p
= NULL
; /* takes priority over mb if set */
784 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
785 char ntoabuf
[MAX_IPSTRLEN
];
793 if (request
&& request
->auth_user_request
!= NULL
)
794 p
= request
->auth_user_request
->username();
801 mb
.Printf("%d", getMyPort());
805 if (building_deny_info_url
) break;
806 p
= request
? ftpUrlWith2f(request
) : "[no URL]";
810 if (building_deny_info_url
) break;
811 p
= errorPageName(type
);
816 p
= "%D"; // if recursion is not allowed, do not convert
818 // currently only SSL error details implemented
820 detail
->useRequest(request
);
821 const String
&errDetail
= detail
->toString();
822 if (errDetail
.defined()) {
823 MemBuf
*detail_mb
= ConvertText(errDetail
.termedBuf(), false);
824 mb
.append(detail_mb
->content(), detail_mb
->contentSize());
830 if (!mb
.contentSize())
831 mb
.Printf("[No Error Detail]");
835 mb
.Printf("%d", xerrno
);
840 mb
.Printf("(%d) %s", xerrno
, strerror(xerrno
));
842 mb
.Printf("[No Error]");
846 if (building_deny_info_url
) break;
847 /* FTP REQUEST LINE */
855 if (building_deny_info_url
) break;
864 if (building_deny_info_url
) break;
865 /* FTP SERVER RESPONSE */
867 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
869 } else if (ftp
.server_msg
) {
870 wordlistCat(ftp
.server_msg
, &mb
);
875 mb
.Printf("%s", getMyHostname());
880 if (request
->hier
.host
[0] != '\0') // if non-empty string.
881 p
= request
->hier
.host
;
883 p
= request
->GetHost();
884 } else if (!building_deny_info_url
)
885 p
= "[unknown host]";
889 mb
.Printf("%s", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
893 if (request
&& request
->hier
.host
[0] != '\0') // if non-empty string
894 mb
.Printf("%s", request
->hier
.host
);
895 else if (!building_deny_info_url
)
900 if (building_deny_info_url
) break;
901 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
906 if (building_deny_info_url
) break;
907 if (Config
.errHtmlText
) {
908 mb
.Printf("%s", Config
.errHtmlText
);
911 p
= "[not available]";
915 if (building_deny_info_url
) break;
917 p
= auth_user_request
->denyMessage("[not available]");
925 p
= RequestMethodStr(request
->method
);
926 else if (!building_deny_info_url
)
927 p
= "[unknown method]";
931 p
= request
? request
->extacl_message
.termedBuf() : external_acl_message
;
932 if (!p
&& !building_deny_info_url
)
933 p
= "[not available]";
938 mb
.Printf("%d", (int) request
->port
);
939 } else if (!building_deny_info_url
) {
940 p
= "[unknown port]";
946 p
= AnyP::ProtocolType_str
[request
->protocol
];
947 } else if (!building_deny_info_url
) {
948 p
= "[unknown protocol]";
953 if (building_deny_info_url
) {
954 p
= (request
->urlpath
.size() != 0 ? request
->urlpath
.termedBuf() : "/");
957 if (NULL
!= request
) {
959 String urlpath_or_slash
;
961 if (request
->urlpath
.size() != 0)
962 urlpath_or_slash
= request
->urlpath
;
964 urlpath_or_slash
= "/";
966 mb
.Printf("%s " SQUIDSTRINGPH
" HTTP/%d.%d\n",
967 RequestMethodStr(request
->method
),
968 SQUIDSTRINGPRINT(urlpath_or_slash
),
969 request
->http_ver
.major
, request
->http_ver
.minor
);
970 packerToMemInit(&pck
, &mb
);
971 request
->header
.packInto(&pck
);
973 } else if (request_hdrs
) {
981 /* for backward compat we make %s show the full URL. Drop this in some future release. */
982 if (building_deny_info_url
) {
983 p
= request
? urlCanonical(request
) : url
;
984 debugs(0,0, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
986 p
= visible_appname_string
;
990 if (building_deny_info_url
) {
991 p
= visible_appname_string
;
994 /* signature may contain %-escapes, recursion */
995 if (page_id
!= ERR_SQUID_SIGNATURE
) {
996 const int saved_id
= page_id
;
997 page_id
= ERR_SQUID_SIGNATURE
;
998 MemBuf
*sign_mb
= BuildContent();
999 mb
.Printf("%s", sign_mb
->content());
1005 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1011 mb
.Printf("%s", Time::FormatHttpd(squid_curtime
));
1015 mb
.Printf("%s", mkrfc1123(squid_curtime
));
1019 /* Using the fake-https version of canonical so error pages see https:// */
1020 /* even when the url-path cannot be shown as more than '*' */
1022 p
= urlCanonicalFakeHttps(request
);
1025 else if (!building_deny_info_url
)
1031 p
= urlCanonical(request
);
1034 else if (!building_deny_info_url
)
1039 if (Config
.adminEmail
)
1040 mb
.Printf("%s", Config
.adminEmail
);
1041 else if (!building_deny_info_url
)
1046 if (building_deny_info_url
) break;
1047 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
1055 mb
.Printf("%s", detail
->errorName());
1058 if (!building_deny_info_url
)
1059 p
= "[Unknown Error Code]";
1063 if (building_deny_info_url
) break;
1064 if (dnsError
.size() > 0)
1065 p
= dnsError
.termedBuf();
1066 else if (ftp
.cwd_msg
)
1073 if (building_deny_info_url
) break;
1085 mb
.Printf("%%%c", token
);
1091 p
= mb
.buf
; /* do not use mb after this assignment! */
1095 debugs(4, 3, "errorConvert: %%" << token
<< " --> '" << p
<< "'" );
1100 if (building_deny_info_url
&& !no_urlescape
)
1101 p
= rfc1738_escape_part(p
);
1107 ErrorState::DenyInfoLocation(const char *name
, HttpRequest
*aRequest
, MemBuf
&result
)
1109 char const *m
= name
;
1114 m
+= 4; // skip "3xx:"
1116 while ((p
= strchr(m
, '%'))) {
1117 result
.append(m
, p
- m
); /* copy */
1118 t
= Convert(*++p
, true, true); /* convert */
1119 result
.Printf("%s", t
); /* copy */
1120 m
= p
+ 1; /* advance */
1124 result
.Printf("%s", m
); /* copy tail */
1126 assert((size_t)result
.contentSize() == strlen(result
.content()));
1130 ErrorState::BuildHttpReply()
1132 HttpReply
*rep
= new HttpReply
;
1133 const char *name
= errorPageName(page_id
);
1134 /* no LMT for error pages; error pages expire immediately */
1136 if (name
[0] == '3' || (name
[0] != '4' && name
[0] != '5' && strchr(name
, ':'))) {
1138 http_status status
= HTTP_MOVED_TEMPORARILY
;
1139 // Use configured 3xx reply status if set.
1141 status
= httpStatus
;
1143 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1144 if (request
->method
!= METHOD_GET
&& request
->method
!= METHOD_HEAD
&& request
->http_ver
>= HttpVersion(1,1))
1145 status
= HTTP_TEMPORARY_REDIRECT
;
1148 rep
->setHeaders(status
, NULL
, "text/html", 0, 0, -1);
1151 MemBuf redirect_location
;
1152 redirect_location
.init();
1153 DenyInfoLocation(name
, request
, redirect_location
);
1154 httpHeaderPutStrf(&rep
->header
, HDR_LOCATION
, "%s", redirect_location
.content() );
1157 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
1159 MemBuf
*content
= BuildContent();
1160 rep
->setHeaders(httpStatus
, NULL
, "text/html", content
->contentSize(), 0, -1);
1162 * include some information for downstream caches. Implicit
1163 * replaceable content. This isn't quite sufficient. xerrno is not
1164 * necessarily meaningful to another system, so we really should
1165 * expand it. Additionally, we should identify ourselves. Someone
1166 * might want to know. Someone _will_ want to know OTOH, the first
1167 * X-CACHE-MISS entry should tell us who.
1169 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%s %d", name
, xerrno
);
1173 * If error page auto-negotiate is enabled in any way, send the Vary.
1174 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1175 * We have even better reasons though:
1176 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1178 if (!Config
.errorDirectory
) {
1179 /* We 'negotiated' this ONLY from the Accept-Language. */
1180 rep
->header
.delById(HDR_VARY
);
1181 rep
->header
.putStr(HDR_VARY
, "Accept-Language");
1184 /* add the Content-Language header according to RFC section 14.12 */
1186 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, err_language
);
1188 #endif /* USE_ERROR_LOCALES */
1190 /* default templates are in English */
1191 /* language is known unless error_directory override used */
1192 if (!Config
.errorDirectory
)
1193 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, "en");
1196 httpBodySet(&rep
->body
, content
);
1197 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1204 ErrorState::BuildContent()
1206 const char *m
= NULL
;
1208 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
1211 ErrorPageFile
*localeTmpl
= NULL
;
1213 /** error_directory option in squid.conf overrides translations.
1214 * Custom errors are always found either in error_directory or the templates directory.
1215 * Otherwise locate the Accept-Language header
1217 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
) {
1218 if (err_language
&& err_language
!= Config
.errorDefaultLanguage
)
1219 safe_free(err_language
);
1221 localeTmpl
= new ErrorPageFile(err_type_str
[page_id
]);
1222 if (localeTmpl
->loadFor(request
)) {
1223 m
= localeTmpl
->text();
1224 assert(localeTmpl
->language());
1225 err_language
= xstrdup(localeTmpl
->language());
1228 #endif /* USE_ERR_LOCALES */
1231 * If client-specific error templates are not enabled or available.
1232 * fall back to the old style squid.conf settings.
1235 m
= error_text
[page_id
];
1237 if (!Config
.errorDirectory
)
1238 err_language
= Config
.errorDefaultLanguage
;
1240 debugs(4, 2, HERE
<< "No existing error page language negotiated for " << errorPageName(page_id
) << ". Using default error file.");
1243 MemBuf
*result
= ConvertText(m
, true);
1251 MemBuf
*ErrorState::ConvertText(const char *text
, bool allowRecursion
)
1253 MemBuf
*content
= new MemBuf
;
1255 const char *m
= text
;
1259 while ((p
= strchr(m
, '%'))) {
1260 content
->append(m
, p
- m
); /* copy */
1261 const char *t
= Convert(*++p
, false, allowRecursion
); /* convert */
1262 content
->Printf("%s", t
); /* copy */
1263 m
= p
+ 1; /* advance */
1267 content
->Printf("%s", m
); /* copy tail */
1269 assert((size_t)content
->contentSize() == strlen(content
->content()));