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 char *errorTryLoadText(const char *page_name
, const char *dir
, bool silent
= false);
133 static char *errorLoadText(const char *page_name
);
134 static const char *errorFindHardText(err_type type
);
135 static ErrorDynamicPageInfo
*errorDynamicPageInfoCreate(int id
, const char *page_name
);
136 static void errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
);
137 static IOCB errorSendComplete
;
140 /// \ingroup ErrorPageInternal
141 err_type
&operator++ (err_type
&anErr
)
143 int tmp
= (int)anErr
;
144 anErr
= (err_type
)(++tmp
);
148 /// \ingroup ErrorPageInternal
149 int operator - (err_type
const &anErr
, err_type
const &anErr2
)
151 return (int)anErr
- (int)anErr2
;
155 errorInitialize(void)
159 error_page_count
= ERR_MAX
+ ErrorDynamicPages
.size();
160 error_text
= static_cast<char **>(xcalloc(error_page_count
, sizeof(char *)));
162 for (i
= ERR_NONE
, ++i
; i
< error_page_count
; ++i
) {
163 safe_free(error_text
[i
]);
165 if ((text
= errorFindHardText(i
))) {
167 * Index any hard-coded error text into defaults.
169 error_text
[i
] = xstrdup(text
);
171 } else if (i
< ERR_MAX
) {
173 * Index precompiled fixed template files from one of two sources:
174 * (a) default language translation directory (error_default_language)
175 * (b) admin specified custom directory (error_directory)
177 error_text
[i
] = errorLoadText(err_type_str
[i
]);
181 * Index any unknown file names used by deny_info.
183 ErrorDynamicPageInfo
*info
= ErrorDynamicPages
.items
[i
- ERR_MAX
];
184 assert(info
&& info
->id
== i
&& info
->page_name
);
186 const char *pg
= info
->page_name
;
187 if (info
->page_redirect
!= HTTP_STATUS_NONE
)
188 pg
= info
->page_name
+4;
190 if (strchr(pg
, ':') == NULL
) {
191 /** But only if they are not redirection URL. */
192 error_text
[i
] = errorLoadText(pg
);
197 error_stylesheet
.reset();
199 // look for and load stylesheet into global MemBuf for it.
200 if (Config
.errorStylesheet
) {
201 char *temp
= errorTryLoadText(Config
.errorStylesheet
,NULL
);
203 error_stylesheet
.Printf("%s",temp
);
215 for (i
= ERR_NONE
+ 1; i
< error_page_count
; i
++)
216 safe_free(error_text
[i
]);
218 safe_free(error_text
);
221 while (ErrorDynamicPages
.size())
222 errorDynamicPageInfoDestroy(ErrorDynamicPages
.pop_back());
224 error_page_count
= 0;
227 /// \ingroup ErrorPageInternal
229 errorFindHardText(err_type type
)
233 for (i
= 0; i
< error_hard_text_count
; i
++)
234 if (error_hard_text
[i
].type
== type
)
235 return error_hard_text
[i
].text
;
241 * \ingroup ErrorPageInternal
243 * Load into the in-memory error text Index a file probably available at:
244 * (a) admin specified custom directory (error_directory)
245 * (b) default language translation directory (error_default_language)
246 * (c) English sub-directory where errors should ALWAYS exist
249 errorLoadText(const char *page_name
)
253 /** test error_directory configured location */
254 if (Config
.errorDirectory
)
255 text
= errorTryLoadText(page_name
, Config
.errorDirectory
);
258 /** test error_default_language location */
259 if (!text
&& Config
.errorDefaultLanguage
) {
261 snprintf(dir
,256,"%s/%s", DEFAULT_SQUID_ERROR_DIR
, Config
.errorDefaultLanguage
);
262 text
= errorTryLoadText(page_name
, dir
);
264 debugs(1, DBG_CRITICAL
, "Unable to load default error language files. Reset to backups.");
269 /* test default location if failed (templates == English translation base templates) */
271 text
= errorTryLoadText(page_name
, DEFAULT_SQUID_ERROR_DIR
"/templates");
274 /* giving up if failed */
276 fatal("failed to find or read error text file.");
281 /// \ingroup ErrorPageInternal
283 errorTryLoadText(const char *page_name
, const char *dir
, bool silent
)
286 char path
[MAXPATHLEN
];
292 // maybe received compound parts, maybe an absolute page_name and no dir
294 snprintf(path
, sizeof(path
), "%s/%s", dir
, page_name
);
296 snprintf(path
, sizeof(path
), "%s", page_name
);
298 fd
= file_open(path
, O_RDONLY
| O_TEXT
);
301 /* with dynamic locale negotiation we may see some failures before a success. */
303 debugs(4, DBG_CRITICAL
, HERE
<< "'" << path
<< "': " << xstrerror());
309 while ((len
= FD_READ_METHOD(fd
, buf
, sizeof(buf
))) > 0) {
310 textbuf
.append(buf
, len
);
314 debugs(4, DBG_CRITICAL
, HERE
<< "failed to fully read: '" << path
<< "': " << xstrerror());
319 /* Shrink memory size down to exact size. MemBuf has a tencendy
320 * to be rather large..
322 text
= xstrdup(textbuf
.buf
);
329 /// \ingroup ErrorPageInternal
330 static ErrorDynamicPageInfo
*
331 errorDynamicPageInfoCreate(int id
, const char *page_name
)
333 ErrorDynamicPageInfo
*info
= new ErrorDynamicPageInfo
;
335 info
->page_name
= xstrdup(page_name
);
336 info
->page_redirect
= static_cast<http_status
>(atoi(page_name
));
338 /* WARNING on redirection status:
339 * 2xx are permitted, but not documented officially.
340 * - might be useful for serving static files (PAC etc) in special cases
341 * 3xx require a URL suitable for Location: header.
342 * - the current design does not allow for a Location: URI as well as a local file template
343 * although this possibility is explicitly permitted in the specs.
344 * 4xx-5xx require a local file template.
345 * - sending Location: on these codes with no body is invalid by the specs.
346 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
347 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
349 if (info
->page_redirect
== HTTP_STATUS_NONE
)
350 ; // special case okay.
351 else if (info
->page_redirect
< 200 || info
->page_redirect
> 599) {
353 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
355 } else if ( /* >= 200 && */ info
->page_redirect
< 300 && strchr(&(page_name
[4]), ':')) {
356 // 2xx require a local template file
357 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
359 } else if (/* >= 300 && */ info
->page_redirect
<= 399 && !strchr(&(page_name
[4]), ':')) {
360 // 3xx require an absolute URL
361 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
363 } else if (info
->page_redirect
>= 400 /* && <= 599 */ && strchr(&(page_name
[4]), ':')) {
364 // 4xx/5xx require a local template file
365 debugs(0, DBG_CRITICAL
, "FATAL: status " << info
->page_redirect
<< " is not valid on '" << page_name
<< "'");
373 /// \ingroup ErrorPageInternal
375 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
)
378 safe_free(info
->page_name
);
382 /// \ingroup ErrorPageInternal
384 errorPageId(const char *page_name
)
386 for (int i
= 0; i
< ERR_MAX
; i
++) {
387 if (strcmp(err_type_str
[i
], page_name
) == 0)
391 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); j
++) {
392 if (strcmp(ErrorDynamicPages
.items
[j
]->page_name
, page_name
) == 0)
400 errorReservePageId(const char *page_name
)
402 ErrorDynamicPageInfo
*info
;
403 int id
= errorPageId(page_name
);
405 if (id
== ERR_NONE
) {
406 info
= errorDynamicPageInfoCreate(ERR_MAX
+ ErrorDynamicPages
.size(), page_name
);
407 ErrorDynamicPages
.push_back(info
);
414 /// \ingroup ErrorPageInternal
416 errorPageName(int pageId
)
418 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
419 return err_type_str
[pageId
];
421 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
422 return ErrorDynamicPages
.items
[pageId
- ERR_MAX
]->page_name
;
424 return "ERR_UNKNOWN"; /* should not happen */
428 errorCon(err_type type
, http_status status
, HttpRequest
* request
)
430 ErrorState
*err
= new ErrorState
;
431 err
->page_id
= type
; /* has to be reset manually if needed */
432 err
->err_language
= NULL
;
434 err
->httpStatus
= status
;
435 if (err
->page_id
>= ERR_MAX
&& ErrorDynamicPages
.items
[err
->page_id
- ERR_MAX
]->page_redirect
!= HTTP_STATUS_NONE
)
436 err
->httpStatus
= ErrorDynamicPages
.items
[err
->page_id
- ERR_MAX
]->page_redirect
;
438 if (request
!= NULL
) {
439 err
->request
= HTTPMSGLOCK(request
);
440 err
->src_addr
= request
->client_addr
;
441 request
->detailError(type
, ERR_DETAIL_NONE
);
448 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
450 assert(entry
->mem_obj
!= NULL
);
451 assert (entry
->isEmpty());
452 debugs(4, 4, "Creating an error page for entry " << entry
<<
453 " with errorstate " << err
<<
454 " page id " << err
->page_id
);
456 if (entry
->store_status
!= STORE_PENDING
) {
457 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
459 * If the entry is not STORE_PENDING, then no clients
460 * care about it, and we don't need to generate an
463 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
464 assert(entry
->mem_obj
->nclients
== 0);
469 if (err
->page_id
== TCP_RESET
) {
471 debugs(4, 2, "RSTing this reply");
472 err
->request
->flags
.setResetTCP();
478 entry
->replaceHttpReply( err
->BuildHttpReply() );
479 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
482 entry
->negativeCache();
483 entry
->releaseRequest();
489 errorSend(const Comm::ConnectionPointer
&conn
, ErrorState
* err
)
492 debugs(4, 3, HERE
<< conn
<< ", err=" << err
);
493 assert(Comm::IsConnOpen(conn
));
495 * ugh, this is how we make sure error codes get back to
496 * the client side for logging and error tracking.
500 err
->request
->detailError(err
->type
, err
->xerrno
);
502 /* moved in front of errorBuildBuf @?@ */
503 err
->flags
.flag_cbdata
= 1;
505 rep
= err
->BuildHttpReply();
507 MemBuf
*mb
= rep
->pack();
508 AsyncCall::Pointer call
= commCbCall(78, 5, "errorSendComplete",
509 CommIoCbPtrFun(&errorSendComplete
, err
));
510 Comm::Write(conn
, mb
, call
);
517 \ingroup ErrorPageAPI
519 * Called by commHandleWrite() after data has been written
520 * to the client socket.
522 \note If there is a callback, the callback is responsible for
523 * closing the FD, otherwise we do it ourselves.
526 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
528 ErrorState
*err
= static_cast<ErrorState
*>(data
);
529 debugs(4, 3, HERE
<< conn
<< ", size=" << size
);
531 if (errflag
!= COMM_ERR_CLOSING
) {
533 debugs(4, 3, "errorSendComplete: callback");
534 err
->callback(conn
->fd
, err
->callback_data
, size
);
536 debugs(4, 3, "errorSendComplete: comm_close");
545 errorStateFree(ErrorState
* err
)
547 HTTPMSGUNLOCK(err
->request
);
548 safe_free(err
->redirect_url
);
550 safe_free(err
->request_hdrs
);
551 wordlistDestroy(&err
->ftp
.server_msg
);
552 safe_free(err
->ftp
.request
);
553 safe_free(err
->ftp
.reply
);
555 err
->auth_user_request
= NULL
;
557 safe_free(err
->err_msg
);
559 if (err
->err_language
!= Config
.errorDefaultLanguage
)
561 safe_free(err
->err_language
);
569 ErrorState::Dump(MemBuf
* mb
)
572 const char *p
= NULL
; /* takes priority over mb if set */
573 char ntoabuf
[MAX_IPSTRLEN
];
576 /* email subject line */
577 str
.Printf("CacheErrorInfo - %s", errorPageName(type
));
578 mb
->Printf("?subject=%s", rfc1738_escape_part(str
.buf
));
581 str
.Printf("CacheHost: %s\r\n", getMyHostname());
583 str
.Printf("ErrPage: %s\r\n", errorPageName(type
));
586 str
.Printf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
588 str
.Printf("Err: [none]\r\n");
591 if (auth_user_request
->denyMessage())
592 str
.Printf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
594 if (dnsError
.size() > 0)
595 str
.Printf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
598 str
.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
601 str
.Printf("ClientIP: %s\r\n", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
603 if (request
&& request
->hier
.host
[0] != '\0') {
604 str
.Printf("ServerIP: %s\r\n", request
->hier
.host
);
609 str
.Printf("HTTP Request:\r\n");
611 if (NULL
!= request
) {
613 String urlpath_or_slash
;
615 if (request
->urlpath
.size() != 0)
616 urlpath_or_slash
= request
->urlpath
;
618 urlpath_or_slash
= "/";
620 str
.Printf("%s " SQUIDSTRINGPH
" HTTP/%d.%d\n",
621 RequestMethodStr(request
->method
),
622 SQUIDSTRINGPRINT(urlpath_or_slash
),
623 request
->http_ver
.major
, request
->http_ver
.minor
);
624 packerToMemInit(&pck
, &str
);
625 request
->header
.packInto(&pck
);
627 } else if (request_hdrs
) {
637 str
.Printf("FTP Request: %s\r\n", ftp
.request
);
638 str
.Printf("FTP Reply: %s\r\n", ftp
.reply
);
639 str
.Printf("FTP Msg: ");
640 wordlistCat(ftp
.server_msg
, &str
);
645 mb
->Printf("&body=%s", rfc1738_escape_part(str
.buf
));
650 /// \ingroup ErrorPageInternal
651 #define CVT_BUF_SZ 512
654 ErrorState::Convert(char token
, bool building_deny_info_url
, bool allowRecursion
)
657 const char *p
= NULL
; /* takes priority over mb if set */
659 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
660 char ntoabuf
[MAX_IPSTRLEN
];
668 if (request
&& request
->auth_user_request
!= NULL
)
669 p
= request
->auth_user_request
->username();
676 mb
.Printf("%d", getMyPort());
680 if (building_deny_info_url
) break;
681 p
= request
? ftpUrlWith2f(request
) : "[no URL]";
685 if (building_deny_info_url
) break;
686 p
= errorPageName(type
);
691 p
= "%D"; // if recursion is not allowed, do not convert
693 // currently only SSL error details implemented
695 const String
&errDetail
= detail
->toString();
696 if (errDetail
.defined()) {
697 MemBuf
*detail_mb
= ConvertText(errDetail
.termedBuf(), false);
698 mb
.append(detail_mb
->content(), detail_mb
->contentSize());
704 if (!mb
.contentSize())
705 mb
.Printf("[No Error Detail]");
709 mb
.Printf("%d", xerrno
);
714 mb
.Printf("(%d) %s", xerrno
, strerror(xerrno
));
716 mb
.Printf("[No Error]");
720 if (building_deny_info_url
) break;
721 /* FTP REQUEST LINE */
729 if (building_deny_info_url
) break;
738 if (building_deny_info_url
) break;
739 /* FTP SERVER RESPONSE */
741 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
743 } else if (ftp
.server_msg
) {
744 wordlistCat(ftp
.server_msg
, &mb
);
749 mb
.Printf("%s", getMyHostname());
754 if (request
->hier
.host
[0] != '\0') // if non-empty string.
755 p
= request
->hier
.host
;
757 p
= request
->GetHost();
758 } else if (!building_deny_info_url
)
759 p
= "[unknown host]";
763 mb
.Printf("%s", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
767 if (request
&& request
->hier
.host
[0] != '\0') // if non-empty string
768 mb
.Printf("%s", request
->hier
.host
);
769 else if (!building_deny_info_url
)
774 if (building_deny_info_url
) break;
775 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
780 if (building_deny_info_url
) break;
781 if (Config
.errHtmlText
) {
782 mb
.Printf("%s", Config
.errHtmlText
);
785 p
= "[not available]";
789 if (building_deny_info_url
) break;
791 p
= auth_user_request
->denyMessage("[not available]");
799 p
= RequestMethodStr(request
->method
);
800 else if (!building_deny_info_url
)
801 p
= "[unknown method]";
805 p
= request
? request
->extacl_message
.termedBuf() : external_acl_message
;
806 if (!p
&& !building_deny_info_url
)
807 p
= "[not available]";
812 mb
.Printf("%d", (int) request
->port
);
813 } else if (!building_deny_info_url
) {
814 p
= "[unknown port]";
820 p
= AnyP::ProtocolType_str
[request
->protocol
];
821 } else if (!building_deny_info_url
) {
822 p
= "[unknown protocol]";
827 if (building_deny_info_url
) {
828 p
= (request
->urlpath
.size() != 0 ? request
->urlpath
.termedBuf() : "/");
831 if (NULL
!= request
) {
833 String urlpath_or_slash
;
835 if (request
->urlpath
.size() != 0)
836 urlpath_or_slash
= request
->urlpath
;
838 urlpath_or_slash
= "/";
840 mb
.Printf("%s " SQUIDSTRINGPH
" HTTP/%d.%d\n",
841 RequestMethodStr(request
->method
),
842 SQUIDSTRINGPRINT(urlpath_or_slash
),
843 request
->http_ver
.major
, request
->http_ver
.minor
);
844 packerToMemInit(&pck
, &mb
);
845 request
->header
.packInto(&pck
);
847 } else if (request_hdrs
) {
855 /* for backward compat we make %s show the full URL. Drop this in some future release. */
856 if (building_deny_info_url
) {
857 p
= request
? urlCanonical(request
) : url
;
858 debugs(0,0, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
860 p
= visible_appname_string
;
864 if (building_deny_info_url
) {
865 p
= visible_appname_string
;
868 /* signature may contain %-escapes, recursion */
869 if (page_id
!= ERR_SQUID_SIGNATURE
) {
870 const int saved_id
= page_id
;
871 page_id
= ERR_SQUID_SIGNATURE
;
872 MemBuf
*sign_mb
= BuildContent();
873 mb
.Printf("%s", sign_mb
->content());
879 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
885 mb
.Printf("%s", Time::FormatHttpd(squid_curtime
));
889 mb
.Printf("%s", mkrfc1123(squid_curtime
));
893 /* Using the fake-https version of canonical so error pages see https:// */
894 /* even when the url-path cannot be shown as more than '*' */
896 p
= urlCanonicalFakeHttps(request
);
899 else if (!building_deny_info_url
)
905 p
= urlCanonical(request
);
908 else if (!building_deny_info_url
)
913 if (Config
.adminEmail
)
914 mb
.Printf("%s", Config
.adminEmail
);
915 else if (!building_deny_info_url
)
920 if (building_deny_info_url
) break;
921 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
927 if (building_deny_info_url
) break;
928 if (dnsError
.size() > 0)
929 p
= dnsError
.termedBuf();
930 else if (ftp
.cwd_msg
)
937 if (building_deny_info_url
) break;
949 mb
.Printf("%%%c", token
);
955 p
= mb
.buf
; /* do not use mb after this assignment! */
959 debugs(4, 3, "errorConvert: %%" << token
<< " --> '" << p
<< "'" );
964 if (building_deny_info_url
&& !no_urlescape
)
965 p
= rfc1738_escape_part(p
);
971 ErrorState::DenyInfoLocation(const char *name
, HttpRequest
*aRequest
, MemBuf
&result
)
973 char const *m
= name
;
978 m
+= 4; // skip "3xx:"
980 while ((p
= strchr(m
, '%'))) {
981 result
.append(m
, p
- m
); /* copy */
982 t
= Convert(*++p
, true, true); /* convert */
983 result
.Printf("%s", t
); /* copy */
984 m
= p
+ 1; /* advance */
988 result
.Printf("%s", m
); /* copy tail */
990 assert((size_t)result
.contentSize() == strlen(result
.content()));
994 ErrorState::BuildHttpReply()
996 HttpReply
*rep
= new HttpReply
;
997 const char *name
= errorPageName(page_id
);
998 /* no LMT for error pages; error pages expire immediately */
1000 if (name
[0] == '3' || (name
[0] != '4' && name
[0] != '5' && strchr(name
, ':'))) {
1002 http_status status
= HTTP_MOVED_TEMPORARILY
;
1003 // Use configured 3xx reply status if set.
1005 status
= httpStatus
;
1007 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1008 if (request
->method
!= METHOD_GET
&& request
->method
!= METHOD_HEAD
&& request
->http_ver
>= HttpVersion(1,1))
1009 status
= HTTP_TEMPORARY_REDIRECT
;
1012 rep
->setHeaders(status
, NULL
, "text/html", 0, 0, -1);
1015 MemBuf redirect_location
;
1016 redirect_location
.init();
1017 DenyInfoLocation(name
, request
, redirect_location
);
1018 httpHeaderPutStrf(&rep
->header
, HDR_LOCATION
, "%s", redirect_location
.content() );
1021 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
1023 MemBuf
*content
= BuildContent();
1024 rep
->setHeaders(httpStatus
, NULL
, "text/html", content
->contentSize(), 0, -1);
1026 * include some information for downstream caches. Implicit
1027 * replaceable content. This isn't quite sufficient. xerrno is not
1028 * necessarily meaningful to another system, so we really should
1029 * expand it. Additionally, we should identify ourselves. Someone
1030 * might want to know. Someone _will_ want to know OTOH, the first
1031 * X-CACHE-MISS entry should tell us who.
1033 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%s %d", name
, xerrno
);
1037 * If error page auto-negotiate is enabled in any way, send the Vary.
1038 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1039 * We have even better reasons though:
1040 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1042 if (!Config
.errorDirectory
) {
1043 /* We 'negotiated' this ONLY from the Accept-Language. */
1044 rep
->header
.delById(HDR_VARY
);
1045 rep
->header
.putStr(HDR_VARY
, "Accept-Language");
1048 /* add the Content-Language header according to RFC section 14.12 */
1050 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, err_language
);
1052 #endif /* USE_ERROR_LOCALES */
1054 /* default templates are in English */
1055 /* language is known unless error_directory override used */
1056 if (!Config
.errorDirectory
)
1057 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, "en");
1060 httpBodySet(&rep
->body
, content
);
1061 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1068 ErrorState::BuildContent()
1070 const char *m
= NULL
;
1072 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
1078 const char *freePage
= NULL
;
1080 /** error_directory option in squid.conf overrides translations.
1081 * Custom errors are always found either in error_directory or the templates directory.
1082 * Otherwise locate the Accept-Language header
1084 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
&& request
&& request
->header
.getList(HDR_ACCEPT_LANGUAGE
, &hdr
) ) {
1086 size_t pos
= 0; // current parsing position in header string
1087 char *reset
= NULL
; // where to reset the p pointer for each new tag file
1090 /* prep the directory path string to prevent snprintf ... */
1091 l
= strlen(DEFAULT_SQUID_ERROR_DIR
);
1092 memcpy(dir
, DEFAULT_SQUID_ERROR_DIR
, l
);
1094 reset
= dt
= dir
+ l
;
1096 debugs(4, 6, HERE
<< "Testing Header: '" << hdr
<< "'");
1098 while ( pos
< hdr
.size() ) {
1100 /* skip any initial whitespace. */
1101 while (pos
< hdr
.size() && xisspace(hdr
[pos
])) pos
++;
1104 * Header value format:
1105 * - sequence of whitespace delimited tags
1106 * - each tag may suffix with ';'.* which we can ignore.
1107 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
1108 * with preference given to an exact match.
1110 bool invalid_byte
= false;
1111 while (pos
< hdr
.size() && hdr
[pos
] != ';' && hdr
[pos
] != ',' && !xisspace(hdr
[pos
]) && dt
< (dir
+256) ) {
1112 if (!invalid_byte
) {
1113 #if USE_HTTP_VIOLATIONS
1114 // if accepting violations we may as well accept some broken browsers
1115 // which may send us the right code, wrong ISO formatting.
1116 if (hdr
[pos
] == '_')
1120 *dt
= xtolower(hdr
[pos
]);
1121 // valid codes only contain A-Z, hyphen (-) and *
1122 if (*dt
!= '-' && *dt
!= '*' && (*dt
< 'a' || *dt
> 'z') )
1123 invalid_byte
= true;
1125 dt
++; // move to next destination byte.
1129 *dt
++ = '\0'; // nul-terminated the filename content string before system use.
1131 debugs(4, 9, HERE
<< "STATE: dt='" << dt
<< "', reset='" << reset
<< "', pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
1133 /* if we found anything we might use, try it. */
1134 if (*reset
!= '\0' && !invalid_byte
) {
1136 /* wildcard uses the configured default language */
1137 if (reset
[0] == '*' && reset
[1] == '\0') {
1138 debugs(4, 6, HERE
<< "Found language '" << reset
<< "'. Using configured default.");
1139 m
= error_text
[page_id
];
1140 if (!Config
.errorDirectory
)
1141 err_language
= Config
.errorDefaultLanguage
;
1145 debugs(4, 6, HERE
<< "Found language '" << reset
<< "', testing for available template in: '" << dir
<< "'");
1147 m
= errorTryLoadText( err_type_str
[page_id
], dir
, false);
1150 /* store the language we found for the Content-Language reply header */
1151 err_language
= xstrdup(reset
);
1154 } else if (Config
.errorLogMissingLanguages
) {
1155 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << reset
);
1159 if ( (dt
- reset
) == 2) {
1160 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
1161 /* use first result. */
1162 debugs(4,2, HERE
<< "wildcard fallback errors not coded yet.");
1167 dt
= reset
; // reset for next tag testing. we replace the failed name instead of cloning.
1169 // IFF we terminated the tag on whitespace or ';' we need to skip to the next ',' or end of header.
1170 while (pos
< hdr
.size() && hdr
[pos
] != ',') pos
++;
1171 if (hdr
[pos
] == ',') pos
++;
1174 #endif /* USE_ERR_LOCALES */
1177 * If client-specific error templates are not enabled or available.
1178 * fall back to the old style squid.conf settings.
1181 m
= error_text
[page_id
];
1183 if (!Config
.errorDirectory
)
1184 err_language
= Config
.errorDefaultLanguage
;
1186 debugs(4, 2, HERE
<< "No existing error page language negotiated for " << errorPageName(page_id
) << ". Using default error file.");
1189 MemBuf
*result
= ConvertText(m
, true);
1191 safe_free(freePage
);
1197 MemBuf
*ErrorState::ConvertText(const char *text
, bool allowRecursion
)
1199 MemBuf
*content
= new MemBuf
;
1201 const char *m
= text
;
1205 while ((p
= strchr(m
, '%'))) {
1206 content
->append(m
, p
- m
); /* copy */
1207 const char *t
= Convert(*++p
, false, allowRecursion
); /* convert */
1208 content
->Printf("%s", t
); /* copy */
1209 m
= p
+ 1; /* advance */
1213 content
->Printf("%s", m
); /* copy tail */
1215 assert((size_t)content
->contentSize() == strlen(content
->content()));