]> git.ipfire.org Git - thirdparty/squid.git/blob - src/errorpage.cc
Merged from trunk
[thirdparty/squid.git] / src / errorpage.cc
1 /*
2 * DEBUG: section 04 Error Generation
3 * AUTHOR: Duane Wessels
4 *
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
7 *
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
16 *
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
21 *
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
30 *
31 */
32 #include "squid.h"
33 #include "cache_cf.h"
34 #include "comm/Connection.h"
35 #include "comm/Write.h"
36 #include "disk.h"
37 #include "err_detail_type.h"
38 #include "errorpage.h"
39 #include "fde.h"
40 #include "ftp.h"
41 #include "html_quote.h"
42 #include "HttpHeaderTools.h"
43 #include "HttpReply.h"
44 #include "HttpRequest.h"
45 #include "MemBuf.h"
46 #include "MemObject.h"
47 #include "rfc1738.h"
48 #include "SquidConfig.h"
49 #include "Store.h"
50 #include "tools.h"
51 #include "URL.h"
52 #include "URL.h"
53 #include "URLScheme.h"
54 #include "wordlist.h"
55 #if USE_AUTH
56 #include "auth/UserRequest.h"
57 #endif
58 #include "SquidTime.h"
59 #if USE_SSL
60 #include "ssl/ErrorDetailManager.h"
61 #endif
62
63 /**
64 \defgroup ErrorPageInternal Error Page Internals
65 \ingroup ErrorPageAPI
66 *
67 \section Abstract Abstract:
68 * These routines are used to generate error messages to be
69 * sent to clients. The error type is used to select between
70 * the various message formats. (formats are stored in the
71 * Config.errorDirectory)
72 */
73
74 #if !defined(DEFAULT_SQUID_ERROR_DIR)
75 /** Where to look for errors if config path fails.
76 \note Please use ./configure --datadir=/path instead of patching
77 */
78 #define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
79 #endif
80
81 /// \ingroup ErrorPageInternal
82 CBDATA_CLASS_INIT(ErrorState);
83
84 /* local types */
85
86 /// \ingroup ErrorPageInternal
87 typedef struct {
88 int id;
89 char *page_name;
90 Http::StatusCode page_redirect;
91 } ErrorDynamicPageInfo;
92
93 /* local constant and vars */
94
95 /**
96 \ingroup ErrorPageInternal
97 *
98 \note hard coded error messages are not appended with %S
99 * automagically to give you more control on the format
100 */
101 static const struct {
102 int type; /* and page_id */
103 const char *text;
104 }
105
106 error_hard_text[] = {
107
108 {
109 ERR_SQUID_SIGNATURE,
110 "\n<br>\n"
111 "<hr>\n"
112 "<div id=\"footer\">\n"
113 "Generated %T by %h (%s)\n"
114 "</div>\n"
115 "</body></html>\n"
116 },
117 {
118 TCP_RESET,
119 "reset"
120 }
121 };
122
123 /// \ingroup ErrorPageInternal
124 static Vector<ErrorDynamicPageInfo *> ErrorDynamicPages;
125
126 /* local prototypes */
127
128 /// \ingroup ErrorPageInternal
129 static const int error_hard_text_count = sizeof(error_hard_text) / sizeof(*error_hard_text);
130
131 /// \ingroup ErrorPageInternal
132 static char **error_text = NULL;
133
134 /// \ingroup ErrorPageInternal
135 static int error_page_count = 0;
136
137 /// \ingroup ErrorPageInternal
138 static MemBuf error_stylesheet;
139
140 static const char *errorFindHardText(err_type type);
141 static ErrorDynamicPageInfo *errorDynamicPageInfoCreate(int id, const char *page_name);
142 static void errorDynamicPageInfoDestroy(ErrorDynamicPageInfo * info);
143 static IOCB errorSendComplete;
144
145 /// \ingroup ErrorPageInternal
146 /// manages an error page template
147 class ErrorPageFile: public TemplateFile
148 {
149 public:
150 ErrorPageFile(const char *name, const err_type code): TemplateFile(name,code) { textBuf.init();}
151
152 /// The template text data read from disk
153 const char *text() { return textBuf.content(); }
154
155 private:
156 /// stores the data read from disk to a local buffer
157 virtual bool parse(const char *buf, int len, bool eof) {
158 if (len)
159 textBuf.append(buf, len);
160 return true;
161 }
162
163 MemBuf textBuf; ///< A buffer to store the error page
164 };
165
166 /// \ingroup ErrorPageInternal
167 err_type &operator++ (err_type &anErr)
168 {
169 int tmp = (int)anErr;
170 anErr = (err_type)(++tmp);
171 return anErr;
172 }
173
174 /// \ingroup ErrorPageInternal
175 int operator - (err_type const &anErr, err_type const &anErr2)
176 {
177 return (int)anErr - (int)anErr2;
178 }
179
180 void
181 errorInitialize(void)
182 {
183 err_type i;
184 const char *text;
185 error_page_count = ERR_MAX + ErrorDynamicPages.size();
186 error_text = static_cast<char **>(xcalloc(error_page_count, sizeof(char *)));
187
188 for (i = ERR_NONE, ++i; i < error_page_count; ++i) {
189 safe_free(error_text[i]);
190
191 if ((text = errorFindHardText(i))) {
192 /**\par
193 * Index any hard-coded error text into defaults.
194 */
195 error_text[i] = xstrdup(text);
196
197 } else if (i < ERR_MAX) {
198 /**\par
199 * Index precompiled fixed template files from one of two sources:
200 * (a) default language translation directory (error_default_language)
201 * (b) admin specified custom directory (error_directory)
202 */
203 ErrorPageFile errTmpl(err_type_str[i], i);
204 error_text[i] = errTmpl.loadDefault() ? xstrdup(errTmpl.text()) : NULL;
205 } else {
206 /** \par
207 * Index any unknown file names used by deny_info.
208 */
209 ErrorDynamicPageInfo *info = ErrorDynamicPages[i - ERR_MAX];
210 assert(info && info->id == i && info->page_name);
211
212 const char *pg = info->page_name;
213 if (info->page_redirect != Http::scNone)
214 pg = info->page_name +4;
215
216 if (strchr(pg, ':') == NULL) {
217 /** But only if they are not redirection URL. */
218 ErrorPageFile errTmpl(pg, ERR_MAX);
219 error_text[i] = errTmpl.loadDefault() ? xstrdup(errTmpl.text()) : NULL;
220 }
221 }
222 }
223
224 error_stylesheet.reset();
225
226 // look for and load stylesheet into global MemBuf for it.
227 if (Config.errorStylesheet) {
228 ErrorPageFile tmpl("StylesSheet", ERR_MAX);
229 tmpl.loadFromFile(Config.errorStylesheet);
230 error_stylesheet.Printf("%s",tmpl.text());
231 }
232
233 #if USE_SSL
234 Ssl::errorDetailInitialize();
235 #endif
236 }
237
238 void
239 errorClean(void)
240 {
241 if (error_text) {
242 int i;
243
244 for (i = ERR_NONE + 1; i < error_page_count; ++i)
245 safe_free(error_text[i]);
246
247 safe_free(error_text);
248 }
249
250 while (!ErrorDynamicPages.empty()) {
251 errorDynamicPageInfoDestroy(ErrorDynamicPages.back());
252 ErrorDynamicPages.pop_back();
253 }
254
255 error_page_count = 0;
256
257 #if USE_SSL
258 Ssl::errorDetailClean();
259 #endif
260 }
261
262 /// \ingroup ErrorPageInternal
263 static const char *
264 errorFindHardText(err_type type)
265 {
266 int i;
267
268 for (i = 0; i < error_hard_text_count; ++i)
269 if (error_hard_text[i].type == type)
270 return error_hard_text[i].text;
271
272 return NULL;
273 }
274
275 TemplateFile::TemplateFile(const char *name, const err_type code): silent(false), wasLoaded(false), templateName(name), templateCode(code)
276 {
277 assert(name);
278 }
279
280 bool
281 TemplateFile::loadDefault()
282 {
283 if (loaded()) // already loaded?
284 return true;
285
286 /** test error_directory configured location */
287 if (Config.errorDirectory) {
288 char path[MAXPATHLEN];
289 snprintf(path, sizeof(path), "%s/%s", Config.errorDirectory, templateName.termedBuf());
290 loadFromFile(path);
291 }
292
293 #if USE_ERR_LOCALES
294 /** test error_default_language location */
295 if (!loaded() && Config.errorDefaultLanguage) {
296 if (!tryLoadTemplate(Config.errorDefaultLanguage)) {
297 debugs(1, (templateCode < TCP_RESET ? DBG_CRITICAL : 3), "Unable to load default error language files. Reset to backups.");
298 }
299 }
300 #endif
301
302 /* test default location if failed (templates == English translation base templates) */
303 if (!loaded()) {
304 tryLoadTemplate("templates");
305 }
306
307 /* giving up if failed */
308 if (!loaded()) {
309 debugs(1, (templateCode < TCP_RESET ? DBG_CRITICAL : 3), "WARNING: failed to find or read error text file " << templateName);
310 parse("Internal Error: Missing Template ", 33, '\0');
311 parse(templateName.termedBuf(), templateName.size(), '\0');
312 }
313
314 return true;
315 }
316
317 bool
318 TemplateFile::tryLoadTemplate(const char *lang)
319 {
320 assert(lang);
321
322 char path[MAXPATHLEN];
323 /* TODO: prep the directory path string to prevent snprintf ... */
324 snprintf(path, sizeof(path), "%s/%s/%s",
325 DEFAULT_SQUID_ERROR_DIR, lang, templateName.termedBuf());
326 path[MAXPATHLEN-1] = '\0';
327
328 if (loadFromFile(path))
329 return true;
330
331 #if HAVE_GLOB
332 if ( strlen(lang) == 2) {
333 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
334 /* use first result. */
335 debugs(4,2, HERE << "wildcard fallback errors not coded yet.");
336 }
337 #endif
338
339 return false;
340 }
341
342 bool
343 TemplateFile::loadFromFile(const char *path)
344 {
345 int fd;
346 char buf[4096];
347 ssize_t len;
348
349 if (loaded()) // already loaded?
350 return true;
351
352 fd = file_open(path, O_RDONLY | O_TEXT);
353
354 if (fd < 0) {
355 /* with dynamic locale negotiation we may see some failures before a success. */
356 if (!silent && templateCode < TCP_RESET)
357 debugs(4, DBG_CRITICAL, HERE << "'" << path << "': " << xstrerror());
358 wasLoaded = false;
359 return wasLoaded;
360 }
361
362 while ((len = FD_READ_METHOD(fd, buf, sizeof(buf))) > 0) {
363 if (!parse(buf, len, false)) {
364 debugs(4, DBG_CRITICAL, HERE << " parse error while reading template file: " << path);
365 wasLoaded = false;
366 return wasLoaded;
367 }
368 }
369 parse(buf, 0, true);
370
371 if (len < 0) {
372 debugs(4, DBG_CRITICAL, HERE << "failed to fully read: '" << path << "': " << xstrerror());
373 }
374
375 file_close(fd);
376
377 wasLoaded = true;
378 return wasLoaded;
379 }
380
381 bool strHdrAcptLangGetItem(const String &hdr, char *lang, int langLen, size_t &pos)
382 {
383 while (pos < hdr.size()) {
384 char *dt = lang;
385
386 /* skip any initial whitespace. */
387 while (pos < hdr.size() && xisspace(hdr[pos]))
388 ++pos;
389
390 /*
391 * Header value format:
392 * - sequence of whitespace delimited tags
393 * - each tag may suffix with ';'.* which we can ignore.
394 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
395 * with preference given to an exact match.
396 */
397 bool invalid_byte = false;
398 while (pos < hdr.size() && hdr[pos] != ';' && hdr[pos] != ',' && !xisspace(hdr[pos]) && dt < (lang + (langLen -1)) ) {
399 if (!invalid_byte) {
400 #if USE_HTTP_VIOLATIONS
401 // if accepting violations we may as well accept some broken browsers
402 // which may send us the right code, wrong ISO formatting.
403 if (hdr[pos] == '_')
404 *dt = '-';
405 else
406 #endif
407 *dt = xtolower(hdr[pos]);
408 // valid codes only contain A-Z, hyphen (-) and *
409 if (*dt != '-' && *dt != '*' && (*dt < 'a' || *dt > 'z') )
410 invalid_byte = true;
411 else
412 ++dt; // move to next destination byte.
413 }
414 ++pos;
415 }
416 *dt = '\0'; // nul-terminated the filename content string before system use.
417 ++dt;
418
419 // if we terminated the tag on garbage or ';' we need to skip to the next ',' or end of header.
420 while (pos < hdr.size() && hdr[pos] != ',')
421 ++pos;
422
423 if (pos < hdr.size() && hdr[pos] == ',')
424 ++pos;
425
426 debugs(4, 9, HERE << "STATE: dt='" << dt << "', lang='" << lang << "', pos=" << pos << ", buf='" << ((pos < hdr.size()) ? hdr.substr(pos,hdr.size()) : "") << "'");
427
428 /* if we found anything we might use, try it. */
429 if (*lang != '\0' && !invalid_byte)
430 return true;
431 }
432 return false;
433 }
434
435 bool
436 TemplateFile::loadFor(const HttpRequest *request)
437 {
438 String hdr;
439
440 #if USE_ERR_LOCALES
441 if (loaded()) // already loaded?
442 return true;
443
444 if (!request || !request->header.getList(HDR_ACCEPT_LANGUAGE, &hdr) )
445 return false;
446
447 char lang[256];
448 size_t pos = 0; // current parsing position in header string
449
450 debugs(4, 6, HERE << "Testing Header: '" << hdr << "'");
451
452 while ( strHdrAcptLangGetItem(hdr, lang, 256, pos) ) {
453
454 /* wildcard uses the configured default language */
455 if (lang[0] == '*' && lang[1] == '\0') {
456 debugs(4, 6, HERE << "Found language '" << lang << "'. Using configured default.");
457 return false;
458 }
459
460 debugs(4, 6, HERE << "Found language '" << lang << "', testing for available template");
461
462 if (tryLoadTemplate(lang)) {
463 /* store the language we found for the Content-Language reply header */
464 errLanguage = lang;
465 break;
466 } else if (Config.errorLogMissingLanguages) {
467 debugs(4, DBG_IMPORTANT, "WARNING: Error Pages Missing Language: " << lang);
468 }
469 }
470 #endif
471
472 return loaded();
473 }
474
475 /// \ingroup ErrorPageInternal
476 static ErrorDynamicPageInfo *
477 errorDynamicPageInfoCreate(int id, const char *page_name)
478 {
479 ErrorDynamicPageInfo *info = new ErrorDynamicPageInfo;
480 info->id = id;
481 info->page_name = xstrdup(page_name);
482 info->page_redirect = static_cast<Http::StatusCode>(atoi(page_name));
483
484 /* WARNING on redirection status:
485 * 2xx are permitted, but not documented officially.
486 * - might be useful for serving static files (PAC etc) in special cases
487 * 3xx require a URL suitable for Location: header.
488 * - the current design does not allow for a Location: URI as well as a local file template
489 * although this possibility is explicitly permitted in the specs.
490 * 4xx-5xx require a local file template.
491 * - sending Location: on these codes with no body is invalid by the specs.
492 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
493 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
494 */
495 if (info->page_redirect == Http::scNone)
496 ; // special case okay.
497 else if (info->page_redirect < 200 || info->page_redirect > 599) {
498 // out of range
499 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " is not valid on '" << page_name << "'");
500 self_destruct();
501 } else if ( /* >= 200 && */ info->page_redirect < 300 && strchr(&(page_name[4]), ':')) {
502 // 2xx require a local template file
503 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " requires a template on '" << page_name << "'");
504 self_destruct();
505 } else if (info->page_redirect >= 300 && info->page_redirect <= 399 && !strchr(&(page_name[4]), ':')) {
506 // 3xx require an absolute URL
507 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " requires a URL on '" << page_name << "'");
508 self_destruct();
509 } else if (info->page_redirect >= 400 /* && <= 599 */ && strchr(&(page_name[4]), ':')) {
510 // 4xx/5xx require a local template file
511 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " requires a template on '" << page_name << "'");
512 self_destruct();
513 }
514 // else okay.
515
516 return info;
517 }
518
519 /// \ingroup ErrorPageInternal
520 static void
521 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo * info)
522 {
523 assert(info);
524 safe_free(info->page_name);
525 delete info;
526 }
527
528 /// \ingroup ErrorPageInternal
529 static int
530 errorPageId(const char *page_name)
531 {
532 for (int i = 0; i < ERR_MAX; ++i) {
533 if (strcmp(err_type_str[i], page_name) == 0)
534 return i;
535 }
536
537 for (size_t j = 0; j < ErrorDynamicPages.size(); ++j) {
538 if (strcmp(ErrorDynamicPages[j]->page_name, page_name) == 0)
539 return j + ERR_MAX;
540 }
541
542 return ERR_NONE;
543 }
544
545 err_type
546 errorReservePageId(const char *page_name)
547 {
548 ErrorDynamicPageInfo *info;
549 int id = errorPageId(page_name);
550
551 if (id == ERR_NONE) {
552 info = errorDynamicPageInfoCreate(ERR_MAX + ErrorDynamicPages.size(), page_name);
553 ErrorDynamicPages.push_back(info);
554 id = info->id;
555 }
556
557 return (err_type)id;
558 }
559
560 /// \ingroup ErrorPageInternal
561 const char *
562 errorPageName(int pageId)
563 {
564 if (pageId >= ERR_NONE && pageId < ERR_MAX) /* common case */
565 return err_type_str[pageId];
566
567 if (pageId >= ERR_MAX && pageId - ERR_MAX < (ssize_t)ErrorDynamicPages.size())
568 return ErrorDynamicPages[pageId - ERR_MAX]->page_name;
569
570 return "ERR_UNKNOWN"; /* should not happen */
571 }
572
573 ErrorState::ErrorState(err_type t, Http::StatusCode status, HttpRequest * req) :
574 type(t),
575 page_id(t),
576 err_language(NULL),
577 httpStatus(status),
578 #if USE_AUTH
579 auth_user_request (NULL),
580 #endif
581 request(NULL),
582 url(NULL),
583 xerrno(0),
584 port(0),
585 dnsError(),
586 ttl(0),
587 src_addr(),
588 redirect_url(NULL),
589 callback(NULL),
590 callback_data(NULL),
591 request_hdrs(NULL),
592 err_msg(NULL),
593 #if USE_SSL
594 detail(NULL),
595 #endif
596 detailCode(ERR_DETAIL_NONE)
597 {
598 memset(&ftp, 0, sizeof(ftp));
599
600 if (page_id >= ERR_MAX && ErrorDynamicPages[page_id - ERR_MAX]->page_redirect != Http::scNone)
601 httpStatus = ErrorDynamicPages[page_id - ERR_MAX]->page_redirect;
602
603 if (req != NULL) {
604 request = req;
605 HTTPMSGLOCK(request);
606 src_addr = req->client_addr;
607 }
608 }
609
610 void
611 errorAppendEntry(StoreEntry * entry, ErrorState * err)
612 {
613 assert(entry->mem_obj != NULL);
614 assert (entry->isEmpty());
615 debugs(4, 4, "Creating an error page for entry " << entry <<
616 " with errorstate " << err <<
617 " page id " << err->page_id);
618
619 if (entry->store_status != STORE_PENDING) {
620 debugs(4, 2, "Skipping error page due to store_status: " << entry->store_status);
621 /*
622 * If the entry is not STORE_PENDING, then no clients
623 * care about it, and we don't need to generate an
624 * error message
625 */
626 assert(EBIT_TEST(entry->flags, ENTRY_ABORTED));
627 assert(entry->mem_obj->nclients == 0);
628 delete err;
629 return;
630 }
631
632 if (err->page_id == TCP_RESET) {
633 if (err->request) {
634 debugs(4, 2, "RSTing this reply");
635 err->request->flags.resetTcp = true;
636 }
637 }
638
639 entry->lock("errorAppendEntry");
640 entry->buffer();
641 entry->replaceHttpReply( err->BuildHttpReply() );
642 entry->flush();
643 entry->complete();
644 entry->negativeCache();
645 entry->releaseRequest();
646 entry->unlock("errorAppendEntry");
647 delete err;
648 }
649
650 void
651 errorSend(const Comm::ConnectionPointer &conn, ErrorState * err)
652 {
653 HttpReply *rep;
654 debugs(4, 3, HERE << conn << ", err=" << err);
655 assert(Comm::IsConnOpen(conn));
656
657 rep = err->BuildHttpReply();
658
659 MemBuf *mb = rep->pack();
660 AsyncCall::Pointer call = commCbCall(78, 5, "errorSendComplete",
661 CommIoCbPtrFun(&errorSendComplete, err));
662 Comm::Write(conn, mb, call);
663 delete mb;
664
665 delete rep;
666 }
667
668 /**
669 \ingroup ErrorPageAPI
670 *
671 * Called by commHandleWrite() after data has been written
672 * to the client socket.
673 *
674 \note If there is a callback, the callback is responsible for
675 * closing the FD, otherwise we do it ourselves.
676 */
677 static void
678 errorSendComplete(const Comm::ConnectionPointer &conn, char *bufnotused, size_t size, comm_err_t errflag, int xerrno, void *data)
679 {
680 ErrorState *err = static_cast<ErrorState *>(data);
681 debugs(4, 3, HERE << conn << ", size=" << size);
682
683 if (errflag != COMM_ERR_CLOSING) {
684 if (err->callback) {
685 debugs(4, 3, "errorSendComplete: callback");
686 err->callback(conn->fd, err->callback_data, size);
687 } else {
688 debugs(4, 3, "errorSendComplete: comm_close");
689 conn->close();
690 }
691 }
692
693 delete err;
694 }
695
696 ErrorState::~ErrorState()
697 {
698 HTTPMSGUNLOCK(request);
699 safe_free(redirect_url);
700 safe_free(url);
701 safe_free(request_hdrs);
702 wordlistDestroy(&ftp.server_msg);
703 safe_free(ftp.request);
704 safe_free(ftp.reply);
705 #if USE_AUTH
706 auth_user_request = NULL;
707 #endif
708 safe_free(err_msg);
709 #if USE_ERR_LOCALES
710 if (err_language != Config.errorDefaultLanguage)
711 #endif
712 safe_free(err_language);
713 #if USE_SSL
714 delete detail;
715 #endif
716 }
717
718 int
719 ErrorState::Dump(MemBuf * mb)
720 {
721 MemBuf str;
722 char ntoabuf[MAX_IPSTRLEN];
723
724 str.reset();
725 /* email subject line */
726 str.Printf("CacheErrorInfo - %s", errorPageName(type));
727 mb->Printf("?subject=%s", rfc1738_escape_part(str.buf));
728 str.reset();
729 /* email body */
730 str.Printf("CacheHost: %s\r\n", getMyHostname());
731 /* - Err Msgs */
732 str.Printf("ErrPage: %s\r\n", errorPageName(type));
733
734 if (xerrno) {
735 str.Printf("Err: (%d) %s\r\n", xerrno, strerror(xerrno));
736 } else {
737 str.Printf("Err: [none]\r\n");
738 }
739 #if USE_AUTH
740 if (auth_user_request->denyMessage())
741 str.Printf("Auth ErrMsg: %s\r\n", auth_user_request->denyMessage());
742 #endif
743 if (dnsError.size() > 0)
744 str.Printf("DNS ErrMsg: %s\r\n", dnsError.termedBuf());
745
746 /* - TimeStamp */
747 str.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime));
748
749 /* - IP stuff */
750 str.Printf("ClientIP: %s\r\n", src_addr.toStr(ntoabuf,MAX_IPSTRLEN));
751
752 if (request && request->hier.host[0] != '\0') {
753 str.Printf("ServerIP: %s\r\n", request->hier.host);
754 }
755
756 str.Printf("\r\n");
757 /* - HTTP stuff */
758 str.Printf("HTTP Request:\r\n");
759
760 if (NULL != request) {
761 Packer pck;
762 String urlpath_or_slash;
763
764 if (request->urlpath.size() != 0)
765 urlpath_or_slash = request->urlpath;
766 else
767 urlpath_or_slash = "/";
768
769 str.Printf("%s " SQUIDSTRINGPH " %s/%d.%d\n",
770 RequestMethodStr(request->method),
771 SQUIDSTRINGPRINT(urlpath_or_slash),
772 AnyP::ProtocolType_str[request->http_ver.protocol],
773 request->http_ver.major, request->http_ver.minor);
774 packerToMemInit(&pck, &str);
775 request->header.packInto(&pck);
776 packerClean(&pck);
777 }
778
779 str.Printf("\r\n");
780 /* - FTP stuff */
781
782 if (ftp.request) {
783 str.Printf("FTP Request: %s\r\n", ftp.request);
784 str.Printf("FTP Reply: %s\r\n", (ftp.reply? ftp.reply:"[none]"));
785 str.Printf("FTP Msg: ");
786 wordlistCat(ftp.server_msg, &str);
787 str.Printf("\r\n");
788 }
789
790 str.Printf("\r\n");
791 mb->Printf("&body=%s", rfc1738_escape_part(str.buf));
792 str.clean();
793 return 0;
794 }
795
796 /// \ingroup ErrorPageInternal
797 #define CVT_BUF_SZ 512
798
799 const char *
800 ErrorState::Convert(char token, bool building_deny_info_url, bool allowRecursion)
801 {
802 static MemBuf mb;
803 const char *p = NULL; /* takes priority over mb if set */
804 int do_quote = 1;
805 int no_urlescape = 0; /* if true then item is NOT to be further URL-encoded */
806 char ntoabuf[MAX_IPSTRLEN];
807
808 mb.reset();
809
810 switch (token) {
811
812 case 'a':
813 #if USE_AUTH
814 if (request && request->auth_user_request != NULL)
815 p = request->auth_user_request->username();
816 if (!p)
817 #endif
818 p = "-";
819 break;
820
821 case 'b':
822 mb.Printf("%d", getMyPort());
823 break;
824
825 case 'B':
826 if (building_deny_info_url) break;
827 p = request ? ftpUrlWith2f(request) : "[no URL]";
828 break;
829
830 case 'c':
831 if (building_deny_info_url) break;
832 p = errorPageName(type);
833 break;
834
835 case 'D':
836 if (!allowRecursion)
837 p = "%D"; // if recursion is not allowed, do not convert
838 #if USE_SSL
839 // currently only SSL error details implemented
840 else if (detail) {
841 detail->useRequest(request);
842 const String &errDetail = detail->toString();
843 if (errDetail.size() > 0) {
844 MemBuf *detail_mb = ConvertText(errDetail.termedBuf(), false);
845 mb.append(detail_mb->content(), detail_mb->contentSize());
846 delete detail_mb;
847 do_quote = 0;
848 }
849 }
850 #endif
851 if (!mb.contentSize())
852 mb.Printf("[No Error Detail]");
853 break;
854
855 case 'e':
856 mb.Printf("%d", xerrno);
857 break;
858
859 case 'E':
860 if (xerrno)
861 mb.Printf("(%d) %s", xerrno, strerror(xerrno));
862 else
863 mb.Printf("[No Error]");
864 break;
865
866 case 'f':
867 if (building_deny_info_url) break;
868 /* FTP REQUEST LINE */
869 if (ftp.request)
870 p = ftp.request;
871 else
872 p = "nothing";
873 break;
874
875 case 'F':
876 if (building_deny_info_url) break;
877 /* FTP REPLY LINE */
878 if (ftp.reply)
879 p = ftp.reply;
880 else
881 p = "nothing";
882 break;
883
884 case 'g':
885 if (building_deny_info_url) break;
886 /* FTP SERVER RESPONSE */
887 if (ftp.listing) {
888 mb.append(ftp.listing->content(), ftp.listing->contentSize());
889 do_quote = 0;
890 } else if (ftp.server_msg) {
891 wordlistCat(ftp.server_msg, &mb);
892 }
893 break;
894
895 case 'h':
896 mb.Printf("%s", getMyHostname());
897 break;
898
899 case 'H':
900 if (request) {
901 if (request->hier.host[0] != '\0') // if non-empty string.
902 p = request->hier.host;
903 else
904 p = request->GetHost();
905 } else if (!building_deny_info_url)
906 p = "[unknown host]";
907 break;
908
909 case 'i':
910 mb.Printf("%s", src_addr.toStr(ntoabuf,MAX_IPSTRLEN));
911 break;
912
913 case 'I':
914 if (request && request->hier.tcpServer != NULL)
915 p = request->hier.tcpServer->remote.toStr(ntoabuf,MAX_IPSTRLEN);
916 else if (!building_deny_info_url)
917 p = "[unknown]";
918 break;
919
920 case 'l':
921 if (building_deny_info_url) break;
922 mb.append(error_stylesheet.content(), error_stylesheet.contentSize());
923 do_quote = 0;
924 break;
925
926 case 'L':
927 if (building_deny_info_url) break;
928 if (Config.errHtmlText) {
929 mb.Printf("%s", Config.errHtmlText);
930 do_quote = 0;
931 } else
932 p = "[not available]";
933 break;
934
935 case 'm':
936 if (building_deny_info_url) break;
937 #if USE_AUTH
938 p = auth_user_request->denyMessage("[not available]");
939 #else
940 p = "-";
941 #endif
942 break;
943
944 case 'M':
945 if (request)
946 p = RequestMethodStr(request->method);
947 else if (!building_deny_info_url)
948 p= "[unknown method]";
949 break;
950
951 case 'o':
952 p = request ? request->extacl_message.termedBuf() : external_acl_message;
953 if (!p && !building_deny_info_url)
954 p = "[not available]";
955 break;
956
957 case 'p':
958 if (request) {
959 mb.Printf("%d", (int) request->port);
960 } else if (!building_deny_info_url) {
961 p = "[unknown port]";
962 }
963 break;
964
965 case 'P':
966 if (request) {
967 p = AnyP::ProtocolType_str[request->protocol];
968 } else if (!building_deny_info_url) {
969 p = "[unknown protocol]";
970 }
971 break;
972
973 case 'R':
974 if (building_deny_info_url) {
975 p = (request->urlpath.size() != 0 ? request->urlpath.termedBuf() : "/");
976 no_urlescape = 1;
977 break;
978 }
979 if (NULL != request) {
980 Packer pck;
981 String urlpath_or_slash;
982
983 if (request->urlpath.size() != 0)
984 urlpath_or_slash = request->urlpath;
985 else
986 urlpath_or_slash = "/";
987
988 mb.Printf("%s " SQUIDSTRINGPH " %s/%d.%d\n",
989 RequestMethodStr(request->method),
990 SQUIDSTRINGPRINT(urlpath_or_slash),
991 AnyP::ProtocolType_str[request->http_ver.protocol],
992 request->http_ver.major, request->http_ver.minor);
993 packerToMemInit(&pck, &mb);
994 request->header.packInto(&pck, true); //hide authorization data
995 packerClean(&pck);
996 } else if (request_hdrs) {
997 p = request_hdrs;
998 } else {
999 p = "[no request]";
1000 }
1001 break;
1002
1003 case 's':
1004 /* for backward compat we make %s show the full URL. Drop this in some future release. */
1005 if (building_deny_info_url) {
1006 p = request ? urlCanonical(request) : url;
1007 debugs(0, DBG_CRITICAL, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
1008 } else
1009 p = visible_appname_string;
1010 break;
1011
1012 case 'S':
1013 if (building_deny_info_url) {
1014 p = visible_appname_string;
1015 break;
1016 }
1017 /* signature may contain %-escapes, recursion */
1018 if (page_id != ERR_SQUID_SIGNATURE) {
1019 const int saved_id = page_id;
1020 page_id = ERR_SQUID_SIGNATURE;
1021 MemBuf *sign_mb = BuildContent();
1022 mb.Printf("%s", sign_mb->content());
1023 sign_mb->clean();
1024 delete sign_mb;
1025 page_id = saved_id;
1026 do_quote = 0;
1027 } else {
1028 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1029 p = "[%S]";
1030 }
1031 break;
1032
1033 case 't':
1034 mb.Printf("%s", Time::FormatHttpd(squid_curtime));
1035 break;
1036
1037 case 'T':
1038 mb.Printf("%s", mkrfc1123(squid_curtime));
1039 break;
1040
1041 case 'U':
1042 /* Using the fake-https version of canonical so error pages see https:// */
1043 /* even when the url-path cannot be shown as more than '*' */
1044 if (request)
1045 p = urlCanonicalFakeHttps(request);
1046 else if (url)
1047 p = url;
1048 else if (!building_deny_info_url)
1049 p = "[no URL]";
1050 break;
1051
1052 case 'u':
1053 if (request)
1054 p = urlCanonical(request);
1055 else if (url)
1056 p = url;
1057 else if (!building_deny_info_url)
1058 p = "[no URL]";
1059 break;
1060
1061 case 'w':
1062 if (Config.adminEmail)
1063 mb.Printf("%s", Config.adminEmail);
1064 else if (!building_deny_info_url)
1065 p = "[unknown]";
1066 break;
1067
1068 case 'W':
1069 if (building_deny_info_url) break;
1070 if (Config.adminEmail && Config.onoff.emailErrData)
1071 Dump(&mb);
1072 no_urlescape = 1;
1073 break;
1074
1075 case 'x':
1076 #if USE_SSL
1077 if (detail)
1078 mb.Printf("%s", detail->errorName());
1079 else
1080 #endif
1081 if (!building_deny_info_url)
1082 p = "[Unknown Error Code]";
1083 break;
1084
1085 case 'z':
1086 if (building_deny_info_url) break;
1087 if (dnsError.size() > 0)
1088 p = dnsError.termedBuf();
1089 else if (ftp.cwd_msg)
1090 p = ftp.cwd_msg;
1091 else
1092 p = "[unknown]";
1093 break;
1094
1095 case 'Z':
1096 if (building_deny_info_url) break;
1097 if (err_msg)
1098 p = err_msg;
1099 else
1100 p = "[unknown]";
1101 break;
1102
1103 case '%':
1104 p = "%";
1105 break;
1106
1107 default:
1108 mb.Printf("%%%c", token);
1109 do_quote = 0;
1110 break;
1111 }
1112
1113 if (!p)
1114 p = mb.buf; /* do not use mb after this assignment! */
1115
1116 assert(p);
1117
1118 debugs(4, 3, "errorConvert: %%" << token << " --> '" << p << "'" );
1119
1120 if (do_quote)
1121 p = html_quote(p);
1122
1123 if (building_deny_info_url && !no_urlescape)
1124 p = rfc1738_escape_part(p);
1125
1126 return p;
1127 }
1128
1129 void
1130 ErrorState::DenyInfoLocation(const char *name, HttpRequest *aRequest, MemBuf &result)
1131 {
1132 char const *m = name;
1133 char const *p = m;
1134 char const *t;
1135
1136 if (m[0] == '3')
1137 m += 4; // skip "3xx:"
1138
1139 while ((p = strchr(m, '%'))) {
1140 result.append(m, p - m); /* copy */
1141 t = Convert(*++p, true, true); /* convert */
1142 result.Printf("%s", t); /* copy */
1143 m = p + 1; /* advance */
1144 }
1145
1146 if (*m)
1147 result.Printf("%s", m); /* copy tail */
1148
1149 assert((size_t)result.contentSize() == strlen(result.content()));
1150 }
1151
1152 HttpReply *
1153 ErrorState::BuildHttpReply()
1154 {
1155 HttpReply *rep = new HttpReply;
1156 const char *name = errorPageName(page_id);
1157 /* no LMT for error pages; error pages expire immediately */
1158
1159 if (name[0] == '3' || (name[0] != '2' && name[0] != '4' && name[0] != '5' && strchr(name, ':'))) {
1160 /* Redirection */
1161 Http::StatusCode status = Http::scMovedTemporarily;
1162 // Use configured 3xx reply status if set.
1163 if (name[0] == '3')
1164 status = httpStatus;
1165 else {
1166 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1167 if (request->method != Http::METHOD_GET && request->method != Http::METHOD_HEAD && request->http_ver >= Http::ProtocolVersion(1,1))
1168 status = Http::scTemporaryRedirect;
1169 }
1170
1171 rep->setHeaders(status, NULL, "text/html;charset=utf-8", 0, 0, -1);
1172
1173 if (request) {
1174 MemBuf redirect_location;
1175 redirect_location.init();
1176 DenyInfoLocation(name, request, redirect_location);
1177 httpHeaderPutStrf(&rep->header, HDR_LOCATION, "%s", redirect_location.content() );
1178 }
1179
1180 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%d %s", httpStatus, "Access Denied");
1181 } else {
1182 MemBuf *content = BuildContent();
1183 rep->setHeaders(httpStatus, NULL, "text/html;charset=utf-8", content->contentSize(), 0, -1);
1184 /*
1185 * include some information for downstream caches. Implicit
1186 * replaceable content. This isn't quite sufficient. xerrno is not
1187 * necessarily meaningful to another system, so we really should
1188 * expand it. Additionally, we should identify ourselves. Someone
1189 * might want to know. Someone _will_ want to know OTOH, the first
1190 * X-CACHE-MISS entry should tell us who.
1191 */
1192 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%s %d", name, xerrno);
1193
1194 #if USE_ERR_LOCALES
1195 /*
1196 * If error page auto-negotiate is enabled in any way, send the Vary.
1197 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1198 * We have even better reasons though:
1199 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1200 */
1201 if (!Config.errorDirectory) {
1202 /* We 'negotiated' this ONLY from the Accept-Language. */
1203 rep->header.delById(HDR_VARY);
1204 rep->header.putStr(HDR_VARY, "Accept-Language");
1205 }
1206
1207 /* add the Content-Language header according to RFC section 14.12 */
1208 if (err_language) {
1209 rep->header.putStr(HDR_CONTENT_LANGUAGE, err_language);
1210 } else
1211 #endif /* USE_ERROR_LOCALES */
1212 {
1213 /* default templates are in English */
1214 /* language is known unless error_directory override used */
1215 if (!Config.errorDirectory)
1216 rep->header.putStr(HDR_CONTENT_LANGUAGE, "en");
1217 }
1218
1219 rep->body.setMb(content);
1220 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1221 }
1222
1223 // Make sure error codes get back to the client side for logging and
1224 // error tracking.
1225 if (request) {
1226 int edc = ERR_DETAIL_NONE; // error detail code
1227 #if USE_SSL
1228 if (detail)
1229 edc = detail->errorNo();
1230 else
1231 #endif
1232 if (detailCode)
1233 edc = detailCode;
1234 else
1235 edc = xerrno;
1236 request->detailError(type, edc);
1237 }
1238
1239 return rep;
1240 }
1241
1242 MemBuf *
1243 ErrorState::BuildContent()
1244 {
1245 const char *m = NULL;
1246
1247 assert(page_id > ERR_NONE && page_id < error_page_count);
1248
1249 #if USE_ERR_LOCALES
1250 ErrorPageFile *localeTmpl = NULL;
1251
1252 /** error_directory option in squid.conf overrides translations.
1253 * Custom errors are always found either in error_directory or the templates directory.
1254 * Otherwise locate the Accept-Language header
1255 */
1256 if (!Config.errorDirectory && page_id < ERR_MAX) {
1257 if (err_language && err_language != Config.errorDefaultLanguage)
1258 safe_free(err_language);
1259
1260 localeTmpl = new ErrorPageFile(err_type_str[page_id], static_cast<err_type>(page_id));
1261 if (localeTmpl->loadFor(request)) {
1262 m = localeTmpl->text();
1263 assert(localeTmpl->language());
1264 err_language = xstrdup(localeTmpl->language());
1265 }
1266 }
1267 #endif /* USE_ERR_LOCALES */
1268
1269 /** \par
1270 * If client-specific error templates are not enabled or available.
1271 * fall back to the old style squid.conf settings.
1272 */
1273 if (!m) {
1274 m = error_text[page_id];
1275 #if USE_ERR_LOCALES
1276 if (!Config.errorDirectory)
1277 err_language = Config.errorDefaultLanguage;
1278 #endif
1279 debugs(4, 2, HERE << "No existing error page language negotiated for " << errorPageName(page_id) << ". Using default error file.");
1280 }
1281
1282 MemBuf *result = ConvertText(m, true);
1283 #if USE_ERR_LOCALES
1284 if (localeTmpl)
1285 delete localeTmpl;
1286 #endif
1287 return result;
1288 }
1289
1290 MemBuf *ErrorState::ConvertText(const char *text, bool allowRecursion)
1291 {
1292 MemBuf *content = new MemBuf;
1293 const char *p;
1294 const char *m = text;
1295 assert(m);
1296 content->init();
1297
1298 while ((p = strchr(m, '%'))) {
1299 content->append(m, p - m); /* copy */
1300 const char *t = Convert(*++p, false, allowRecursion); /* convert */
1301 content->Printf("%s", t); /* copy */
1302 m = p + 1; /* advance */
1303 }
1304
1305 if (*m)
1306 content->Printf("%s", m); /* copy tail */
1307
1308 content->terminate();
1309
1310 assert((size_t)content->contentSize() == strlen(content->content()));
1311
1312 return content;
1313 }