]> git.ipfire.org Git - thirdparty/squid.git/blob - src/errorpage.cc
Bug 3390: Proxy auth data visible to scripts
[thirdparty/squid.git] / src / errorpage.cc
1 /*
2 * $Id$
3 *
4 * DEBUG: section 04 Error Generation
5 * AUTHOR: Duane Wessels
6 *
7 * SQUID Web Proxy Cache http://www.squid-cache.org/
8 * ----------------------------------------------------------
9 *
10 * Squid is the result of efforts by numerous individuals from
11 * the Internet community; see the CONTRIBUTORS file for full
12 * details. Many organizations have provided support for Squid's
13 * development; see the SPONSORS file for full details. Squid is
14 * Copyrighted (C) 2001 by the Regents of the University of
15 * California; see the COPYRIGHT file for full details. Squid
16 * incorporates software developed and/or copyrighted by other
17 * sources; see the CREDITS file for full details.
18 *
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
23 *
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
28 *
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
32 *
33 */
34 #include "squid.h"
35 #include "comm/Connection.h"
36 #include "comm/Write.h"
37 #include "errorpage.h"
38 #if USE_AUTH
39 #include "auth/UserRequest.h"
40 #endif
41 #include "SquidTime.h"
42 #if USE_SSL
43 #include "ssl/ErrorDetailManager.h"
44 #endif
45 #include "Store.h"
46 #include "html_quote.h"
47 #include "HttpReply.h"
48 #include "HttpRequest.h"
49 #include "MemObject.h"
50 #include "fde.h"
51 #include "MemBuf.h"
52 #include "rfc1738.h"
53 #include "URLScheme.h"
54 #include "wordlist.h"
55 #include "err_detail_type.h"
56
57 /**
58 \defgroup ErrorPageInternal Error Page Internals
59 \ingroup ErrorPageAPI
60 *
61 \section Abstract Abstract:
62 * These routines are used to generate error messages to be
63 * sent to clients. The error type is used to select between
64 * the various message formats. (formats are stored in the
65 * Config.errorDirectory)
66 */
67
68
69 #if !defined(DEFAULT_SQUID_ERROR_DIR)
70 /** Where to look for errors if config path fails.
71 \note Please use ./configure --datadir=/path instead of patching
72 */
73 #define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
74 #endif
75
76 /// \ingroup ErrorPageInternal
77 CBDATA_CLASS_INIT(ErrorState);
78
79 /* local types */
80
81 /// \ingroup ErrorPageInternal
82 typedef struct {
83 int id;
84 char *page_name;
85 http_status page_redirect;
86 } ErrorDynamicPageInfo;
87
88 /* local constant and vars */
89
90 /**
91 \ingroup ErrorPageInternal
92 *
93 \note hard coded error messages are not appended with %S
94 * automagically to give you more control on the format
95 */
96 static const struct {
97 int type; /* and page_id */
98 const char *text;
99 }
100
101 error_hard_text[] = {
102
103 {
104 ERR_SQUID_SIGNATURE,
105 "\n<br>\n"
106 "<hr>\n"
107 "<div id=\"footer\">\n"
108 "Generated %T by %h (%s)\n"
109 "</div>\n"
110 "</body></html>\n"
111 },
112 {
113 TCP_RESET,
114 "reset"
115 }
116 };
117
118 /// \ingroup ErrorPageInternal
119 static Vector<ErrorDynamicPageInfo *> ErrorDynamicPages;
120
121 /* local prototypes */
122
123 /// \ingroup ErrorPageInternal
124 static const int error_hard_text_count = sizeof(error_hard_text) / sizeof(*error_hard_text);
125
126 /// \ingroup ErrorPageInternal
127 static char **error_text = NULL;
128
129 /// \ingroup ErrorPageInternal
130 static int error_page_count = 0;
131
132 /// \ingroup ErrorPageInternal
133 static MemBuf error_stylesheet;
134
135 static const char *errorFindHardText(err_type type);
136 static ErrorDynamicPageInfo *errorDynamicPageInfoCreate(int id, const char *page_name);
137 static void errorDynamicPageInfoDestroy(ErrorDynamicPageInfo * info);
138 static IOCB errorSendComplete;
139
140 /// \ingroup ErrorPageInternal
141 /// manages an error page template
142 class ErrorPageFile: public TemplateFile
143 {
144 public:
145 ErrorPageFile(const char *name, const err_type code): TemplateFile(name,code) { textBuf.init();}
146
147 /// The template text data read from disk
148 const char *text() { return textBuf.content(); }
149
150 private:
151 /// stores the data read from disk to a local buffer
152 virtual bool parse(const char *buf, int len, bool eof) {
153 if (len)
154 textBuf.append(buf, len);
155 return true;
156 }
157
158 MemBuf textBuf; ///< A buffer to store the error page
159 };
160
161 /// \ingroup ErrorPageInternal
162 err_type &operator++ (err_type &anErr)
163 {
164 int tmp = (int)anErr;
165 anErr = (err_type)(++tmp);
166 return anErr;
167 }
168
169 /// \ingroup ErrorPageInternal
170 int operator - (err_type const &anErr, err_type const &anErr2)
171 {
172 return (int)anErr - (int)anErr2;
173 }
174
175 void
176 errorInitialize(void)
177 {
178 err_type i;
179 const char *text;
180 error_page_count = ERR_MAX + ErrorDynamicPages.size();
181 error_text = static_cast<char **>(xcalloc(error_page_count, sizeof(char *)));
182
183 for (i = ERR_NONE, ++i; i < error_page_count; ++i) {
184 safe_free(error_text[i]);
185
186 if ((text = errorFindHardText(i))) {
187 /**\par
188 * Index any hard-coded error text into defaults.
189 */
190 error_text[i] = xstrdup(text);
191
192 } else if (i < ERR_MAX) {
193 /**\par
194 * Index precompiled fixed template files from one of two sources:
195 * (a) default language translation directory (error_default_language)
196 * (b) admin specified custom directory (error_directory)
197 */
198 ErrorPageFile errTmpl(err_type_str[i], i);
199 error_text[i] = errTmpl.loadDefault() ? xstrdup(errTmpl.text()) : NULL;
200 } else {
201 /** \par
202 * Index any unknown file names used by deny_info.
203 */
204 ErrorDynamicPageInfo *info = ErrorDynamicPages.items[i - ERR_MAX];
205 assert(info && info->id == i && info->page_name);
206
207 const char *pg = info->page_name;
208 if (info->page_redirect != HTTP_STATUS_NONE)
209 pg = info->page_name +4;
210
211 if (strchr(pg, ':') == NULL) {
212 /** But only if they are not redirection URL. */
213 ErrorPageFile errTmpl(pg, ERR_MAX);
214 error_text[i] = errTmpl.loadDefault() ? xstrdup(errTmpl.text()) : NULL;
215 }
216 }
217 }
218
219 error_stylesheet.reset();
220
221 // look for and load stylesheet into global MemBuf for it.
222 if (Config.errorStylesheet) {
223 ErrorPageFile tmpl("StylesSheet", ERR_MAX);
224 tmpl.loadFromFile(Config.errorStylesheet);
225 error_stylesheet.Printf("%s",tmpl.text());
226 }
227
228 #if USE_SSL
229 Ssl::errorDetailInitialize();
230 #endif
231 }
232
233 void
234 errorClean(void)
235 {
236 if (error_text) {
237 int i;
238
239 for (i = ERR_NONE + 1; i < error_page_count; i++)
240 safe_free(error_text[i]);
241
242 safe_free(error_text);
243 }
244
245 while (ErrorDynamicPages.size())
246 errorDynamicPageInfoDestroy(ErrorDynamicPages.pop_back());
247
248 error_page_count = 0;
249
250 #if USE_SSL
251 Ssl::errorDetailClean();
252 #endif
253 }
254
255 /// \ingroup ErrorPageInternal
256 static const char *
257 errorFindHardText(err_type type)
258 {
259 int i;
260
261 for (i = 0; i < error_hard_text_count; i++)
262 if (error_hard_text[i].type == type)
263 return error_hard_text[i].text;
264
265 return NULL;
266 }
267
268 TemplateFile::TemplateFile(const char *name, const err_type code): silent(false), wasLoaded(false), templateName(name), templateCode(code)
269 {
270 assert(name);
271 }
272
273 bool
274 TemplateFile::loadDefault()
275 {
276 if (loaded()) // already loaded?
277 return true;
278
279 /** test error_directory configured location */
280 if (Config.errorDirectory) {
281 char path[MAXPATHLEN];
282 snprintf(path, sizeof(path), "%s/%s", Config.errorDirectory, templateName.termedBuf());
283 loadFromFile(path);
284 }
285
286 #if USE_ERR_LOCALES
287 /** test error_default_language location */
288 if (!loaded() && Config.errorDefaultLanguage) {
289 if (!tryLoadTemplate(Config.errorDefaultLanguage)) {
290 debugs(1, (templateCode < TCP_RESET ? DBG_CRITICAL : 3), "Unable to load default error language files. Reset to backups.");
291 }
292 }
293 #endif
294
295 /* test default location if failed (templates == English translation base templates) */
296 if (!loaded()) {
297 tryLoadTemplate("templates");
298 }
299
300 /* giving up if failed */
301 if (!loaded()) {
302 debugs(1, (templateCode < TCP_RESET ? DBG_CRITICAL : 3), "WARNING: failed to find or read error text file " << templateName);
303 parse("Internal Error: Missing Template ", 33, '\0');
304 parse(templateName.termedBuf(), templateName.size(), '\0');
305 }
306
307 return true;
308 }
309
310 bool
311 TemplateFile::tryLoadTemplate(const char *lang)
312 {
313 assert(lang);
314
315 char path[MAXPATHLEN];
316 /* TODO: prep the directory path string to prevent snprintf ... */
317 snprintf(path, sizeof(path), "%s/%s/%s",
318 DEFAULT_SQUID_ERROR_DIR, lang, templateName.termedBuf());
319 path[MAXPATHLEN-1] = '\0';
320
321 if (loadFromFile(path))
322 return true;
323
324 #if HAVE_GLOB
325 if ( strlen(lang) == 2) {
326 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
327 /* use first result. */
328 debugs(4,2, HERE << "wildcard fallback errors not coded yet.");
329 }
330 #endif
331
332 return false;
333 }
334
335 bool
336 TemplateFile::loadFromFile(const char *path)
337 {
338 int fd;
339 char buf[4096];
340 ssize_t len;
341
342 if (loaded()) // already loaded?
343 return true;
344
345 fd = file_open(path, O_RDONLY | O_TEXT);
346
347 if (fd < 0) {
348 /* with dynamic locale negotiation we may see some failures before a success. */
349 if (!silent && templateCode < TCP_RESET)
350 debugs(4, DBG_CRITICAL, HERE << "'" << path << "': " << xstrerror());
351 wasLoaded = false;
352 return wasLoaded;
353 }
354
355 while ((len = FD_READ_METHOD(fd, buf, sizeof(buf))) > 0) {
356 if (!parse(buf, len, false)) {
357 debugs(4, DBG_CRITICAL, HERE << " parse error while reading template file: " << path);
358 wasLoaded = false;
359 return wasLoaded;
360 }
361 }
362 parse(buf, 0, true);
363
364 if (len < 0) {
365 debugs(4, DBG_CRITICAL, HERE << "failed to fully read: '" << path << "': " << xstrerror());
366 }
367
368 file_close(fd);
369
370 wasLoaded = true;
371 return wasLoaded;
372 }
373
374 bool strHdrAcptLangGetItem(const String &hdr, char *lang, int langLen, size_t &pos)
375 {
376 while (pos < hdr.size()) {
377 char *dt = lang;
378
379 if (!pos) {
380 /* skip any initial whitespace. */
381 while (pos < hdr.size() && xisspace(hdr[pos])) pos++;
382 } else {
383 // IFF we terminated the tag on whitespace or ';' we need to skip to the next ',' or end of header.
384 while (pos < hdr.size() && hdr[pos] != ',') pos++;
385 if (hdr[pos] == ',') pos++;
386 }
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
416 debugs(4, 9, HERE << "STATE: dt='" << dt << "', lang='" << lang << "', pos=" << pos << ", buf='" << ((pos < hdr.size()) ? hdr.substr(pos,hdr.size()) : "") << "'");
417
418 /* if we found anything we might use, try it. */
419 if (*lang != '\0' && !invalid_byte)
420 return true;
421 }
422 return false;
423 }
424
425 bool
426 TemplateFile::loadFor(HttpRequest *request)
427 {
428 String hdr;
429
430 #if USE_ERR_LOCALES
431 if (loaded()) // already loaded?
432 return true;
433
434 if (!request || !request->header.getList(HDR_ACCEPT_LANGUAGE, &hdr) )
435 return false;
436
437 char lang[256];
438 size_t pos = 0; // current parsing position in header string
439
440 debugs(4, 6, HERE << "Testing Header: '" << hdr << "'");
441
442 while ( strHdrAcptLangGetItem(hdr, lang, 256, pos) ) {
443
444 /* wildcard uses the configured default language */
445 if (lang[0] == '*' && lang[1] == '\0') {
446 debugs(4, 6, HERE << "Found language '" << lang << "'. Using configured default.");
447 return false;
448 }
449
450 debugs(4, 6, HERE << "Found language '" << lang << "', testing for available template");
451
452 if (tryLoadTemplate(lang)) {
453 /* store the language we found for the Content-Language reply header */
454 errLanguage = lang;
455 break;
456 } else if (Config.errorLogMissingLanguages) {
457 debugs(4, DBG_IMPORTANT, "WARNING: Error Pages Missing Language: " << lang);
458 }
459 }
460 #endif
461
462 return loaded();
463 }
464
465 /// \ingroup ErrorPageInternal
466 static ErrorDynamicPageInfo *
467 errorDynamicPageInfoCreate(int id, const char *page_name)
468 {
469 ErrorDynamicPageInfo *info = new ErrorDynamicPageInfo;
470 info->id = id;
471 info->page_name = xstrdup(page_name);
472 info->page_redirect = static_cast<http_status>(atoi(page_name));
473
474 /* WARNING on redirection status:
475 * 2xx are permitted, but not documented officially.
476 * - might be useful for serving static files (PAC etc) in special cases
477 * 3xx require a URL suitable for Location: header.
478 * - the current design does not allow for a Location: URI as well as a local file template
479 * although this possibility is explicitly permitted in the specs.
480 * 4xx-5xx require a local file template.
481 * - sending Location: on these codes with no body is invalid by the specs.
482 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
483 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
484 */
485 if (info->page_redirect == HTTP_STATUS_NONE)
486 ; // special case okay.
487 else if (info->page_redirect < 200 || info->page_redirect > 599) {
488 // out of range
489 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " is not valid on '" << page_name << "'");
490 self_destruct();
491 } else if ( /* >= 200 && */ info->page_redirect < 300 && strchr(&(page_name[4]), ':')) {
492 // 2xx require a local template file
493 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " requires a template on '" << page_name << "'");
494 self_destruct();
495 } else if (info->page_redirect >= 300 && info->page_redirect <= 399 && !strchr(&(page_name[4]), ':')) {
496 // 3xx require an absolute URL
497 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " requires a URL on '" << page_name << "'");
498 self_destruct();
499 } else if (info->page_redirect >= 400 /* && <= 599 */ && strchr(&(page_name[4]), ':')) {
500 // 4xx/5xx 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 }
504 // else okay.
505
506 return info;
507 }
508
509 /// \ingroup ErrorPageInternal
510 static void
511 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo * info)
512 {
513 assert(info);
514 safe_free(info->page_name);
515 delete info;
516 }
517
518 /// \ingroup ErrorPageInternal
519 static int
520 errorPageId(const char *page_name)
521 {
522 for (int i = 0; i < ERR_MAX; i++) {
523 if (strcmp(err_type_str[i], page_name) == 0)
524 return i;
525 }
526
527 for (size_t j = 0; j < ErrorDynamicPages.size(); j++) {
528 if (strcmp(ErrorDynamicPages.items[j]->page_name, page_name) == 0)
529 return j + ERR_MAX;
530 }
531
532 return ERR_NONE;
533 }
534
535 err_type
536 errorReservePageId(const char *page_name)
537 {
538 ErrorDynamicPageInfo *info;
539 int id = errorPageId(page_name);
540
541 if (id == ERR_NONE) {
542 info = errorDynamicPageInfoCreate(ERR_MAX + ErrorDynamicPages.size(), page_name);
543 ErrorDynamicPages.push_back(info);
544 id = info->id;
545 }
546
547 return (err_type)id;
548 }
549
550 /// \ingroup ErrorPageInternal
551 const char *
552 errorPageName(int pageId)
553 {
554 if (pageId >= ERR_NONE && pageId < ERR_MAX) /* common case */
555 return err_type_str[pageId];
556
557 if (pageId >= ERR_MAX && pageId - ERR_MAX < (ssize_t)ErrorDynamicPages.size())
558 return ErrorDynamicPages.items[pageId - ERR_MAX]->page_name;
559
560 return "ERR_UNKNOWN"; /* should not happen */
561 }
562
563 ErrorState::ErrorState(err_type t, http_status status, HttpRequest * req) :
564 type(t),
565 page_id(t),
566 err_language(NULL),
567 httpStatus(status),
568 #if USE_AUTH
569 auth_user_request (NULL),
570 #endif
571 request(NULL),
572 url(NULL),
573 xerrno(0),
574 port(0),
575 dnsError(),
576 ttl(0),
577 src_addr(),
578 redirect_url(NULL),
579 callback(NULL),
580 callback_data(NULL),
581 request_hdrs(NULL),
582 err_msg(NULL)
583 #if USE_SSL
584 , detail(NULL)
585 #endif
586 {
587 memset(&flags, 0, sizeof(flags));
588 memset(&ftp, 0, sizeof(ftp));
589
590 if (page_id >= ERR_MAX && ErrorDynamicPages.items[page_id - ERR_MAX]->page_redirect != HTTP_STATUS_NONE)
591 httpStatus = ErrorDynamicPages.items[page_id - ERR_MAX]->page_redirect;
592
593 if (req != NULL) {
594 request = HTTPMSGLOCK(req);
595 src_addr = req->client_addr;
596 request->detailError(type, ERR_DETAIL_NONE);
597 }
598 }
599
600 void
601 errorAppendEntry(StoreEntry * entry, ErrorState * err)
602 {
603 assert(entry->mem_obj != NULL);
604 assert (entry->isEmpty());
605 debugs(4, 4, "Creating an error page for entry " << entry <<
606 " with errorstate " << err <<
607 " page id " << err->page_id);
608
609 if (entry->store_status != STORE_PENDING) {
610 debugs(4, 2, "Skipping error page due to store_status: " << entry->store_status);
611 /*
612 * If the entry is not STORE_PENDING, then no clients
613 * care about it, and we don't need to generate an
614 * error message
615 */
616 assert(EBIT_TEST(entry->flags, ENTRY_ABORTED));
617 assert(entry->mem_obj->nclients == 0);
618 delete err;
619 return;
620 }
621
622 if (err->page_id == TCP_RESET) {
623 if (err->request) {
624 debugs(4, 2, "RSTing this reply");
625 err->request->flags.setResetTCP();
626 }
627 }
628
629 entry->lock();
630 entry->buffer();
631 entry->replaceHttpReply( err->BuildHttpReply() );
632 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
633 entry->flush();
634 entry->complete();
635 entry->negativeCache();
636 entry->releaseRequest();
637 entry->unlock();
638 delete err;
639 }
640
641 void
642 errorSend(const Comm::ConnectionPointer &conn, ErrorState * err)
643 {
644 HttpReply *rep;
645 debugs(4, 3, HERE << conn << ", err=" << err);
646 assert(Comm::IsConnOpen(conn));
647 /*
648 * ugh, this is how we make sure error codes get back to
649 * the client side for logging and error tracking.
650 */
651
652 if (err->request)
653 err->request->detailError(err->type, err->xerrno);
654
655 /* moved in front of errorBuildBuf @?@ */
656 err->flags.flag_cbdata = 1;
657
658 rep = err->BuildHttpReply();
659
660 MemBuf *mb = rep->pack();
661 AsyncCall::Pointer call = commCbCall(78, 5, "errorSendComplete",
662 CommIoCbPtrFun(&errorSendComplete, err));
663 Comm::Write(conn, mb, call);
664 delete mb;
665
666 delete rep;
667 }
668
669 /**
670 \ingroup ErrorPageAPI
671 *
672 * Called by commHandleWrite() after data has been written
673 * to the client socket.
674 *
675 \note If there is a callback, the callback is responsible for
676 * closing the FD, otherwise we do it ourselves.
677 */
678 static void
679 errorSendComplete(const Comm::ConnectionPointer &conn, char *bufnotused, size_t size, comm_err_t errflag, int xerrno, void *data)
680 {
681 ErrorState *err = static_cast<ErrorState *>(data);
682 debugs(4, 3, HERE << conn << ", size=" << size);
683
684 if (errflag != COMM_ERR_CLOSING) {
685 if (err->callback) {
686 debugs(4, 3, "errorSendComplete: callback");
687 err->callback(conn->fd, err->callback_data, size);
688 } else {
689 debugs(4, 3, "errorSendComplete: comm_close");
690 conn->close();
691 }
692 }
693
694 delete err;
695 }
696
697 ErrorState::~ErrorState()
698 {
699 HTTPMSGUNLOCK(request);
700 safe_free(redirect_url);
701 safe_free(url);
702 safe_free(request_hdrs);
703 wordlistDestroy(&ftp.server_msg);
704 safe_free(ftp.request);
705 safe_free(ftp.reply);
706 #if USE_AUTH
707 auth_user_request = NULL;
708 #endif
709 safe_free(err_msg);
710 #if USE_ERR_LOCALES
711 if (err_language != Config.errorDefaultLanguage)
712 #endif
713 safe_free(err_language);
714 #if USE_SSL
715 delete detail;
716 #endif
717 }
718
719 int
720 ErrorState::Dump(MemBuf * mb)
721 {
722 MemBuf str;
723 char ntoabuf[MAX_IPSTRLEN];
724
725 str.reset();
726 /* email subject line */
727 str.Printf("CacheErrorInfo - %s", errorPageName(type));
728 mb->Printf("?subject=%s", rfc1738_escape_part(str.buf));
729 str.reset();
730 /* email body */
731 str.Printf("CacheHost: %s\r\n", getMyHostname());
732 /* - Err Msgs */
733 str.Printf("ErrPage: %s\r\n", errorPageName(type));
734
735 if (xerrno) {
736 str.Printf("Err: (%d) %s\r\n", xerrno, strerror(xerrno));
737 } else {
738 str.Printf("Err: [none]\r\n");
739 }
740 #if USE_AUTH
741 if (auth_user_request->denyMessage())
742 str.Printf("Auth ErrMsg: %s\r\n", auth_user_request->denyMessage());
743 #endif
744 if (dnsError.size() > 0)
745 str.Printf("DNS ErrMsg: %s\r\n", dnsError.termedBuf());
746
747 /* - TimeStamp */
748 str.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime));
749
750 /* - IP stuff */
751 str.Printf("ClientIP: %s\r\n", src_addr.NtoA(ntoabuf,MAX_IPSTRLEN));
752
753 if (request && request->hier.host[0] != '\0') {
754 str.Printf("ServerIP: %s\r\n", request->hier.host);
755 }
756
757 str.Printf("\r\n");
758 /* - HTTP stuff */
759 str.Printf("HTTP Request:\r\n");
760
761 if (NULL != request) {
762 Packer pck;
763 String urlpath_or_slash;
764
765 if (request->urlpath.size() != 0)
766 urlpath_or_slash = request->urlpath;
767 else
768 urlpath_or_slash = "/";
769
770 str.Printf("%s " SQUIDSTRINGPH " %s/%d.%d\n",
771 RequestMethodStr(request->method),
772 SQUIDSTRINGPRINT(urlpath_or_slash),
773 AnyP::ProtocolType_str[request->http_ver.protocol],
774 request->http_ver.major, request->http_ver.minor);
775 packerToMemInit(&pck, &str);
776 request->header.packInto(&pck);
777 packerClean(&pck);
778 }
779
780 str.Printf("\r\n");
781 /* - FTP stuff */
782
783 if (ftp.request) {
784 str.Printf("FTP Request: %s\r\n", ftp.request);
785 str.Printf("FTP Reply: %s\r\n", (ftp.reply? ftp.reply:"[none]"));
786 str.Printf("FTP Msg: ");
787 wordlistCat(ftp.server_msg, &str);
788 str.Printf("\r\n");
789 }
790
791 str.Printf("\r\n");
792 mb->Printf("&body=%s", rfc1738_escape_part(str.buf));
793 str.clean();
794 return 0;
795 }
796
797 /// \ingroup ErrorPageInternal
798 #define CVT_BUF_SZ 512
799
800 const char *
801 ErrorState::Convert(char token, bool building_deny_info_url, bool allowRecursion)
802 {
803 static MemBuf mb;
804 const char *p = NULL; /* takes priority over mb if set */
805 int do_quote = 1;
806 int no_urlescape = 0; /* if true then item is NOT to be further URL-encoded */
807 char ntoabuf[MAX_IPSTRLEN];
808
809 mb.reset();
810
811 switch (token) {
812
813 case 'a':
814 #if USE_AUTH
815 if (request && request->auth_user_request != NULL)
816 p = request->auth_user_request->username();
817 if (!p)
818 #endif
819 p = "-";
820 break;
821
822 case 'b':
823 mb.Printf("%d", getMyPort());
824 break;
825
826 case 'B':
827 if (building_deny_info_url) break;
828 p = request ? ftpUrlWith2f(request) : "[no URL]";
829 break;
830
831 case 'c':
832 if (building_deny_info_url) break;
833 p = errorPageName(type);
834 break;
835
836 case 'D':
837 if (!allowRecursion)
838 p = "%D"; // if recursion is not allowed, do not convert
839 #if USE_SSL
840 // currently only SSL error details implemented
841 else if (detail) {
842 detail->useRequest(request);
843 const String &errDetail = detail->toString();
844 if (errDetail.defined()) {
845 MemBuf *detail_mb = ConvertText(errDetail.termedBuf(), false);
846 mb.append(detail_mb->content(), detail_mb->contentSize());
847 delete detail_mb;
848 do_quote = 0;
849 }
850 }
851 #endif
852 if (!mb.contentSize())
853 mb.Printf("[No Error Detail]");
854 break;
855
856 case 'e':
857 mb.Printf("%d", xerrno);
858 break;
859
860 case 'E':
861 if (xerrno)
862 mb.Printf("(%d) %s", xerrno, strerror(xerrno));
863 else
864 mb.Printf("[No Error]");
865 break;
866
867 case 'f':
868 if (building_deny_info_url) break;
869 /* FTP REQUEST LINE */
870 if (ftp.request)
871 p = ftp.request;
872 else
873 p = "nothing";
874 break;
875
876 case 'F':
877 if (building_deny_info_url) break;
878 /* FTP REPLY LINE */
879 if (ftp.reply)
880 p = ftp.reply;
881 else
882 p = "nothing";
883 break;
884
885 case 'g':
886 if (building_deny_info_url) break;
887 /* FTP SERVER RESPONSE */
888 if (ftp.listing) {
889 mb.append(ftp.listing->content(), ftp.listing->contentSize());
890 do_quote = 0;
891 } else if (ftp.server_msg) {
892 wordlistCat(ftp.server_msg, &mb);
893 }
894 break;
895
896 case 'h':
897 mb.Printf("%s", getMyHostname());
898 break;
899
900 case 'H':
901 if (request) {
902 if (request->hier.host[0] != '\0') // if non-empty string.
903 p = request->hier.host;
904 else
905 p = request->GetHost();
906 } else if (!building_deny_info_url)
907 p = "[unknown host]";
908 break;
909
910 case 'i':
911 mb.Printf("%s", src_addr.NtoA(ntoabuf,MAX_IPSTRLEN));
912 break;
913
914 case 'I':
915 if (request && request->hier.tcpServer != NULL)
916 p = request->hier.tcpServer->remote.NtoA(ntoabuf,MAX_IPSTRLEN);
917 else if (!building_deny_info_url)
918 p = "[unknown]";
919 break;
920
921 case 'l':
922 if (building_deny_info_url) break;
923 mb.append(error_stylesheet.content(), error_stylesheet.contentSize());
924 do_quote = 0;
925 break;
926
927 case 'L':
928 if (building_deny_info_url) break;
929 if (Config.errHtmlText) {
930 mb.Printf("%s", Config.errHtmlText);
931 do_quote = 0;
932 } else
933 p = "[not available]";
934 break;
935
936 case 'm':
937 if (building_deny_info_url) break;
938 #if USE_AUTH
939 p = auth_user_request->denyMessage("[not available]");
940 #else
941 p = "-";
942 #endif
943 break;
944
945 case 'M':
946 if (request)
947 p = RequestMethodStr(request->method);
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 = AnyP::ProtocolType_str[request->protocol];
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 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,0, "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_status status = HTTP_MOVED_TEMPORARILY;
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 != METHOD_GET && request->method != METHOD_HEAD && request->http_ver >= HttpVersion(1,1))
1168 status = HTTP_TEMPORARY_REDIRECT;
1169 }
1170
1171 rep->setHeaders(status, NULL, "text/html", 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", 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 return rep;
1224 }
1225
1226 MemBuf *
1227 ErrorState::BuildContent()
1228 {
1229 const char *m = NULL;
1230
1231 assert(page_id > ERR_NONE && page_id < error_page_count);
1232
1233 #if USE_ERR_LOCALES
1234 ErrorPageFile *localeTmpl = NULL;
1235
1236 /** error_directory option in squid.conf overrides translations.
1237 * Custom errors are always found either in error_directory or the templates directory.
1238 * Otherwise locate the Accept-Language header
1239 */
1240 if (!Config.errorDirectory && page_id < ERR_MAX) {
1241 if (err_language && err_language != Config.errorDefaultLanguage)
1242 safe_free(err_language);
1243
1244 localeTmpl = new ErrorPageFile(err_type_str[page_id], static_cast<err_type>(page_id));
1245 if (localeTmpl->loadFor(request)) {
1246 m = localeTmpl->text();
1247 assert(localeTmpl->language());
1248 err_language = xstrdup(localeTmpl->language());
1249 }
1250 }
1251 #endif /* USE_ERR_LOCALES */
1252
1253 /** \par
1254 * If client-specific error templates are not enabled or available.
1255 * fall back to the old style squid.conf settings.
1256 */
1257 if (!m) {
1258 m = error_text[page_id];
1259 #if USE_ERR_LOCALES
1260 if (!Config.errorDirectory)
1261 err_language = Config.errorDefaultLanguage;
1262 #endif
1263 debugs(4, 2, HERE << "No existing error page language negotiated for " << errorPageName(page_id) << ". Using default error file.");
1264 }
1265
1266 MemBuf *result = ConvertText(m, true);
1267 #if USE_ERR_LOCALES
1268 if (localeTmpl)
1269 delete localeTmpl;
1270 #endif
1271 return result;
1272 }
1273
1274 MemBuf *ErrorState::ConvertText(const char *text, bool allowRecursion)
1275 {
1276 MemBuf *content = new MemBuf;
1277 const char *p;
1278 const char *m = text;
1279 assert(m);
1280 content->init();
1281
1282 while ((p = strchr(m, '%'))) {
1283 content->append(m, p - m); /* copy */
1284 const char *t = Convert(*++p, false, allowRecursion); /* convert */
1285 content->Printf("%s", t); /* copy */
1286 m = p + 1; /* advance */
1287 }
1288
1289 if (*m)
1290 content->Printf("%s", m); /* copy tail */
1291
1292 assert((size_t)content->contentSize() == strlen(content->content()));
1293
1294 return content;
1295 }