]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/errorpage.cc
3 * $Id: errorpage.cc,v 1.230 2008/02/26 21:49:34 amosjeffries Exp $
5 * DEBUG: section 4 Error Generation
6 * AUTHOR: Duane Wessels
8 * SQUID Web Proxy Cache http://www.squid-cache.org/
9 * ----------------------------------------------------------
11 * Squid is the result of efforts by numerous individuals from
12 * the Internet community; see the CONTRIBUTORS file for full
13 * details. Many organizations have provided support for Squid's
14 * development; see the SPONSORS file for full details. Squid is
15 * Copyrighted (C) 2001 by the Regents of the University of
16 * California; see the COPYRIGHT file for full details. Squid
17 * incorporates software developed and/or copyrighted by other
18 * sources; see the CREDITS file for full details.
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
37 #include "errorpage.h"
38 #include "AuthUserRequest.h"
39 #include "SquidTime.h"
41 #include "HttpReply.h"
42 #include "HttpRequest.h"
43 #include "MemObject.h"
46 #include "URLScheme.h"
50 \defgroup ErrorPageInternal Error Page Internals
53 \section Abstract Abstract:
54 * These routines are used to generate error messages to be
55 * sent to clients. The error type is used to select between
56 * the various message formats. (formats are stored in the
57 * Config.errorDirectory)
61 #ifndef DEFAULT_SQUID_ERROR_DIR
62 /** Where to look for errors if config path fails.
63 \note Please use ./configure --datadir=/path instead of patching
65 #define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
68 /// \ingroup ErrorPageInternal
69 CBDATA_CLASS_INIT(ErrorState
);
73 /// \ingroup ErrorPageInternal
78 } ErrorDynamicPageInfo
;
80 /* local constant and vars */
83 \ingroup ErrorPageInternal
85 \note hard coded error messages are not appended with %S
86 * automagically to give you more control on the format
90 int type
; /* and page_id */
100 "<div id=\"footer\">\n"
101 "Generated %T by %h (%s)\n"
111 /// \ingroup ErrorPageInternal
112 static Vector
<ErrorDynamicPageInfo
*> ErrorDynamicPages
;
114 /* local prototypes */
116 /// \ingroup ErrorPageInternal
117 static const int error_hard_text_count
= sizeof(error_hard_text
) / sizeof(*error_hard_text
);
119 /// \ingroup ErrorPageInternal
120 static char **error_text
= NULL
;
122 /// \ingroup ErrorPageInternal
123 static int error_page_count
= 0;
125 static char *errorTryLoadText(const char *page_name
, const char *dir
, bool silent
= false);
126 static char *errorLoadText(const char *page_name
);
127 static const char *errorFindHardText(err_type type
);
128 static ErrorDynamicPageInfo
*errorDynamicPageInfoCreate(int id
, const char *page_name
);
129 static void errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
);
130 static IOCB errorSendComplete
;
133 /// \ingroup ErrorPageInternal
134 err_type
&operator++ (err_type
&anErr
)
136 int tmp
= (int)anErr
;
137 anErr
= (err_type
)(++tmp
);
141 /// \ingroup ErrorPageInternal
142 int operator - (err_type
const &anErr
, err_type
const &anErr2
)
144 return (int)anErr
- (int)anErr2
;
148 errorInitialize(void)
152 error_page_count
= ERR_MAX
+ ErrorDynamicPages
.size();
153 error_text
= static_cast<char **>(xcalloc(error_page_count
, sizeof(char *)));
155 for (i
= ERR_NONE
, ++i
; i
< error_page_count
; ++i
) {
156 safe_free(error_text
[i
]);
158 if ((text
= errorFindHardText(i
))) {
160 * Index any hard-coded error text into defaults.
162 error_text
[i
] = xstrdup(text
);
164 } else if (i
< ERR_MAX
) {
166 * Index precompiled fixed template files from one of two sources:
167 * (a) default language translation directory (error_default_language)
168 * (b) admin specified custom directory (error_directory)
170 error_text
[i
] = errorLoadText(err_type_str
[i
]);
174 * Index any unknown file names used by deny_info.
176 ErrorDynamicPageInfo
*info
= ErrorDynamicPages
.items
[i
- ERR_MAX
];
177 assert(info
&& info
->id
== i
&& info
->page_name
);
179 if (strchr(info
->page_name
, ':') == NULL
) {
180 /** But only if they are not redirection URL. */
181 error_text
[i
] = errorLoadText(info
->page_name
);
193 for (i
= ERR_NONE
+ 1; i
< error_page_count
; i
++)
194 safe_free(error_text
[i
]);
196 safe_free(error_text
);
199 while (ErrorDynamicPages
.size())
200 errorDynamicPageInfoDestroy(ErrorDynamicPages
.pop_back());
202 error_page_count
= 0;
205 /// \ingroup ErrorPageInternal
207 errorFindHardText(err_type type
)
211 for (i
= 0; i
< error_hard_text_count
; i
++)
212 if (error_hard_text
[i
].type
== type
)
213 return error_hard_text
[i
].text
;
219 * \ingroup ErrorPageInternal
221 * Load into the in-memory error text Index a file probably available at:
222 * (a) admin specified custom directory (error_directory)
223 * (b) default language translation directory (error_default_language)
224 * (c) English sub-directory where errors should ALWAYS exist
227 errorLoadText(const char *page_name
)
231 /** test error_directory configured location */
232 if(Config
.errorDirectory
)
233 text
= errorTryLoadText(page_name
, Config
.errorDirectory
);
236 /** test error_default_language location */
237 if(!text
&& Config
.errorDefaultLanguage
) {
239 snprintf(dir
,256,"%s/%s", DEFAULT_SQUID_ERROR_DIR
, Config
.errorDefaultLanguage
);
240 text
= errorTryLoadText(page_name
, dir
);
242 debugs(1, DBG_CRITICAL
, "Unable to load default error language files. Reset to backups.");
247 /* test default location if failed (templates == English translation base templates) */
249 text
= errorTryLoadText(page_name
, DEFAULT_SQUID_ERROR_DIR
"/templates");
252 /* giving up if failed */
254 fatal("failed to find or read error text file.");
259 /// \ingroup ErrorPageInternal
261 errorTryLoadText(const char *page_name
, const char *dir
, bool silent
)
264 char path
[MAXPATHLEN
];
270 snprintf(path
, sizeof(path
), "%s/%s", dir
, page_name
);
271 fd
= file_open(path
, O_RDONLY
| O_TEXT
);
274 /* with dynamic locale negotiation we may see some failures before a success. */
276 debugs(4, DBG_CRITICAL
, HERE
<< "'" << path
<< "': " << xstrerror());
282 while((len
= FD_READ_METHOD(fd
, buf
, sizeof(buf
))) > 0) {
283 textbuf
.append(buf
, len
);
287 debugs(4, DBG_CRITICAL
, HERE
<< "failed to fully read: '" << path
<< "': " << xstrerror());
292 if (strstr(textbuf
.buf
, "%s") == NULL
)
293 textbuf
.append("%S", 2); /* add signature */
295 /* Shrink memory size down to exact size. MemBuf has a tencendy
296 * to be rather large..
298 text
= xstrdup(textbuf
.buf
);
305 /// \ingroup ErrorPageInternal
306 static ErrorDynamicPageInfo
*
307 errorDynamicPageInfoCreate(int id
, const char *page_name
)
309 ErrorDynamicPageInfo
*info
= new ErrorDynamicPageInfo
;
311 info
->page_name
= xstrdup(page_name
);
315 /// \ingroup ErrorPageInternal
317 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo
* info
)
320 safe_free(info
->page_name
);
324 /// \ingroup ErrorPageInternal
326 errorPageId(const char *page_name
)
328 for (int i
= 0; i
< ERR_MAX
; i
++) {
329 if (strcmp(err_type_str
[i
], page_name
) == 0)
333 for (size_t j
= 0; j
< ErrorDynamicPages
.size(); j
++) {
334 if (strcmp(ErrorDynamicPages
.items
[j
]->page_name
, page_name
) == 0)
342 errorReservePageId(const char *page_name
)
344 ErrorDynamicPageInfo
*info
;
345 int id
= errorPageId(page_name
);
347 if (id
== ERR_NONE
) {
348 info
= errorDynamicPageInfoCreate(ERR_MAX
+ ErrorDynamicPages
.size(), page_name
);
349 ErrorDynamicPages
.push_back(info
);
356 /// \ingroup ErrorPageInternal
358 errorPageName(int pageId
)
360 if (pageId
>= ERR_NONE
&& pageId
< ERR_MAX
) /* common case */
361 return err_type_str
[pageId
];
363 if (pageId
>= ERR_MAX
&& pageId
- ERR_MAX
< (ssize_t
)ErrorDynamicPages
.size())
364 return ErrorDynamicPages
.items
[pageId
- ERR_MAX
]->page_name
;
366 return "ERR_UNKNOWN"; /* should not happen */
370 errorCon(err_type type
, http_status status
, HttpRequest
* request
)
372 ErrorState
*err
= new ErrorState
;
373 err
->page_id
= type
; /* has to be reset manually if needed */
374 err
->err_language
= NULL
;
376 err
->httpStatus
= status
;
378 if (request
!= NULL
) {
379 err
->request
= HTTPMSGLOCK(request
);
380 err
->src_addr
= request
->client_addr
;
387 errorAppendEntry(StoreEntry
* entry
, ErrorState
* err
)
389 assert(entry
->mem_obj
!= NULL
);
390 assert (entry
->isEmpty());
391 debugs(4, 4, "Creating an error page for entry " << entry
<<
392 " with errorstate " << err
<<
393 " page id " << err
->page_id
);
395 if (entry
->store_status
!= STORE_PENDING
) {
396 debugs(4, 2, "Skipping error page due to store_status: " << entry
->store_status
);
398 * If the entry is not STORE_PENDING, then no clients
399 * care about it, and we don't need to generate an
402 assert(EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
403 assert(entry
->mem_obj
->nclients
== 0);
408 if (err
->page_id
== TCP_RESET
) {
410 debugs(4, 2, "RSTing this reply");
411 err
->request
->flags
.setResetTCP();
417 entry
->replaceHttpReply( err
->BuildHttpReply() );
418 EBIT_CLR(entry
->flags
, ENTRY_FWD_HDR_WAIT
);
421 entry
->negativeCache();
422 entry
->releaseRequest();
428 errorSend(int fd
, ErrorState
* err
)
431 debugs(4, 3, "errorSend: FD " << fd
<< ", err=" << err
);
434 * ugh, this is how we make sure error codes get back to
435 * the client side for logging and error tracking.
439 err
->request
->errType
= err
->type
;
441 /* moved in front of errorBuildBuf @?@ */
442 err
->flags
.flag_cbdata
= 1;
444 rep
= err
->BuildHttpReply();
446 comm_write_mbuf(fd
, rep
->pack(), errorSendComplete
, err
);
452 \ingroup ErrorPageAPI
454 * Called by commHandleWrite() after data has been written
455 * to the client socket.
457 \note If there is a callback, the callback is responsible for
458 * closeing the FD, otherwise we do it ourseves.
461 errorSendComplete(int fd
, char *bufnotused
, size_t size
, comm_err_t errflag
, int xerrno
, void *data
)
463 ErrorState
*err
= static_cast<ErrorState
*>(data
);
464 debugs(4, 3, "errorSendComplete: FD " << fd
<< ", size=" << size
);
466 if (errflag
!= COMM_ERR_CLOSING
) {
468 debugs(4, 3, "errorSendComplete: callback");
469 err
->callback(fd
, err
->callback_data
, size
);
472 debugs(4, 3, "errorSendComplete: comm_close");
480 errorStateFree(ErrorState
* err
)
482 HTTPMSGUNLOCK(err
->request
);
483 safe_free(err
->redirect_url
);
485 safe_free(err
->dnsserver_msg
);
486 safe_free(err
->request_hdrs
);
487 wordlistDestroy(&err
->ftp
.server_msg
);
488 safe_free(err
->ftp
.request
);
489 safe_free(err
->ftp
.reply
);
490 AUTHUSERREQUESTUNLOCK(err
->auth_user_request
, "errstate");
491 safe_free(err
->err_msg
);
493 if(err
->err_language
!= Config
.errorDefaultLanguage
)
495 safe_free(err
->err_language
);
500 ErrorState::Dump(MemBuf
* mb
)
503 const char *p
= NULL
; /* takes priority over mb if set */
504 char ntoabuf
[MAX_IPSTRLEN
];
507 /* email subject line */
508 str
.Printf("CacheErrorInfo - %s", errorPageName(type
));
509 mb
->Printf("?subject=%s", rfc1738_escape_part(str
.buf
));
512 str
.Printf("CacheHost: %s\r\n", getMyHostname());
514 str
.Printf("ErrPage: %s\r\n", errorPageName(type
));
517 str
.Printf("Err: (%d) %s\r\n", xerrno
, strerror(xerrno
));
519 str
.Printf("Err: [none]\r\n");
522 if (auth_user_request
->denyMessage())
523 str
.Printf("Auth ErrMsg: %s\r\n", auth_user_request
->denyMessage());
526 str
.Printf("DNS Server ErrMsg: %s\r\n", dnsserver_msg
);
530 str
.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime
));
533 str
.Printf("ClientIP: %s\r\n", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
535 if (request
&& request
->hier
.host
) {
536 str
.Printf("ServerIP: %s\r\n", request
->hier
.host
);
541 str
.Printf("HTTP Request:\r\n");
543 if (NULL
!= request
) {
545 str
.Printf("%s %s HTTP/%d.%d\n",
546 RequestMethodStr(request
->method
),
547 request
->urlpath
.size() ? request
->urlpath
.buf() : "/",
548 request
->http_ver
.major
, request
->http_ver
.minor
);
549 packerToMemInit(&p
, &str
);
550 request
->header
.packInto(&p
);
552 } else if (request_hdrs
) {
562 str
.Printf("FTP Request: %s\r\n", ftp
.request
);
563 str
.Printf("FTP Reply: %s\r\n", ftp
.reply
);
564 str
.Printf("FTP Msg: ");
565 wordlistCat(ftp
.server_msg
, &str
);
570 mb
->Printf("&body=%s", rfc1738_escape_part(str
.buf
));
575 /// \ingroup ErrorPageInternal
576 #define CVT_BUF_SZ 512
579 ErrorState::Convert(char token
)
582 const char *p
= NULL
; /* takes priority over mb if set */
584 char ntoabuf
[MAX_IPSTRLEN
];
592 if (request
&& request
->auth_user_request
)
593 p
= request
->auth_user_request
->username();
601 p
= request
? ftpUrlWith2f(request
) : "[no URL]";
606 p
= errorPageName(type
);
611 mb
.Printf("%d", xerrno
);
618 mb
.Printf("(%d) %s", xerrno
, strerror(xerrno
));
620 mb
.Printf("[No Error]");
625 /* FTP REQUEST LINE */
643 /* FTP SERVER MESSAGE */
644 wordlistCat(ftp
.server_msg
, &mb
);
649 mb
.Printf("%s", getMyHostname());
655 if (request
->hier
.host
)
656 p
= request
->hier
.host
;
658 p
= request
->GetHost();
660 p
= "[unknown host]";
665 mb
.Printf("%s", src_addr
.NtoA(ntoabuf
,MAX_IPSTRLEN
));
670 if (request
&& request
->hier
.host
) {
671 mb
.Printf("%s", request
->hier
.host
);
678 if (Config
.errHtmlText
) {
679 mb
.Printf("%s", Config
.errHtmlText
);
682 p
= "[not available]";
687 p
= auth_user_request
->denyMessage("[not available]");
692 p
= request
? RequestMethodStr(request
->method
) : "[unknown method]";
697 p
= external_acl_message
? external_acl_message
: "[not available]";
703 mb
.Printf("%d", (int) request
->port
);
705 p
= "[unknown port]";
711 p
= request
? ProtocolStr
[request
->protocol
] : "[unknown protocol]";
716 if (NULL
!= request
) {
718 mb
.Printf("%s %s HTTP/%d.%d\n",
719 RequestMethodStr(request
->method
),
720 request
->urlpath
.size() ? request
->urlpath
.buf() : "/",
721 request
->http_ver
.major
, request
->http_ver
.minor
);
722 packerToMemInit(&p
, &mb
);
723 request
->header
.packInto(&p
);
725 } else if (request_hdrs
) {
734 p
= visible_appname_string
;
738 /* signature may contain %-escapes, recursion */
740 if (page_id
!= ERR_SQUID_SIGNATURE
) {
741 const int saved_id
= page_id
;
742 page_id
= ERR_SQUID_SIGNATURE
;
743 MemBuf
*sign_mb
= BuildContent();
744 mb
.Printf("%s", sign_mb
->content());
750 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
757 mb
.Printf("%s", mkhttpdlogtime(&squid_curtime
));
761 mb
.Printf("%s", mkrfc1123(squid_curtime
));
765 p
= request
? urlCanonicalClean(request
) : url
? url
: "[no URL]";
769 p
= request
? urlCanonical(request
) : url
? url
: "[no URL]";
774 if (Config
.adminEmail
)
775 mb
.Printf("%s", Config
.adminEmail
);
782 if (Config
.adminEmail
&& Config
.onoff
.emailErrData
)
809 mb
.Printf("%%%c", token
);
817 p
= mb
.buf
; /* do not use mb after this assignment! */
821 debugs(4, 3, "errorConvert: %%" << token
<< " --> '" << p
<< "'" );
830 ErrorState::BuildHttpReply()
832 HttpReply
*rep
= new HttpReply
;
833 const char *name
= errorPageName(page_id
);
834 /* no LMT for error pages; error pages expire immediately */
835 HttpVersion
version(1, 0);
837 if (strchr(name
, ':')) {
839 rep
->setHeaders(version
, HTTP_MOVED_TEMPORARILY
, NULL
, "text/html", 0, 0, squid_curtime
);
842 char *quoted_url
= rfc1738_escape_part(urlCanonical(request
));
843 httpHeaderPutStrf(&rep
->header
, HDR_LOCATION
, name
, quoted_url
);
846 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%d %s", httpStatus
, "Access Denied");
848 MemBuf
*content
= BuildContent();
849 rep
->setHeaders(version
, httpStatus
, NULL
, "text/html", content
->contentSize(), 0, squid_curtime
);
851 * include some information for downstream caches. Implicit
852 * replaceable content. This isn't quite sufficient. xerrno is not
853 * necessarily meaningful to another system, so we really should
854 * expand it. Additionally, we should identify ourselves. Someone
855 * might want to know. Someone _will_ want to know OTOH, the first
856 * X-CACHE-MISS entry should tell us who.
858 httpHeaderPutStrf(&rep
->header
, HDR_X_SQUID_ERROR
, "%s %d", name
, xerrno
);
862 * If error page auto-negotiate is enabled in any way, send the Vary.
863 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
864 * We have even better reasons though:
865 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
867 if(!Config
.errorDirectory
) {
868 /* We 'negotiated' this ONLY from the Accept-Language. */
869 httpHeaderDelById(&rep
->header
, HDR_VARY
);
870 httpHeaderPutStrf(&rep
->header
, HDR_VARY
, "Accept-Language");
873 /* add the Content-Language header according to RFC section 14.12 */
875 httpHeaderPutStrf(&rep
->header
, HDR_CONTENT_LANGUAGE
, "%s", err_language
);
878 #endif /* USE_ERROR_LOCALES */
880 /* default templates are in English */
881 /* language is known unless error_directory override used */
882 if(!Config
.errorDirectory
)
883 httpHeaderPutStrf(&rep
->header
, HDR_CONTENT_LANGUAGE
, "en");
886 httpBodySet(&rep
->body
, content
);
887 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
894 ErrorState::BuildContent()
896 MemBuf
*content
= new MemBuf
;
897 const char *m
= NULL
;
901 assert(page_id
> ERR_NONE
&& page_id
< error_page_count
);
908 /** error_directory option in squid.conf overrides translations.
909 * Otherwise locate the Accept-Language header
911 if(!Config
.errorDirectory
&& request
->header
.getList(HDR_ACCEPT_LANGUAGE
, &hdr
) ) {
913 const char *buf
= hdr
.buf(); // raw header string for parsing
914 int pos
= 0; // current parsing position in header string
915 char *reset
= NULL
; // where to reset the p pointer for each new tag file
918 /* prep the directory path string to prevent snprintf ... */
919 l
= strlen(DEFAULT_SQUID_ERROR_DIR
);
920 memcpy(dir
, DEFAULT_SQUID_ERROR_DIR
, l
);
922 reset
= dt
= dir
+ l
;
924 debugs(4, 6, HERE
<< "Testing Header: '" << hdr
<< "'");
926 while( pos
< hdr
.size() ) {
929 * Header value format:
930 * - sequence of whitespace delimited tags
931 * - each tag may suffix with ';'.* which we can ignore.
932 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
933 * with preference given to an exact match.
935 while(pos
< hdr
.size() && buf
[pos
] != ';' && buf
[pos
] != ',' && !xisspace(buf
[pos
]) && dt
< (dir
+256) ) {
936 *dt
++ = xtolower(buf
[pos
++]);
938 *dt
++ = '\0'; // nul-terminated the filename content string before system use.
940 debugs(4, 9, HERE
<< "STATE: dt='" << dt
<< "', reset='" << reset
<< "', reset[1]='" << reset
[1] << "', pos=" << pos
<< ", buf='" << &buf
[pos
] << "'");
942 /* if we found anything we might use, try it. */
945 debugs(4, 6, HERE
<< "Found language '" << reset
<< "', testing for available template in: '" << dir
<< "'");
946 m
= errorTryLoadText( err_type_str
[page_id
], dir
, false);
949 /* store the language we found for the Content-Language reply header */
950 err_language
= xstrdup(reset
);
955 if( (dt
- reset
) == 2) {
956 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
957 /* use first result. */
958 debugs(4,2, HERE
<< "wildcard fallback errors not coded yet.");
963 dt
= reset
; // reset for next tag testing. we replace the failed name instead of cloning.
965 // IFF we terminated the tag on ';' we need to skip the 'q=' bit to the next ',' or end.
966 while(pos
< hdr
.size() && buf
[pos
] != ',') pos
++;
967 if(buf
[pos
] == ',') pos
++;
970 #endif /* USE_ERR_LOCALES */
973 * If client-specific error templates are not enabled or available.
974 * fall back to the old style squid.conf settings.
977 m
= error_text
[page_id
];
978 debugs(4, 2, HERE
<< "No existing error page language negotiated for " << page_id
<< ". Using default error file.");
980 if(!Config
.errorDirectory
)
981 err_language
= Config
.errorDefaultLanguage
;
988 while ((p
= strchr(m
, '%'))) {
989 content
->append(m
, p
- m
); /* copy */
990 t
= Convert(*++p
); /* convert */
991 content
->Printf("%s", t
); /* copy */
992 m
= p
+ 1; /* advance */
996 content
->Printf("%s", m
); /* copy tail */
998 assert((size_t)content
->contentSize() == strlen(content
->content()));