]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/errorpage.cc
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.
36 #include "auth/UserRequest.h"
37 #include "comm/Connection.h"
38 #include "err_detail_type.h"
39 #include "errorpage.h"
41 #include "html_quote.h"
42 #include "HttpReply.h"
43 #include "HttpRequest.h"
45 #include "MemObject.h"
47 #include "SquidTime.h"
49 #include "URLScheme.h"
53 \defgroup ErrorPageInternal Error Page Internals
56 \section Abstract Abstract:
57 * These routines are used to generate error messages to be
58 * sent to clients. The error type is used to select between
59 * the various message formats. (formats are stored in the
60 * Config.errorDirectory)
64 #ifndef DEFAULT_SQUID_ERROR_DIR
65 /** Where to look for errors if config path fails.
66 \note Please use ./configure --datadir=/path instead of patching
68 #define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
71 /// \ingroup ErrorPageInternal
72 CBDATA_CLASS_INIT(ErrorState
);
76 /// \ingroup ErrorPageInternal
80 } ErrorDynamicPageInfo
;
82 /* local constant and vars */
85 \ingroup ErrorPageInternal
87 \note hard coded error messages are not appended with %S
88 * automagically to give you more control on the format
91 int type
; /* and page_id */
101 "<div id=\"footer\">\n"
102 "Generated %T by %h (%s)\n"
112 /// \ingroup ErrorPageInternal
113 static Vector
<ErrorDynamicPageInfo
*> ErrorDynamicPages
;
115 /* local prototypes */
117 /// \ingroup ErrorPageInternal
118 static const int error_hard_text_count
= sizeof(error_hard_text
) / sizeof(*error_hard_text
);
120 /// \ingroup ErrorPageInternal
121 static char **error_text
= NULL
;
123 /// \ingroup ErrorPageInternal
124 static int error_page_count
= 0;
126 /// \ingroup ErrorPageInternal
127 static MemBuf error_stylesheet
;
129 static char *errorTryLoadText(const char *page_name
, const char *dir
, bool silent
= false);
130 static char *errorLoadText(const char *page_name
);
131 static const char *errorFindHardText(err_type type
);
132 static ErrorDynamicPageInfo
*errorDynamicPageInfoCreate(int id
, const char *page_name
);
133 static void errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
);
134 static IOCB errorSendComplete
;
137 /// \ingroup ErrorPageInternal
138 err_type
&operator++ (err_type
&anErr
)
140 int tmp
= (int)anErr
;
141 anErr
= (err_type
)(++tmp
);
145 /// \ingroup ErrorPageInternal
146 int operator - (err_type
const &anErr
, err_type
const &anErr2
)
148 return (int)anErr
- (int)anErr2
;
152 errorInitialize(void)
156 error_page_count
= ERR_MAX
+ ErrorDynamicPages
.size();
157 error_text
= static_cast<char **>(xcalloc(error_page_count
, sizeof(char *)));
159 for (i
= ERR_NONE
, ++i
; i
< error_page_count
; ++i
) {
160 safe_free(error_text
[i
]);
162 if ((text
= errorFindHardText(i
))) {
164 * Index any hard-coded error text into defaults.
166 error_text
[i
] = xstrdup(text
);
168 } else if (i
< ERR_MAX
) {
170 * Index precompiled fixed template files from one of two sources:
171 * (a) default language translation directory (error_default_language)
172 * (b) admin specified custom directory (error_directory)
174 error_text
[i
] = errorLoadText(err_type_str
[i
]);
178 * Index any unknown file names used by deny_info.
180 ErrorDynamicPageInfo
*info
= ErrorDynamicPages
.items
[i
- ERR_MAX
];
181 assert(info
&& info
->id
== i
&& info
->page_name
);
183 if (strchr(info
->page_name
, ':') == NULL
) {
184 /** But only if they are not redirection URL. */
185 error_text
[i
] = errorLoadText(info
->page_name
);
190 error_stylesheet
.reset();
192 // look for and load stylesheet into global MemBuf for it.
193 if (Config
.errorStylesheet
) {
194 char *temp
= errorTryLoadText(Config
.errorStylesheet
,NULL
);
196 error_stylesheet
.Printf("%s",temp
);
208 for (i
= ERR_NONE
+ 1; i
< error_page_count
; i
++)
209 safe_free(error_text
[i
]);
211 safe_free(error_text
);
214 while (ErrorDynamicPages
.size())
215 errorDynamicPageInfoDestroy(ErrorDynamicPages
.pop_back());
217 error_page_count
= 0;
220 /// \ingroup ErrorPageInternal
222 errorFindHardText(err_type type
)
226 for (i
= 0; i
< error_hard_text_count
; i
++)
227 if (error_hard_text
[i
].type
== type
)
228 return error_hard_text
[i
].text
;
234 * \ingroup ErrorPageInternal
236 * Load into the in-memory error text Index a file probably available at:
237 * (a) admin specified custom directory (error_directory)
238 * (b) default language translation directory (error_default_language)
239 * (c) English sub-directory where errors should ALWAYS exist
242 errorLoadText(const char *page_name
)
246 /** test error_directory configured location */
247 if (Config
.errorDirectory
)
248 text
= errorTryLoadText(page_name
, Config
.errorDirectory
);
251 /** test error_default_language location */
252 if (!text
&& Config
.errorDefaultLanguage
) {
254 snprintf(dir
,256,"%s/%s", DEFAULT_SQUID_ERROR_DIR
, Config
.errorDefaultLanguage
);
255 text
= errorTryLoadText(page_name
, dir
);
257 debugs(1, DBG_CRITICAL
, "Unable to load default error language files. Reset to backups.");
262 /* test default location if failed (templates == English translation base templates) */
264 text
= errorTryLoadText(page_name
, DEFAULT_SQUID_ERROR_DIR
"/templates");
267 /* giving up if failed */
269 fatal("failed to find or read error text file.");
274 /// \ingroup ErrorPageInternal
276 errorTryLoadText(const char *page_name
, const char *dir
, bool silent
)
279 char path
[MAXPATHLEN
];
285 // maybe received compound parts, maybe an absolute page_name and no dir
287 snprintf(path
, sizeof(path
), "%s/%s", dir
, page_name
);
289 snprintf(path
, sizeof(path
), "%s", page_name
);
291 fd
= file_open(path
, O_RDONLY
| O_TEXT
);
294 /* with dynamic locale negotiation we may see some failures before a success. */
296 debugs(4, DBG_CRITICAL
, HERE
<< "'" << path
<< "': " << xstrerror());
302 while ((len
= FD_READ_METHOD(fd
, buf
, sizeof(buf
))) > 0) {
303 textbuf
.append(buf
, len
);
307 debugs(4, DBG_CRITICAL
, HERE
<< "failed to fully read: '" << path
<< "': " << xstrerror());
312 /* Shrink memory size down to exact size. MemBuf has a tencendy
313 * to be rather large..
315 text
= xstrdup(textbuf
.buf
);
322 /// \ingroup ErrorPageInternal
323 static ErrorDynamicPageInfo
*
324 errorDynamicPageInfoCreate(int id
, const char *page_name
)
326 ErrorDynamicPageInfo
*info
= new ErrorDynamicPageInfo
;
328 info
->page_name
= xstrdup(page_name
);
332 /// \ingroup ErrorPageInternal
334 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
)
337 safe_free(info
->page_name
);
341 /// \ingroup ErrorPageInternal
343 errorPageId(const char *page_name
)
345 for (int i
= 0; i
< ERR_MAX
; i
++) {
346 if (strcmp(err_type_str
[i
], page_name
) == 0)
350 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); j
++) {
351 if (strcmp(ErrorDynamicPages
.items
[j
]->page_name
, page_name
) == 0)
359 errorReservePageId(const char *page_name
)
361 ErrorDynamicPageInfo
*info
;
362 int id
= errorPageId(page_name
);
364 if (id
== ERR_NONE
) {
365 info
= errorDynamicPageInfoCreate(ERR_MAX
+ ErrorDynamicPages
.size(), page_name
);
366 ErrorDynamicPages
.push_back(info
);
373 /// \ingroup ErrorPageInternal
375 errorPageName(int pageId
)
377 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
378 return err_type_str
[pageId
];
380 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
381 return ErrorDynamicPages
.items
[pageId
- ERR_MAX
]->page_name
;
383 return "ERR_UNKNOWN"; /* should not happen */
387 errorCon(err_type type
, http_status status
, HttpRequest
* request
)
389 ErrorState
*err
= new ErrorState
;
390 err
->page_id
= type
; /* has to be reset manually if needed */
391 err
->err_language
= NULL
;
393 err
->httpStatus
= status
;
395 if (request
!= NULL
) {
396 err
->request
= HTTPMSGLOCK(request
);
397 err
->src_addr
= request
->client_addr
;
398 request
->detailError(type
, ERR_DETAIL_NONE
);
405 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
407 assert(entry
->mem_obj
!= NULL
);
408 assert (entry
->isEmpty());
409 debugs(4, 4, "Creating an error page for entry " << entry
<<
410 " with errorstate " << err
<<
411 " page id " << err
->page_id
);
413 if (entry
->store_status
!= STORE_PENDING
) {
414 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
416 * If the entry is not STORE_PENDING, then no clients
417 * care about it, and we don't need to generate an
420 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
421 assert(entry
->mem_obj
->nclients
== 0);
426 if (err
->page_id
== TCP_RESET
) {
428 debugs(4, 2, "RSTing this reply");
429 err
->request
->flags
.setResetTCP();
435 entry
->replaceHttpReply( err
->BuildHttpReply() );
436 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
439 entry
->negativeCache();
440 entry
->releaseRequest();
446 errorSend(const Comm::ConnectionPointer
&conn
, ErrorState
* err
)
449 debugs(4, 3, HERE
<< conn
<< ", err=" << err
);
450 assert(Comm::IsConnOpen(conn
));
452 * ugh, this is how we make sure error codes get back to
453 * the client side for logging and error tracking.
457 err
->request
->detailError(err
->type
, err
->xerrno
);
459 /* moved in front of errorBuildBuf @?@ */
460 err
->flags
.flag_cbdata
= 1;
462 rep
= err
->BuildHttpReply();
463 MemBuf
*mb
= rep
->pack();
464 comm_write_mbuf(conn
, mb
, errorSendComplete
, err
);
470 \ingroup ErrorPageAPI
472 * Called by commHandleWrite() after data has been written
473 * to the client socket.
475 \note If there is a callback, the callback is responsible for
476 * closing the FD, otherwise we do it ourselves.
479 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
481 ErrorState
*err
= static_cast<ErrorState
*>(data
);
482 debugs(4, 3, HERE
<< conn
<< ", size=" << size
);
484 if (errflag
!= COMM_ERR_CLOSING
) {
486 debugs(4, 3, "errorSendComplete: callback");
487 err
->callback(conn
->fd
, err
->callback_data
, size
);
489 debugs(4, 3, "errorSendComplete: comm_close");
498 errorStateFree(ErrorState
* err
)
500 HTTPMSGUNLOCK(err
->request
);
501 safe_free(err
->redirect_url
);
503 safe_free(err
->request_hdrs
);
504 wordlistDestroy(&err
->ftp
.server_msg
);
505 safe_free(err
->ftp
.request
);
506 safe_free(err
->ftp
.reply
);
507 err
->auth_user_request
= NULL
;
508 safe_free(err
->err_msg
);
510 if (err
->err_language
!= Config
.errorDefaultLanguage
)
512 safe_free(err
->err_language
);
517 ErrorState::Dump(MemBuf
* mb
)
520 const char *p
= NULL
; /* takes priority over mb if set */
521 char ntoabuf
[MAX_IPSTRLEN
];
524 /* email subject line */
525 str
.Printf("CacheErrorInfo - %s", errorPageName(type
));
526 mb
->Printf("?subject=%s", rfc1738_escape_part(str
.buf
));
529 str
.Printf("CacheHost: %s\r\n", getMyHostname());
531 str
.Printf("ErrPage: %s\r\n", errorPageName(type
));
534 str
.Printf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
536 str
.Printf("Err: [none]\r\n");
539 if (auth_user_request
->denyMessage())
540 str
.Printf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
542 if (dnsError
.size() > 0)
543 str
.Printf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
546 str
.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
549 str
.Printf("ClientIP: %s\r\n", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
551 if (request
&& request
->hier
.host
[0] != '\0') {
552 str
.Printf("ServerIP: %s\r\n", request
->hier
.host
);
557 str
.Printf("HTTP Request:\r\n");
559 if (NULL
!= request
) {
561 String urlpath_or_slash
;
563 if (request
->urlpath
.size() != 0)
564 urlpath_or_slash
= request
->urlpath
;
566 urlpath_or_slash
= "/";
568 str
.Printf("%s " SQUIDSTRINGPH
" HTTP/%d.%d\n",
569 RequestMethodStr(request
->method
),
570 SQUIDSTRINGPRINT(urlpath_or_slash
),
571 request
->http_ver
.major
, request
->http_ver
.minor
);
572 packerToMemInit(&pck
, &str
);
573 request
->header
.packInto(&pck
);
575 } else if (request_hdrs
) {
585 str
.Printf("FTP Request: %s\r\n", ftp
.request
);
586 str
.Printf("FTP Reply: %s\r\n", ftp
.reply
);
587 str
.Printf("FTP Msg: ");
588 wordlistCat(ftp
.server_msg
, &str
);
593 mb
->Printf("&body=%s", rfc1738_escape_part(str
.buf
));
598 /// \ingroup ErrorPageInternal
599 #define CVT_BUF_SZ 512
602 ErrorState::Convert(char token
, bool building_deny_info_url
)
605 const char *p
= NULL
; /* takes priority over mb if set */
607 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
608 char ntoabuf
[MAX_IPSTRLEN
];
615 if (request
&& request
->auth_user_request
!= NULL
)
616 p
= request
->auth_user_request
->username();
622 if (building_deny_info_url
) break;
623 p
= request
? ftpUrlWith2f(request
) : "[no URL]";
627 if (building_deny_info_url
) break;
628 p
= errorPageName(type
);
632 mb
.Printf("%d", xerrno
);
637 mb
.Printf("(%d) %s", xerrno
, strerror(xerrno
));
639 mb
.Printf("[No Error]");
643 if (building_deny_info_url
) break;
644 /* FTP REQUEST LINE */
652 if (building_deny_info_url
) break;
661 if (building_deny_info_url
) break;
662 /* FTP SERVER MESSAGE */
664 wordlistCat(ftp
.server_msg
, &mb
);
665 else if (ftp
.listing
) {
666 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
672 mb
.Printf("%s", getMyHostname());
677 if (request
->hier
.host
[0] != '\0') // if non-empty string.
678 p
= request
->hier
.host
;
680 p
= request
->GetHost();
681 } else if (!building_deny_info_url
)
682 p
= "[unknown host]";
686 mb
.Printf("%s", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
690 if (request
&& request
->hier
.host
[0] != '\0') // if non-empty string
691 mb
.Printf("%s", request
->hier
.host
);
692 else if (!building_deny_info_url
)
697 if (building_deny_info_url
) break;
698 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
703 if (building_deny_info_url
) break;
704 if (Config
.errHtmlText
) {
705 mb
.Printf("%s", Config
.errHtmlText
);
708 p
= "[not available]";
712 if (building_deny_info_url
) break;
713 p
= auth_user_request
->denyMessage("[not available]");
718 p
= RequestMethodStr(request
->method
);
719 else if (!building_deny_info_url
)
720 p
= "[unknown method]";
724 p
= request
? request
->extacl_message
.termedBuf() : external_acl_message
;
725 if (!p
&& !building_deny_info_url
)
726 p
= "[not available]";
731 mb
.Printf("%d", (int) request
->port
);
732 } else if (!building_deny_info_url
) {
733 p
= "[unknown port]";
739 p
= ProtocolStr
[request
->protocol
];
740 } else if (!building_deny_info_url
) {
741 p
= "[unknown protocol]";
746 if (building_deny_info_url
) {
747 p
= (request
->urlpath
.size() != 0 ? request
->urlpath
.termedBuf() : "/");
750 if (NULL
!= request
) {
752 String urlpath_or_slash
;
754 if (request
->urlpath
.size() != 0)
755 urlpath_or_slash
= request
->urlpath
;
757 urlpath_or_slash
= "/";
759 mb
.Printf("%s " SQUIDSTRINGPH
" HTTP/%d.%d\n",
760 RequestMethodStr(request
->method
),
761 SQUIDSTRINGPRINT(urlpath_or_slash
),
762 request
->http_ver
.major
, request
->http_ver
.minor
);
763 packerToMemInit(&pck
, &mb
);
764 request
->header
.packInto(&pck
);
766 } else if (request_hdrs
) {
774 /* for backward compat we make %s show the full URL. Drop this in some future release. */
775 if (building_deny_info_url
) {
776 p
= request
? urlCanonical(request
) : url
;
777 debugs(0,0, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
779 p
= visible_appname_string
;
783 if (building_deny_info_url
) {
784 p
= visible_appname_string
;
787 /* signature may contain %-escapes, recursion */
788 if (page_id
!= ERR_SQUID_SIGNATURE
) {
789 const int saved_id
= page_id
;
790 page_id
= ERR_SQUID_SIGNATURE
;
791 MemBuf
*sign_mb
= BuildContent();
792 mb
.Printf("%s", sign_mb
->content());
798 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
804 mb
.Printf("%s", mkhttpdlogtime(&squid_curtime
));
808 mb
.Printf("%s", mkrfc1123(squid_curtime
));
812 /* Using the fake-https version of canonical so error pages see https:// */
813 /* even when the url-path cannot be shown as more than '*' */
815 p
= urlCanonicalFakeHttps(request
);
818 else if (!building_deny_info_url
)
824 p
= urlCanonical(request
);
827 else if (!building_deny_info_url
)
832 if (Config
.adminEmail
)
833 mb
.Printf("%s", Config
.adminEmail
);
834 else if (!building_deny_info_url
)
839 if (building_deny_info_url
) break;
840 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
846 if (building_deny_info_url
) break;
847 if (dnsError
.size() > 0)
848 p
= dnsError
.termedBuf();
849 else if (ftp
.cwd_msg
)
856 if (building_deny_info_url
) break;
868 mb
.Printf("%%%c", token
);
874 p
= mb
.buf
; /* do not use mb after this assignment! */
878 debugs(4, 3, "errorConvert: %%" << token
<< " --> '" << p
<< "'" );
883 if (building_deny_info_url
&& !no_urlescape
)
884 p
= rfc1738_escape_part(p
);
890 ErrorState::DenyInfoLocation(const char *name
, HttpRequest
*aRequest
, MemBuf
&result
)
892 char const *m
= name
;
896 while ((p
= strchr(m
, '%'))) {
897 result
.append(m
, p
- m
); /* copy */
898 t
= Convert(*++p
, true); /* convert */
899 result
.Printf("%s", t
); /* copy */
900 m
= p
+ 1; /* advance */
904 result
.Printf("%s", m
); /* copy tail */
906 assert((size_t)result
.contentSize() == strlen(result
.content()));
910 ErrorState::BuildHttpReply()
912 HttpReply
*rep
= new HttpReply
;
913 const char *name
= errorPageName(page_id
);
914 /* no LMT for error pages; error pages expire immediately */
916 if (strchr(name
, ':')) {
918 rep
->setHeaders(HTTP_MOVED_TEMPORARILY
, NULL
, "text/html", 0, 0, -1);
921 MemBuf redirect_location
;
922 redirect_location
.init();
923 DenyInfoLocation(name
, request
, redirect_location
);
924 httpHeaderPutStrf(&rep
->header
, HDR_LOCATION
, "%s", redirect_location
.content() );
927 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
929 MemBuf
*content
= BuildContent();
930 rep
->setHeaders(httpStatus
, NULL
, "text/html", content
->contentSize(), 0, -1);
932 * include some information for downstream caches. Implicit
933 * replaceable content. This isn't quite sufficient. xerrno is not
934 * necessarily meaningful to another system, so we really should
935 * expand it. Additionally, we should identify ourselves. Someone
936 * might want to know. Someone _will_ want to know OTOH, the first
937 * X-CACHE-MISS entry should tell us who.
939 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%s %d", name
, xerrno
);
943 * If error page auto-negotiate is enabled in any way, send the Vary.
944 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
945 * We have even better reasons though:
946 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
948 if (!Config
.errorDirectory
) {
949 /* We 'negotiated' this ONLY from the Accept-Language. */
950 rep
->header
.delById(HDR_VARY
);
951 rep
->header
.putStr(HDR_VARY
, "Accept-Language");
954 /* add the Content-Language header according to RFC section 14.12 */
956 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, err_language
);
958 #endif /* USE_ERROR_LOCALES */
960 /* default templates are in English */
961 /* language is known unless error_directory override used */
962 if (!Config
.errorDirectory
)
963 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, "en");
966 httpBodySet(&rep
->body
, content
);
967 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
974 ErrorState::BuildContent()
976 MemBuf
*content
= new MemBuf
;
977 const char *m
= NULL
;
981 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
988 /** error_directory option in squid.conf overrides translations.
989 * Custom errors are always found either in error_directory or the templates directory.
990 * Otherwise locate the Accept-Language header
992 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
&& request
&& request
->header
.getList(HDR_ACCEPT_LANGUAGE
, &hdr
) ) {
994 size_t pos
= 0; // current parsing position in header string
995 char *reset
= NULL
; // where to reset the p pointer for each new tag file
998 /* prep the directory path string to prevent snprintf ... */
999 l
= strlen(DEFAULT_SQUID_ERROR_DIR
);
1000 memcpy(dir
, DEFAULT_SQUID_ERROR_DIR
, l
);
1002 reset
= dt
= dir
+ l
;
1004 debugs(4, 6, HERE
<< "Testing Header: '" << hdr
<< "'");
1006 while ( pos
< hdr
.size() ) {
1008 /* skip any initial whitespace. */
1009 while (pos
< hdr
.size() && xisspace(hdr
[pos
])) pos
++;
1012 * Header value format:
1013 * - sequence of whitespace delimited tags
1014 * - each tag may suffix with ';'.* which we can ignore.
1015 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
1016 * with preference given to an exact match.
1018 bool invalid_byte
= false;
1019 while (pos
< hdr
.size() && hdr
[pos
] != ';' && hdr
[pos
] != ',' && !xisspace(hdr
[pos
]) && dt
< (dir
+256) ) {
1020 if (!invalid_byte
) {
1021 #if USE_HTTP_VIOLATIONS
1022 // if accepting violations we may as well accept some broken browsers
1023 // which may send us the right code, wrong ISO formatting.
1024 if (hdr
[pos
] == '_')
1028 *dt
= xtolower(hdr
[pos
]);
1029 // valid codes only contain A-Z, hyphen (-) and *
1030 if (*dt
!= '-' && *dt
!= '*' && (*dt
< 'a' || *dt
> 'z') )
1031 invalid_byte
= true;
1033 dt
++; // move to next destination byte.
1037 *dt
++ = '\0'; // nul-terminated the filename content string before system use.
1039 debugs(4, 9, HERE
<< "STATE: dt='" << dt
<< "', reset='" << reset
<< "', pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
1041 /* if we found anything we might use, try it. */
1042 if (*reset
!= '\0' && !invalid_byte
) {
1044 /* wildcard uses the configured default language */
1045 if (reset
[0] == '*' && reset
[1] == '\0') {
1046 debugs(4, 6, HERE
<< "Found language '" << reset
<< "'. Using configured default.");
1047 m
= error_text
[page_id
];
1048 if (!Config
.errorDirectory
)
1049 err_language
= Config
.errorDefaultLanguage
;
1053 debugs(4, 6, HERE
<< "Found language '" << reset
<< "', testing for available template in: '" << dir
<< "'");
1055 m
= errorTryLoadText( err_type_str
[page_id
], dir
, false);
1058 /* store the language we found for the Content-Language reply header */
1059 err_language
= xstrdup(reset
);
1061 } else if (Config
.errorLogMissingLanguages
) {
1062 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << reset
);
1066 if ( (dt
- reset
) == 2) {
1067 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
1068 /* use first result. */
1069 debugs(4,2, HERE
<< "wildcard fallback errors not coded yet.");
1074 dt
= reset
; // reset for next tag testing. we replace the failed name instead of cloning.
1076 // IFF we terminated the tag on whitespace or ';' we need to skip to the next ',' or end of header.
1077 while (pos
< hdr
.size() && hdr
[pos
] != ',') pos
++;
1078 if (hdr
[pos
] == ',') pos
++;
1081 #endif /* USE_ERR_LOCALES */
1084 * If client-specific error templates are not enabled or available.
1085 * fall back to the old style squid.conf settings.
1088 m
= error_text
[page_id
];
1090 if (!Config
.errorDirectory
)
1091 err_language
= Config
.errorDefaultLanguage
;
1093 debugs(4, 2, HERE
<< "No existing error page language negotiated for " << errorPageName(page_id
) << ". Using default error file.");
1099 while ((p
= strchr(m
, '%'))) {
1100 content
->append(m
, p
- m
); /* copy */
1101 t
= Convert(*++p
, false); /* convert */
1102 content
->Printf("%s", t
); /* copy */
1103 m
= p
+ 1; /* advance */
1107 content
->Printf("%s", m
); /* copy tail */
1109 assert((size_t)content
->contentSize() == strlen(content
->content()));