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