]> git.ipfire.org Git - thirdparty/squid.git/blob - src/errorpage.cc
merge 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 "clients/forward.h"
35 #include "comm/Connection.h"
36 #include "comm/Write.h"
37 #include "disk.h"
38 #include "err_detail_type.h"
39 #include "errorpage.h"
40 #include "fde.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 "wordlist.h"
53 #if USE_AUTH
54 #include "auth/UserRequest.h"
55 #endif
56 #include "SquidTime.h"
57 #if USE_OPENSSL
58 #include "ssl/ErrorDetailManager.h"
59 #endif
60
61 /**
62 \defgroup ErrorPageInternal Error Page Internals
63 \ingroup ErrorPageAPI
64 *
65 \section Abstract Abstract:
66 * These routines are used to generate error messages to be
67 * sent to clients. The error type is used to select between
68 * the various message formats. (formats are stored in the
69 * Config.errorDirectory)
70 */
71
72 #if !defined(DEFAULT_SQUID_ERROR_DIR)
73 /** Where to look for errors if config path fails.
74 \note Please use ./configure --datadir=/path instead of patching
75 */
76 #define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
77 #endif
78
79 /// \ingroup ErrorPageInternal
80 CBDATA_CLASS_INIT(ErrorState);
81
82 /* local types */
83
84 /// \ingroup ErrorPageInternal
85 typedef struct {
86 int id;
87 char *page_name;
88 Http::StatusCode page_redirect;
89 } ErrorDynamicPageInfo;
90
91 /* local constant and vars */
92
93 /**
94 \ingroup ErrorPageInternal
95 *
96 \note hard coded error messages are not appended with %S
97 * automagically to give you more control on the format
98 */
99 static const struct {
100 int type; /* and page_id */
101 const char *text;
102 }
103
104 error_hard_text[] = {
105
106 {
107 ERR_SQUID_SIGNATURE,
108 "\n<br>\n"
109 "<hr>\n"
110 "<div id=\"footer\">\n"
111 "Generated %T by %h (%s)\n"
112 "</div>\n"
113 "</body></html>\n"
114 },
115 {
116 TCP_RESET,
117 "reset"
118 }
119 };
120
121 /// \ingroup ErrorPageInternal
122 static std::vector<ErrorDynamicPageInfo *> ErrorDynamicPages;
123
124 /* local prototypes */
125
126 /// \ingroup ErrorPageInternal
127 static const int error_hard_text_count = sizeof(error_hard_text) / sizeof(*error_hard_text);
128
129 /// \ingroup ErrorPageInternal
130 static char **error_text = NULL;
131
132 /// \ingroup ErrorPageInternal
133 static int error_page_count = 0;
134
135 /// \ingroup ErrorPageInternal
136 static MemBuf error_stylesheet;
137
138 static const char *errorFindHardText(err_type type);
139 static ErrorDynamicPageInfo *errorDynamicPageInfoCreate(int id, const char *page_name);
140 static void errorDynamicPageInfoDestroy(ErrorDynamicPageInfo * info);
141 static IOCB errorSendComplete;
142
143 /// \ingroup ErrorPageInternal
144 /// manages an error page template
145 class ErrorPageFile: public TemplateFile
146 {
147 public:
148 ErrorPageFile(const char *name, const err_type code): TemplateFile(name,code) { textBuf.init();}
149
150 /// The template text data read from disk
151 const char *text() { return textBuf.content(); }
152
153 private:
154 /// stores the data read from disk to a local buffer
155 virtual bool parse(const char *buf, int len, bool eof) {
156 if (len)
157 textBuf.append(buf, len);
158 return true;
159 }
160
161 MemBuf textBuf; ///< A buffer to store the error page
162 };
163
164 /// \ingroup ErrorPageInternal
165 err_type &operator++ (err_type &anErr)
166 {
167 int tmp = (int)anErr;
168 anErr = (err_type)(++tmp);
169 return anErr;
170 }
171
172 /// \ingroup ErrorPageInternal
173 int operator - (err_type const &anErr, err_type const &anErr2)
174 {
175 return (int)anErr - (int)anErr2;
176 }
177
178 void
179 errorInitialize(void)
180 {
181 err_type i;
182 const char *text;
183 error_page_count = ERR_MAX + ErrorDynamicPages.size();
184 error_text = static_cast<char **>(xcalloc(error_page_count, sizeof(char *)));
185
186 for (i = ERR_NONE, ++i; i < error_page_count; ++i) {
187 safe_free(error_text[i]);
188
189 if ((text = errorFindHardText(i))) {
190 /**\par
191 * Index any hard-coded error text into defaults.
192 */
193 error_text[i] = xstrdup(text);
194
195 } else if (i < ERR_MAX) {
196 /**\par
197 * Index precompiled fixed template files from one of two sources:
198 * (a) default language translation directory (error_default_language)
199 * (b) admin specified custom directory (error_directory)
200 */
201 ErrorPageFile errTmpl(err_type_str[i], i);
202 error_text[i] = errTmpl.loadDefault() ? xstrdup(errTmpl.text()) : NULL;
203 } else {
204 /** \par
205 * Index any unknown file names used by deny_info.
206 */
207 ErrorDynamicPageInfo *info = ErrorDynamicPages.at(i - ERR_MAX);
208 assert(info && info->id == i && info->page_name);
209
210 const char *pg = info->page_name;
211 if (info->page_redirect != Http::scNone)
212 pg = info->page_name +4;
213
214 if (strchr(pg, ':') == NULL) {
215 /** But only if they are not redirection URL. */
216 ErrorPageFile errTmpl(pg, ERR_MAX);
217 error_text[i] = errTmpl.loadDefault() ? xstrdup(errTmpl.text()) : NULL;
218 }
219 }
220 }
221
222 error_stylesheet.reset();
223
224 // look for and load stylesheet into global MemBuf for it.
225 if (Config.errorStylesheet) {
226 ErrorPageFile tmpl("StylesSheet", ERR_MAX);
227 tmpl.loadFromFile(Config.errorStylesheet);
228 error_stylesheet.Printf("%s",tmpl.text());
229 }
230
231 #if USE_OPENSSL
232 Ssl::errorDetailInitialize();
233 #endif
234 }
235
236 void
237 errorClean(void)
238 {
239 if (error_text) {
240 int i;
241
242 for (i = ERR_NONE + 1; i < error_page_count; ++i)
243 safe_free(error_text[i]);
244
245 safe_free(error_text);
246 }
247
248 while (!ErrorDynamicPages.empty()) {
249 errorDynamicPageInfoDestroy(ErrorDynamicPages.back());
250 ErrorDynamicPages.pop_back();
251 }
252
253 error_page_count = 0;
254
255 #if USE_OPENSSL
256 Ssl::errorDetailClean();
257 #endif
258 }
259
260 /// \ingroup ErrorPageInternal
261 static const char *
262 errorFindHardText(err_type type)
263 {
264 int i;
265
266 for (i = 0; i < error_hard_text_count; ++i)
267 if (error_hard_text[i].type == type)
268 return error_hard_text[i].text;
269
270 return NULL;
271 }
272
273 TemplateFile::TemplateFile(const char *name, const err_type code): silent(false), wasLoaded(false), templateName(name), templateCode(code)
274 {
275 assert(name);
276 }
277
278 bool
279 TemplateFile::loadDefault()
280 {
281 if (loaded()) // already loaded?
282 return true;
283
284 /** test error_directory configured location */
285 if (Config.errorDirectory) {
286 char path[MAXPATHLEN];
287 snprintf(path, sizeof(path), "%s/%s", Config.errorDirectory, templateName.termedBuf());
288 loadFromFile(path);
289 }
290
291 #if USE_ERR_LOCALES
292 /** test error_default_language location */
293 if (!loaded() && Config.errorDefaultLanguage) {
294 if (!tryLoadTemplate(Config.errorDefaultLanguage)) {
295 debugs(1, (templateCode < TCP_RESET ? DBG_CRITICAL : 3), "Unable to load default error language files. Reset to backups.");
296 }
297 }
298 #endif
299
300 /* test default location if failed (templates == English translation base templates) */
301 if (!loaded()) {
302 tryLoadTemplate("templates");
303 }
304
305 /* giving up if failed */
306 if (!loaded()) {
307 debugs(1, (templateCode < TCP_RESET ? DBG_CRITICAL : 3), "WARNING: failed to find or read error text file " << templateName);
308 parse("Internal Error: Missing Template ", 33, '\0');
309 parse(templateName.termedBuf(), templateName.size(), '\0');
310 }
311
312 return true;
313 }
314
315 bool
316 TemplateFile::tryLoadTemplate(const char *lang)
317 {
318 assert(lang);
319
320 char path[MAXPATHLEN];
321 /* TODO: prep the directory path string to prevent snprintf ... */
322 snprintf(path, sizeof(path), "%s/%s/%s",
323 DEFAULT_SQUID_ERROR_DIR, lang, templateName.termedBuf());
324 path[MAXPATHLEN-1] = '\0';
325
326 if (loadFromFile(path))
327 return true;
328
329 #if HAVE_GLOB
330 if ( strlen(lang) == 2) {
331 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
332 /* use first result. */
333 debugs(4,2, HERE << "wildcard fallback errors not coded yet.");
334 }
335 #endif
336
337 return false;
338 }
339
340 bool
341 TemplateFile::loadFromFile(const char *path)
342 {
343 int fd;
344 char buf[4096];
345 ssize_t len;
346
347 if (loaded()) // already loaded?
348 return true;
349
350 fd = file_open(path, O_RDONLY | O_TEXT);
351
352 if (fd < 0) {
353 /* with dynamic locale negotiation we may see some failures before a success. */
354 if (!silent && templateCode < TCP_RESET)
355 debugs(4, DBG_CRITICAL, HERE << "'" << path << "': " << xstrerror());
356 wasLoaded = false;
357 return wasLoaded;
358 }
359
360 while ((len = FD_READ_METHOD(fd, buf, sizeof(buf))) > 0) {
361 if (!parse(buf, len, false)) {
362 debugs(4, DBG_CRITICAL, HERE << " parse error while reading template file: " << path);
363 wasLoaded = false;
364 return wasLoaded;
365 }
366 }
367 parse(buf, 0, true);
368
369 if (len < 0) {
370 debugs(4, DBG_CRITICAL, HERE << "failed to fully read: '" << path << "': " << xstrerror());
371 }
372
373 file_close(fd);
374
375 wasLoaded = true;
376 return wasLoaded;
377 }
378
379 bool strHdrAcptLangGetItem(const String &hdr, char *lang, int langLen, size_t &pos)
380 {
381 while (pos < hdr.size()) {
382 char *dt = lang;
383
384 /* skip any initial whitespace. */
385 while (pos < hdr.size() && xisspace(hdr[pos]))
386 ++pos;
387
388 /*
389 * Header value format:
390 * - sequence of whitespace delimited tags
391 * - each tag may suffix with ';'.* which we can ignore.
392 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
393 * with preference given to an exact match.
394 */
395 bool invalid_byte = false;
396 while (pos < hdr.size() && hdr[pos] != ';' && hdr[pos] != ',' && !xisspace(hdr[pos]) && dt < (lang + (langLen -1)) ) {
397 if (!invalid_byte) {
398 #if USE_HTTP_VIOLATIONS
399 // if accepting violations we may as well accept some broken browsers
400 // which may send us the right code, wrong ISO formatting.
401 if (hdr[pos] == '_')
402 *dt = '-';
403 else
404 #endif
405 *dt = xtolower(hdr[pos]);
406 // valid codes only contain A-Z, hyphen (-) and *
407 if (*dt != '-' && *dt != '*' && (*dt < 'a' || *dt > 'z') )
408 invalid_byte = true;
409 else
410 ++dt; // move to next destination byte.
411 }
412 ++pos;
413 }
414 *dt = '\0'; // nul-terminated the filename content string before system use.
415 ++dt;
416
417 // if we terminated the tag on garbage or ';' we need to skip to the next ',' or end of header.
418 while (pos < hdr.size() && hdr[pos] != ',')
419 ++pos;
420
421 if (pos < hdr.size() && hdr[pos] == ',')
422 ++pos;
423
424 debugs(4, 9, HERE << "STATE: dt='" << dt << "', lang='" << lang << "', pos=" << pos << ", buf='" << ((pos < hdr.size()) ? hdr.substr(pos,hdr.size()) : "") << "'");
425
426 /* if we found anything we might use, try it. */
427 if (*lang != '\0' && !invalid_byte)
428 return true;
429 }
430 return false;
431 }
432
433 bool
434 TemplateFile::loadFor(const HttpRequest *request)
435 {
436 String hdr;
437
438 #if USE_ERR_LOCALES
439 if (loaded()) // already loaded?
440 return true;
441
442 if (!request || !request->header.getList(HDR_ACCEPT_LANGUAGE, &hdr) )
443 return false;
444
445 char lang[256];
446 size_t pos = 0; // current parsing position in header string
447
448 debugs(4, 6, HERE << "Testing Header: '" << hdr << "'");
449
450 while ( strHdrAcptLangGetItem(hdr, lang, 256, pos) ) {
451
452 /* wildcard uses the configured default language */
453 if (lang[0] == '*' && lang[1] == '\0') {
454 debugs(4, 6, HERE << "Found language '" << lang << "'. Using configured default.");
455 return false;
456 }
457
458 debugs(4, 6, HERE << "Found language '" << lang << "', testing for available template");
459
460 if (tryLoadTemplate(lang)) {
461 /* store the language we found for the Content-Language reply header */
462 errLanguage = lang;
463 break;
464 } else if (Config.errorLogMissingLanguages) {
465 debugs(4, DBG_IMPORTANT, "WARNING: Error Pages Missing Language: " << lang);
466 }
467 }
468 #endif
469
470 return loaded();
471 }
472
473 /// \ingroup ErrorPageInternal
474 static ErrorDynamicPageInfo *
475 errorDynamicPageInfoCreate(int id, const char *page_name)
476 {
477 ErrorDynamicPageInfo *info = new ErrorDynamicPageInfo;
478 info->id = id;
479 info->page_name = xstrdup(page_name);
480 info->page_redirect = static_cast<Http::StatusCode>(atoi(page_name));
481
482 /* WARNING on redirection status:
483 * 2xx are permitted, but not documented officially.
484 * - might be useful for serving static files (PAC etc) in special cases
485 * 3xx require a URL suitable for Location: header.
486 * - the current design does not allow for a Location: URI as well as a local file template
487 * although this possibility is explicitly permitted in the specs.
488 * 4xx-5xx require a local file template.
489 * - sending Location: on these codes with no body is invalid by the specs.
490 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
491 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
492 */
493 if (info->page_redirect == Http::scNone)
494 ; // special case okay.
495 else if (info->page_redirect < 200 || info->page_redirect > 599) {
496 // out of range
497 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " is not valid on '" << page_name << "'");
498 self_destruct();
499 } else if ( /* >= 200 && */ info->page_redirect < 300 && strchr(&(page_name[4]), ':')) {
500 // 2xx require a local template file
501 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " requires a template on '" << page_name << "'");
502 self_destruct();
503 } else if (info->page_redirect >= 300 && info->page_redirect <= 399 && !strchr(&(page_name[4]), ':')) {
504 // 3xx require an absolute URL
505 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " requires a URL on '" << page_name << "'");
506 self_destruct();
507 } else if (info->page_redirect >= 400 /* && <= 599 */ && strchr(&(page_name[4]), ':')) {
508 // 4xx/5xx require a local template file
509 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " requires a template on '" << page_name << "'");
510 self_destruct();
511 }
512 // else okay.
513
514 return info;
515 }
516
517 /// \ingroup ErrorPageInternal
518 static void
519 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo * info)
520 {
521 assert(info);
522 safe_free(info->page_name);
523 delete info;
524 }
525
526 /// \ingroup ErrorPageInternal
527 static int
528 errorPageId(const char *page_name)
529 {
530 for (int i = 0; i < ERR_MAX; ++i) {
531 if (strcmp(err_type_str[i], page_name) == 0)
532 return i;
533 }
534
535 for (size_t j = 0; j < ErrorDynamicPages.size(); ++j) {
536 if (strcmp(ErrorDynamicPages[j]->page_name, page_name) == 0)
537 return j + ERR_MAX;
538 }
539
540 return ERR_NONE;
541 }
542
543 err_type
544 errorReservePageId(const char *page_name)
545 {
546 ErrorDynamicPageInfo *info;
547 int id = errorPageId(page_name);
548
549 if (id == ERR_NONE) {
550 info = errorDynamicPageInfoCreate(ERR_MAX + ErrorDynamicPages.size(), page_name);
551 ErrorDynamicPages.push_back(info);
552 id = info->id;
553 }
554
555 return (err_type)id;
556 }
557
558 /// \ingroup ErrorPageInternal
559 const char *
560 errorPageName(int pageId)
561 {
562 if (pageId >= ERR_NONE && pageId < ERR_MAX) /* common case */
563 return err_type_str[pageId];
564
565 if (pageId >= ERR_MAX && pageId - ERR_MAX < (ssize_t)ErrorDynamicPages.size())
566 return ErrorDynamicPages[pageId - ERR_MAX]->page_name;
567
568 return "ERR_UNKNOWN"; /* should not happen */
569 }
570
571 ErrorState *
572 ErrorState::NewForwarding(err_type type, HttpRequest *request)
573 {
574 assert(request);
575 const Http::StatusCode status = request->flags.needValidation ?
576 Http::scGatewayTimeout : Http::scServiceUnavailable;
577 return new ErrorState(type, status, request);
578 }
579
580 ErrorState::ErrorState(err_type t, Http::StatusCode status, HttpRequest * req) :
581 type(t),
582 page_id(t),
583 err_language(NULL),
584 httpStatus(status),
585 #if USE_AUTH
586 auth_user_request (NULL),
587 #endif
588 request(NULL),
589 url(NULL),
590 xerrno(0),
591 port(0),
592 dnsError(),
593 ttl(0),
594 src_addr(),
595 redirect_url(NULL),
596 callback(NULL),
597 callback_data(NULL),
598 request_hdrs(NULL),
599 err_msg(NULL),
600 #if USE_OPENSSL
601 detail(NULL),
602 #endif
603 detailCode(ERR_DETAIL_NONE)
604 {
605 memset(&ftp, 0, sizeof(ftp));
606
607 if (page_id >= ERR_MAX && ErrorDynamicPages[page_id - ERR_MAX]->page_redirect != Http::scNone)
608 httpStatus = ErrorDynamicPages[page_id - ERR_MAX]->page_redirect;
609
610 if (req != NULL) {
611 request = req;
612 HTTPMSGLOCK(request);
613 src_addr = req->client_addr;
614 }
615 }
616
617 void
618 errorAppendEntry(StoreEntry * entry, ErrorState * err)
619 {
620 assert(entry->mem_obj != NULL);
621 assert (entry->isEmpty());
622 debugs(4, 4, "Creating an error page for entry " << entry <<
623 " with errorstate " << err <<
624 " page id " << err->page_id);
625
626 if (entry->store_status != STORE_PENDING) {
627 debugs(4, 2, "Skipping error page due to store_status: " << entry->store_status);
628 /*
629 * If the entry is not STORE_PENDING, then no clients
630 * care about it, and we don't need to generate an
631 * error message
632 */
633 assert(EBIT_TEST(entry->flags, ENTRY_ABORTED));
634 assert(entry->mem_obj->nclients == 0);
635 delete err;
636 return;
637 }
638
639 if (err->page_id == TCP_RESET) {
640 if (err->request) {
641 debugs(4, 2, "RSTing this reply");
642 err->request->flags.resetTcp = true;
643 }
644 }
645
646 entry->storeErrorResponse(err->BuildHttpReply());
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::Flag 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_OPENSSL
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(SQUIDSBUFPH " " SQUIDSTRINGPH " %s/%d.%d\n",
770 SQUIDSBUFPRINT(request->method.image()),
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 ? Ftp::UrlWith2f(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_OPENSSL
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 const SBuf &m = request->method.image();
947 mb.append(m.rawContent(), m.length());
948 } else if (!building_deny_info_url)
949 p = "[unknown method]";
950 break;
951
952 case 'o':
953 p = request ? request->extacl_message.termedBuf() : external_acl_message;
954 if (!p && !building_deny_info_url)
955 p = "[not available]";
956 break;
957
958 case 'p':
959 if (request) {
960 mb.Printf("%d", (int) request->port);
961 } else if (!building_deny_info_url) {
962 p = "[unknown port]";
963 }
964 break;
965
966 case 'P':
967 if (request) {
968 p = request->url.getScheme().c_str();
969 } else if (!building_deny_info_url) {
970 p = "[unknown protocol]";
971 }
972 break;
973
974 case 'R':
975 if (building_deny_info_url) {
976 p = (request->urlpath.size() != 0 ? request->urlpath.termedBuf() : "/");
977 no_urlescape = 1;
978 break;
979 }
980 if (NULL != request) {
981 Packer pck;
982 String urlpath_or_slash;
983
984 if (request->urlpath.size() != 0)
985 urlpath_or_slash = request->urlpath;
986 else
987 urlpath_or_slash = "/";
988
989 mb.Printf(SQUIDSBUFPH " " SQUIDSTRINGPH " %s/%d.%d\n",
990 SQUIDSBUFPRINT(request->method.image()),
991 SQUIDSTRINGPRINT(urlpath_or_slash),
992 AnyP::ProtocolType_str[request->http_ver.protocol],
993 request->http_ver.major, request->http_ver.minor);
994 packerToMemInit(&pck, &mb);
995 request->header.packInto(&pck, true); //hide authorization data
996 packerClean(&pck);
997 } else if (request_hdrs) {
998 p = request_hdrs;
999 } else {
1000 p = "[no request]";
1001 }
1002 break;
1003
1004 case 's':
1005 /* for backward compat we make %s show the full URL. Drop this in some future release. */
1006 if (building_deny_info_url) {
1007 p = request ? urlCanonical(request) : url;
1008 debugs(0, DBG_CRITICAL, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
1009 } else
1010 p = visible_appname_string;
1011 break;
1012
1013 case 'S':
1014 if (building_deny_info_url) {
1015 p = visible_appname_string;
1016 break;
1017 }
1018 /* signature may contain %-escapes, recursion */
1019 if (page_id != ERR_SQUID_SIGNATURE) {
1020 const int saved_id = page_id;
1021 page_id = ERR_SQUID_SIGNATURE;
1022 MemBuf *sign_mb = BuildContent();
1023 mb.Printf("%s", sign_mb->content());
1024 sign_mb->clean();
1025 delete sign_mb;
1026 page_id = saved_id;
1027 do_quote = 0;
1028 } else {
1029 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1030 p = "[%S]";
1031 }
1032 break;
1033
1034 case 't':
1035 mb.Printf("%s", Time::FormatHttpd(squid_curtime));
1036 break;
1037
1038 case 'T':
1039 mb.Printf("%s", mkrfc1123(squid_curtime));
1040 break;
1041
1042 case 'U':
1043 /* Using the fake-https version of canonical so error pages see https:// */
1044 /* even when the url-path cannot be shown as more than '*' */
1045 if (request)
1046 p = urlCanonicalFakeHttps(request);
1047 else if (url)
1048 p = url;
1049 else if (!building_deny_info_url)
1050 p = "[no URL]";
1051 break;
1052
1053 case 'u':
1054 if (request)
1055 p = urlCanonical(request);
1056 else if (url)
1057 p = url;
1058 else if (!building_deny_info_url)
1059 p = "[no URL]";
1060 break;
1061
1062 case 'w':
1063 if (Config.adminEmail)
1064 mb.Printf("%s", Config.adminEmail);
1065 else if (!building_deny_info_url)
1066 p = "[unknown]";
1067 break;
1068
1069 case 'W':
1070 if (building_deny_info_url) break;
1071 if (Config.adminEmail && Config.onoff.emailErrData)
1072 Dump(&mb);
1073 no_urlescape = 1;
1074 break;
1075
1076 case 'x':
1077 #if USE_OPENSSL
1078 if (detail)
1079 mb.Printf("%s", detail->errorName());
1080 else
1081 #endif
1082 if (!building_deny_info_url)
1083 p = "[Unknown Error Code]";
1084 break;
1085
1086 case 'z':
1087 if (building_deny_info_url) break;
1088 if (dnsError.size() > 0)
1089 p = dnsError.termedBuf();
1090 else if (ftp.cwd_msg)
1091 p = ftp.cwd_msg;
1092 else
1093 p = "[unknown]";
1094 break;
1095
1096 case 'Z':
1097 if (building_deny_info_url) break;
1098 if (err_msg)
1099 p = err_msg;
1100 else
1101 p = "[unknown]";
1102 break;
1103
1104 case '%':
1105 p = "%";
1106 break;
1107
1108 default:
1109 mb.Printf("%%%c", token);
1110 do_quote = 0;
1111 break;
1112 }
1113
1114 if (!p)
1115 p = mb.buf; /* do not use mb after this assignment! */
1116
1117 assert(p);
1118
1119 debugs(4, 3, "errorConvert: %%" << token << " --> '" << p << "'" );
1120
1121 if (do_quote)
1122 p = html_quote(p);
1123
1124 if (building_deny_info_url && !no_urlescape)
1125 p = rfc1738_escape_part(p);
1126
1127 return p;
1128 }
1129
1130 void
1131 ErrorState::DenyInfoLocation(const char *name, HttpRequest *aRequest, MemBuf &result)
1132 {
1133 char const *m = name;
1134 char const *p = m;
1135 char const *t;
1136
1137 if (m[0] == '3')
1138 m += 4; // skip "3xx:"
1139
1140 while ((p = strchr(m, '%'))) {
1141 result.append(m, p - m); /* copy */
1142 t = Convert(*++p, true, true); /* convert */
1143 result.Printf("%s", t); /* copy */
1144 m = p + 1; /* advance */
1145 }
1146
1147 if (*m)
1148 result.Printf("%s", m); /* copy tail */
1149
1150 assert((size_t)result.contentSize() == strlen(result.content()));
1151 }
1152
1153 HttpReply *
1154 ErrorState::BuildHttpReply()
1155 {
1156 HttpReply *rep = new HttpReply;
1157 const char *name = errorPageName(page_id);
1158 /* no LMT for error pages; error pages expire immediately */
1159
1160 if (name[0] == '3' || (name[0] != '2' && name[0] != '4' && name[0] != '5' && strchr(name, ':'))) {
1161 /* Redirection */
1162 Http::StatusCode status = Http::scFound;
1163 // Use configured 3xx reply status if set.
1164 if (name[0] == '3')
1165 status = httpStatus;
1166 else {
1167 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1168 if (request->method != Http::METHOD_GET && request->method != Http::METHOD_HEAD && request->http_ver >= Http::ProtocolVersion(1,1))
1169 status = Http::scTemporaryRedirect;
1170 }
1171
1172 rep->setHeaders(status, NULL, "text/html;charset=utf-8", 0, 0, -1);
1173
1174 if (request) {
1175 MemBuf redirect_location;
1176 redirect_location.init();
1177 DenyInfoLocation(name, request, redirect_location);
1178 httpHeaderPutStrf(&rep->header, HDR_LOCATION, "%s", redirect_location.content() );
1179 }
1180
1181 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%d %s", httpStatus, "Access Denied");
1182 } else {
1183 MemBuf *content = BuildContent();
1184 rep->setHeaders(httpStatus, NULL, "text/html;charset=utf-8", content->contentSize(), 0, -1);
1185 /*
1186 * include some information for downstream caches. Implicit
1187 * replaceable content. This isn't quite sufficient. xerrno is not
1188 * necessarily meaningful to another system, so we really should
1189 * expand it. Additionally, we should identify ourselves. Someone
1190 * might want to know. Someone _will_ want to know OTOH, the first
1191 * X-CACHE-MISS entry should tell us who.
1192 */
1193 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%s %d", name, xerrno);
1194
1195 #if USE_ERR_LOCALES
1196 /*
1197 * If error page auto-negotiate is enabled in any way, send the Vary.
1198 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1199 * We have even better reasons though:
1200 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1201 */
1202 if (!Config.errorDirectory) {
1203 /* We 'negotiated' this ONLY from the Accept-Language. */
1204 rep->header.delById(HDR_VARY);
1205 rep->header.putStr(HDR_VARY, "Accept-Language");
1206 }
1207
1208 /* add the Content-Language header according to RFC section 14.12 */
1209 if (err_language) {
1210 rep->header.putStr(HDR_CONTENT_LANGUAGE, err_language);
1211 } else
1212 #endif /* USE_ERROR_LOCALES */
1213 {
1214 /* default templates are in English */
1215 /* language is known unless error_directory override used */
1216 if (!Config.errorDirectory)
1217 rep->header.putStr(HDR_CONTENT_LANGUAGE, "en");
1218 }
1219
1220 rep->body.setMb(content);
1221 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1222 }
1223
1224 // Make sure error codes get back to the client side for logging and
1225 // error tracking.
1226 if (request) {
1227 int edc = ERR_DETAIL_NONE; // error detail code
1228 #if USE_OPENSSL
1229 if (detail)
1230 edc = detail->errorNo();
1231 else
1232 #endif
1233 if (detailCode)
1234 edc = detailCode;
1235 else
1236 edc = xerrno;
1237 request->detailError(type, edc);
1238 }
1239
1240 return rep;
1241 }
1242
1243 MemBuf *
1244 ErrorState::BuildContent()
1245 {
1246 const char *m = NULL;
1247
1248 assert(page_id > ERR_NONE && page_id < error_page_count);
1249
1250 #if USE_ERR_LOCALES
1251 ErrorPageFile *localeTmpl = NULL;
1252
1253 /** error_directory option in squid.conf overrides translations.
1254 * Custom errors are always found either in error_directory or the templates directory.
1255 * Otherwise locate the Accept-Language header
1256 */
1257 if (!Config.errorDirectory && page_id < ERR_MAX) {
1258 if (err_language && err_language != Config.errorDefaultLanguage)
1259 safe_free(err_language);
1260
1261 localeTmpl = new ErrorPageFile(err_type_str[page_id], static_cast<err_type>(page_id));
1262 if (localeTmpl->loadFor(request)) {
1263 m = localeTmpl->text();
1264 assert(localeTmpl->language());
1265 err_language = xstrdup(localeTmpl->language());
1266 }
1267 }
1268 #endif /* USE_ERR_LOCALES */
1269
1270 /** \par
1271 * If client-specific error templates are not enabled or available.
1272 * fall back to the old style squid.conf settings.
1273 */
1274 if (!m) {
1275 m = error_text[page_id];
1276 #if USE_ERR_LOCALES
1277 if (!Config.errorDirectory)
1278 err_language = Config.errorDefaultLanguage;
1279 #endif
1280 debugs(4, 2, HERE << "No existing error page language negotiated for " << errorPageName(page_id) << ". Using default error file.");
1281 }
1282
1283 MemBuf *result = ConvertText(m, true);
1284 #if USE_ERR_LOCALES
1285 if (localeTmpl)
1286 delete localeTmpl;
1287 #endif
1288 return result;
1289 }
1290
1291 MemBuf *ErrorState::ConvertText(const char *text, bool allowRecursion)
1292 {
1293 MemBuf *content = new MemBuf;
1294 const char *p;
1295 const char *m = text;
1296 assert(m);
1297 content->init();
1298
1299 while ((p = strchr(m, '%'))) {
1300 content->append(m, p - m); /* copy */
1301 const char *t = Convert(*++p, false, allowRecursion); /* convert */
1302 content->Printf("%s", t); /* copy */
1303 m = p + 1; /* advance */
1304 }
1305
1306 if (*m)
1307 content->Printf("%s", m); /* copy tail */
1308
1309 content->terminate();
1310
1311 assert((size_t)content->contentSize() == strlen(content->content()));
1312
1313 return content;
1314 }