]>
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.
35 #include "auth/UserRequest.h"
36 #include "comm/Connection.h"
37 #include "comm/Write.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 AsyncCall::Pointer call
= commCbCall(78, 5, "errorSendComplete",
465 CommIoCbPtrFun(&errorSendComplete
, err
));
466 Comm::Write(conn
, mb
, call
);
472 \ingroup ErrorPageAPI
474 * Called by commHandleWrite() after data has been written
475 * to the client socket.
477 \note If there is a callback, the callback is responsible for
478 * closing the FD, otherwise we do it ourselves.
481 errorSendComplete(const Comm::ConnectionPointer
&conn
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
483 ErrorState
*err
= static_cast<ErrorState
*>(data
);
484 debugs(4, 3, HERE
<< conn
<< ", size=" << size
);
486 if (errflag
!= COMM_ERR_CLOSING
) {
488 debugs(4, 3, "errorSendComplete: callback");
489 err
->callback(conn
->fd
, err
->callback_data
, size
);
491 debugs(4, 3, "errorSendComplete: comm_close");
500 errorStateFree(ErrorState
* err
)
502 HTTPMSGUNLOCK(err
->request
);
503 safe_free(err
->redirect_url
);
505 safe_free(err
->request_hdrs
);
506 wordlistDestroy(&err
->ftp
.server_msg
);
507 safe_free(err
->ftp
.request
);
508 safe_free(err
->ftp
.reply
);
509 err
->auth_user_request
= NULL
;
510 safe_free(err
->err_msg
);
512 if (err
->err_language
!= Config
.errorDefaultLanguage
)
514 safe_free(err
->err_language
);
519 ErrorState::Dump(MemBuf
* mb
)
522 const char *p
= NULL
; /* takes priority over mb if set */
523 char ntoabuf
[MAX_IPSTRLEN
];
526 /* email subject line */
527 str
.Printf("CacheErrorInfo - %s", errorPageName(type
));
528 mb
->Printf("?subject=%s", rfc1738_escape_part(str
.buf
));
531 str
.Printf("CacheHost: %s\r\n", getMyHostname());
533 str
.Printf("ErrPage: %s\r\n", errorPageName(type
));
536 str
.Printf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
538 str
.Printf("Err: [none]\r\n");
541 if (auth_user_request
->denyMessage())
542 str
.Printf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
544 if (dnsError
.size() > 0)
545 str
.Printf("DNS ErrMsg: %s\r\n", dnsError
.termedBuf());
548 str
.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
551 str
.Printf("ClientIP: %s\r\n", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
553 if (request
&& request
->hier
.host
[0] != '\0') {
554 str
.Printf("ServerIP: %s\r\n", request
->hier
.host
);
559 str
.Printf("HTTP Request:\r\n");
561 if (NULL
!= request
) {
563 String urlpath_or_slash
;
565 if (request
->urlpath
.size() != 0)
566 urlpath_or_slash
= request
->urlpath
;
568 urlpath_or_slash
= "/";
570 str
.Printf("%s " SQUIDSTRINGPH
" HTTP/%d.%d\n",
571 RequestMethodStr(request
->method
),
572 SQUIDSTRINGPRINT(urlpath_or_slash
),
573 request
->http_ver
.major
, request
->http_ver
.minor
);
574 packerToMemInit(&pck
, &str
);
575 request
->header
.packInto(&pck
);
577 } else if (request_hdrs
) {
587 str
.Printf("FTP Request: %s\r\n", ftp
.request
);
588 str
.Printf("FTP Reply: %s\r\n", ftp
.reply
);
589 str
.Printf("FTP Msg: ");
590 wordlistCat(ftp
.server_msg
, &str
);
595 mb
->Printf("&body=%s", rfc1738_escape_part(str
.buf
));
600 /// \ingroup ErrorPageInternal
601 #define CVT_BUF_SZ 512
604 ErrorState::Convert(char token
, bool building_deny_info_url
)
607 const char *p
= NULL
; /* takes priority over mb if set */
609 int no_urlescape
= 0; /* if true then item is NOT to be further URL-encoded */
610 char ntoabuf
[MAX_IPSTRLEN
];
617 if (request
&& request
->auth_user_request
!= NULL
)
618 p
= request
->auth_user_request
->username();
624 if (building_deny_info_url
) break;
625 p
= request
? ftpUrlWith2f(request
) : "[no URL]";
629 if (building_deny_info_url
) break;
630 p
= errorPageName(type
);
634 mb
.Printf("%d", xerrno
);
639 mb
.Printf("(%d) %s", xerrno
, strerror(xerrno
));
641 mb
.Printf("[No Error]");
645 if (building_deny_info_url
) break;
646 /* FTP REQUEST LINE */
654 if (building_deny_info_url
) break;
663 if (building_deny_info_url
) break;
664 /* FTP SERVER MESSAGE */
666 wordlistCat(ftp
.server_msg
, &mb
);
667 else if (ftp
.listing
) {
668 mb
.append(ftp
.listing
->content(), ftp
.listing
->contentSize());
674 mb
.Printf("%s", getMyHostname());
679 if (request
->hier
.host
[0] != '\0') // if non-empty string.
680 p
= request
->hier
.host
;
682 p
= request
->GetHost();
683 } else if (!building_deny_info_url
)
684 p
= "[unknown host]";
688 mb
.Printf("%s", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
692 if (request
&& request
->hier
.host
[0] != '\0') // if non-empty string
693 mb
.Printf("%s", request
->hier
.host
);
694 else if (!building_deny_info_url
)
699 if (building_deny_info_url
) break;
700 mb
.append(error_stylesheet
.content(), error_stylesheet
.contentSize());
705 if (building_deny_info_url
) break;
706 if (Config
.errHtmlText
) {
707 mb
.Printf("%s", Config
.errHtmlText
);
710 p
= "[not available]";
714 if (building_deny_info_url
) break;
715 p
= auth_user_request
->denyMessage("[not available]");
720 p
= RequestMethodStr(request
->method
);
721 else if (!building_deny_info_url
)
722 p
= "[unknown method]";
726 p
= request
? request
->extacl_message
.termedBuf() : external_acl_message
;
727 if (!p
&& !building_deny_info_url
)
728 p
= "[not available]";
733 mb
.Printf("%d", (int) request
->port
);
734 } else if (!building_deny_info_url
) {
735 p
= "[unknown port]";
741 p
= ProtocolStr
[request
->protocol
];
742 } else if (!building_deny_info_url
) {
743 p
= "[unknown protocol]";
748 if (building_deny_info_url
) {
749 p
= (request
->urlpath
.size() != 0 ? request
->urlpath
.termedBuf() : "/");
752 if (NULL
!= request
) {
754 String urlpath_or_slash
;
756 if (request
->urlpath
.size() != 0)
757 urlpath_or_slash
= request
->urlpath
;
759 urlpath_or_slash
= "/";
761 mb
.Printf("%s " SQUIDSTRINGPH
" HTTP/%d.%d\n",
762 RequestMethodStr(request
->method
),
763 SQUIDSTRINGPRINT(urlpath_or_slash
),
764 request
->http_ver
.major
, request
->http_ver
.minor
);
765 packerToMemInit(&pck
, &mb
);
766 request
->header
.packInto(&pck
);
768 } else if (request_hdrs
) {
776 /* for backward compat we make %s show the full URL. Drop this in some future release. */
777 if (building_deny_info_url
) {
778 p
= request
? urlCanonical(request
) : url
;
779 debugs(0,0, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
781 p
= visible_appname_string
;
785 if (building_deny_info_url
) {
786 p
= visible_appname_string
;
789 /* signature may contain %-escapes, recursion */
790 if (page_id
!= ERR_SQUID_SIGNATURE
) {
791 const int saved_id
= page_id
;
792 page_id
= ERR_SQUID_SIGNATURE
;
793 MemBuf
*sign_mb
= BuildContent();
794 mb
.Printf("%s", sign_mb
->content());
800 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
806 mb
.Printf("%s", mkhttpdlogtime(&squid_curtime
));
810 mb
.Printf("%s", mkrfc1123(squid_curtime
));
814 /* Using the fake-https version of canonical so error pages see https:// */
815 /* even when the url-path cannot be shown as more than '*' */
817 p
= urlCanonicalFakeHttps(request
);
820 else if (!building_deny_info_url
)
826 p
= urlCanonical(request
);
829 else if (!building_deny_info_url
)
834 if (Config
.adminEmail
)
835 mb
.Printf("%s", Config
.adminEmail
);
836 else if (!building_deny_info_url
)
841 if (building_deny_info_url
) break;
842 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
848 if (building_deny_info_url
) break;
849 if (dnsError
.size() > 0)
850 p
= dnsError
.termedBuf();
851 else if (ftp
.cwd_msg
)
858 if (building_deny_info_url
) break;
870 mb
.Printf("%%%c", token
);
876 p
= mb
.buf
; /* do not use mb after this assignment! */
880 debugs(4, 3, "errorConvert: %%" << token
<< " --> '" << p
<< "'" );
885 if (building_deny_info_url
&& !no_urlescape
)
886 p
= rfc1738_escape_part(p
);
892 ErrorState::DenyInfoLocation(const char *name
, HttpRequest
*aRequest
, MemBuf
&result
)
894 char const *m
= name
;
898 while ((p
= strchr(m
, '%'))) {
899 result
.append(m
, p
- m
); /* copy */
900 t
= Convert(*++p
, true); /* convert */
901 result
.Printf("%s", t
); /* copy */
902 m
= p
+ 1; /* advance */
906 result
.Printf("%s", m
); /* copy tail */
908 assert((size_t)result
.contentSize() == strlen(result
.content()));
912 ErrorState::BuildHttpReply()
914 HttpReply
*rep
= new HttpReply
;
915 const char *name
= errorPageName(page_id
);
916 /* no LMT for error pages; error pages expire immediately */
918 if (strchr(name
, ':')) {
920 rep
->setHeaders(HTTP_MOVED_TEMPORARILY
, NULL
, "text/html", 0, 0, -1);
923 MemBuf redirect_location
;
924 redirect_location
.init();
925 DenyInfoLocation(name
, request
, redirect_location
);
926 httpHeaderPutStrf(&rep
->header
, HDR_LOCATION
, "%s", redirect_location
.content() );
929 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
931 MemBuf
*content
= BuildContent();
932 rep
->setHeaders(httpStatus
, NULL
, "text/html", content
->contentSize(), 0, -1);
934 * include some information for downstream caches. Implicit
935 * replaceable content. This isn't quite sufficient. xerrno is not
936 * necessarily meaningful to another system, so we really should
937 * expand it. Additionally, we should identify ourselves. Someone
938 * might want to know. Someone _will_ want to know OTOH, the first
939 * X-CACHE-MISS entry should tell us who.
941 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%s %d", name
, xerrno
);
945 * If error page auto-negotiate is enabled in any way, send the Vary.
946 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
947 * We have even better reasons though:
948 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
950 if (!Config
.errorDirectory
) {
951 /* We 'negotiated' this ONLY from the Accept-Language. */
952 rep
->header
.delById(HDR_VARY
);
953 rep
->header
.putStr(HDR_VARY
, "Accept-Language");
956 /* add the Content-Language header according to RFC section 14.12 */
958 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, err_language
);
960 #endif /* USE_ERROR_LOCALES */
962 /* default templates are in English */
963 /* language is known unless error_directory override used */
964 if (!Config
.errorDirectory
)
965 rep
->header
.putStr(HDR_CONTENT_LANGUAGE
, "en");
968 httpBodySet(&rep
->body
, content
);
969 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
976 ErrorState::BuildContent()
978 MemBuf
*content
= new MemBuf
;
979 const char *m
= NULL
;
983 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
990 /** error_directory option in squid.conf overrides translations.
991 * Custom errors are always found either in error_directory or the templates directory.
992 * Otherwise locate the Accept-Language header
994 if (!Config
.errorDirectory
&& page_id
< ERR_MAX
&& request
&& request
->header
.getList(HDR_ACCEPT_LANGUAGE
, &hdr
) ) {
996 size_t pos
= 0; // current parsing position in header string
997 char *reset
= NULL
; // where to reset the p pointer for each new tag file
1000 /* prep the directory path string to prevent snprintf ... */
1001 l
= strlen(DEFAULT_SQUID_ERROR_DIR
);
1002 memcpy(dir
, DEFAULT_SQUID_ERROR_DIR
, l
);
1004 reset
= dt
= dir
+ l
;
1006 debugs(4, 6, HERE
<< "Testing Header: '" << hdr
<< "'");
1008 while ( pos
< hdr
.size() ) {
1010 /* skip any initial whitespace. */
1011 while (pos
< hdr
.size() && xisspace(hdr
[pos
])) pos
++;
1014 * Header value format:
1015 * - sequence of whitespace delimited tags
1016 * - each tag may suffix with ';'.* which we can ignore.
1017 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
1018 * with preference given to an exact match.
1020 bool invalid_byte
= false;
1021 while (pos
< hdr
.size() && hdr
[pos
] != ';' && hdr
[pos
] != ',' && !xisspace(hdr
[pos
]) && dt
< (dir
+256) ) {
1022 if (!invalid_byte
) {
1023 #if USE_HTTP_VIOLATIONS
1024 // if accepting violations we may as well accept some broken browsers
1025 // which may send us the right code, wrong ISO formatting.
1026 if (hdr
[pos
] == '_')
1030 *dt
= xtolower(hdr
[pos
]);
1031 // valid codes only contain A-Z, hyphen (-) and *
1032 if (*dt
!= '-' && *dt
!= '*' && (*dt
< 'a' || *dt
> 'z') )
1033 invalid_byte
= true;
1035 dt
++; // move to next destination byte.
1039 *dt
++ = '\0'; // nul-terminated the filename content string before system use.
1041 debugs(4, 9, HERE
<< "STATE: dt='" << dt
<< "', reset='" << reset
<< "', pos=" << pos
<< ", buf='" << ((pos
< hdr
.size()) ? hdr
.substr(pos
,hdr
.size()) : "") << "'");
1043 /* if we found anything we might use, try it. */
1044 if (*reset
!= '\0' && !invalid_byte
) {
1046 /* wildcard uses the configured default language */
1047 if (reset
[0] == '*' && reset
[1] == '\0') {
1048 debugs(4, 6, HERE
<< "Found language '" << reset
<< "'. Using configured default.");
1049 m
= error_text
[page_id
];
1050 if (!Config
.errorDirectory
)
1051 err_language
= Config
.errorDefaultLanguage
;
1055 debugs(4, 6, HERE
<< "Found language '" << reset
<< "', testing for available template in: '" << dir
<< "'");
1057 m
= errorTryLoadText( err_type_str
[page_id
], dir
, false);
1060 /* store the language we found for the Content-Language reply header */
1061 err_language
= xstrdup(reset
);
1063 } else if (Config
.errorLogMissingLanguages
) {
1064 debugs(4, DBG_IMPORTANT
, "WARNING: Error Pages Missing Language: " << reset
);
1068 if ( (dt
- reset
) == 2) {
1069 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
1070 /* use first result. */
1071 debugs(4,2, HERE
<< "wildcard fallback errors not coded yet.");
1076 dt
= reset
; // reset for next tag testing. we replace the failed name instead of cloning.
1078 // IFF we terminated the tag on whitespace or ';' we need to skip to the next ',' or end of header.
1079 while (pos
< hdr
.size() && hdr
[pos
] != ',') pos
++;
1080 if (hdr
[pos
] == ',') pos
++;
1083 #endif /* USE_ERR_LOCALES */
1086 * If client-specific error templates are not enabled or available.
1087 * fall back to the old style squid.conf settings.
1090 m
= error_text
[page_id
];
1092 if (!Config
.errorDirectory
)
1093 err_language
= Config
.errorDefaultLanguage
;
1095 debugs(4, 2, HERE
<< "No existing error page language negotiated for " << errorPageName(page_id
) << ". Using default error file.");
1101 while ((p
= strchr(m
, '%'))) {
1102 content
->append(m
, p
- m
); /* copy */
1103 t
= Convert(*++p
, false); /* convert */
1104 content
->Printf("%s", t
); /* copy */
1105 m
= p
+ 1; /* advance */
1109 content
->Printf("%s", m
); /* copy tail */
1111 assert((size_t)content
->contentSize() == strlen(content
->content()));