]> git.ipfire.org Git - thirdparty/squid.git/blob - src/errorpage.cc
Tightened StoreEntry locking. Fixed entry touching and synchronization code:
[thirdparty/squid.git] / src / errorpage.cc
1 /*
2 * DEBUG: section 04 Error Generation
3 * AUTHOR: Duane Wessels
4 *
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
7 *
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
16 *
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
21 *
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
30 *
31 */
32 #include "squid.h"
33 #include "cache_cf.h"
34 #include "comm/Connection.h"
35 #include "comm/Write.h"
36 #include "disk.h"
37 #include "err_detail_type.h"
38 #include "errorpage.h"
39 #include "ftp.h"
40 #include "Store.h"
41 #include "html_quote.h"
42 #include "HttpHeaderTools.h"
43 #include "HttpReply.h"
44 #include "HttpRequest.h"
45 #include "MemObject.h"
46 #include "fde.h"
47 #include "MemBuf.h"
48 #include "rfc1738.h"
49 #include "SquidConfig.h"
50 #include "URL.h"
51 #include "URLScheme.h"
52 #include "URL.h"
53 #include "tools.h"
54 #include "wordlist.h"
55 #if USE_AUTH
56 #include "auth/UserRequest.h"
57 #endif
58 #include "SquidTime.h"
59 #if USE_SSL
60 #include "ssl/ErrorDetailManager.h"
61 #endif
62
63 /**
64 \defgroup ErrorPageInternal Error Page Internals
65 \ingroup ErrorPageAPI
66 *
67 \section Abstract Abstract:
68 * These routines are used to generate error messages to be
69 * sent to clients. The error type is used to select between
70 * the various message formats. (formats are stored in the
71 * Config.errorDirectory)
72 */
73
74 #if !defined(DEFAULT_SQUID_ERROR_DIR)
75 /** Where to look for errors if config path fails.
76 \note Please use ./configure --datadir=/path instead of patching
77 */
78 #define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
79 #endif
80
81 /// \ingroup ErrorPageInternal
82 CBDATA_CLASS_INIT(ErrorState);
83
84 /* local types */
85
86 /// \ingroup ErrorPageInternal
87 typedef struct {
88 int id;
89 char *page_name;
90 Http::StatusCode page_redirect;
91 } ErrorDynamicPageInfo;
92
93 /* local constant and vars */
94
95 /**
96 \ingroup ErrorPageInternal
97 *
98 \note hard coded error messages are not appended with %S
99 * automagically to give you more control on the format
100 */
101 static const struct {
102 int type; /* and page_id */
103 const char *text;
104 }
105
106 error_hard_text[] = {
107
108 {
109 ERR_SQUID_SIGNATURE,
110 "\n<br>\n"
111 "<hr>\n"
112 "<div id=\"footer\">\n"
113 "Generated %T by %h (%s)\n"
114 "</div>\n"
115 "</body></html>\n"
116 },
117 {
118 TCP_RESET,
119 "reset"
120 }
121 };
122
123 /// \ingroup ErrorPageInternal
124 static Vector<ErrorDynamicPageInfo *> ErrorDynamicPages;
125
126 /* local prototypes */
127
128 /// \ingroup ErrorPageInternal
129 static const int error_hard_text_count = sizeof(error_hard_text) / sizeof(*error_hard_text);
130
131 /// \ingroup ErrorPageInternal
132 static char **error_text = NULL;
133
134 /// \ingroup ErrorPageInternal
135 static int error_page_count = 0;
136
137 /// \ingroup ErrorPageInternal
138 static MemBuf error_stylesheet;
139
140 static const char *errorFindHardText(err_type type);
141 static ErrorDynamicPageInfo *errorDynamicPageInfoCreate(int id, const char *page_name);
142 static void errorDynamicPageInfoDestroy(ErrorDynamicPageInfo * info);
143 static IOCB errorSendComplete;
144
145 /// \ingroup ErrorPageInternal
146 /// manages an error page template
147 class ErrorPageFile: public TemplateFile
148 {
149 public:
150 ErrorPageFile(const char *name, const err_type code): TemplateFile(name,code) { textBuf.init();}
151
152 /// The template text data read from disk
153 const char *text() { return textBuf.content(); }
154
155 private:
156 /// stores the data read from disk to a local buffer
157 virtual bool parse(const char *buf, int len, bool eof) {
158 if (len)
159 textBuf.append(buf, len);
160 return true;
161 }
162
163 MemBuf textBuf; ///< A buffer to store the error page
164 };
165
166 /// \ingroup ErrorPageInternal
167 err_type &operator++ (err_type &anErr)
168 {
169 int tmp = (int)anErr;
170 anErr = (err_type)(++tmp);
171 return anErr;
172 }
173
174 /// \ingroup ErrorPageInternal
175 int operator - (err_type const &anErr, err_type const &anErr2)
176 {
177 return (int)anErr - (int)anErr2;
178 }
179
180 void
181 errorInitialize(void)
182 {
183 err_type i;
184 const char *text;
185 error_page_count = ERR_MAX + ErrorDynamicPages.size();
186 error_text = static_cast<char **>(xcalloc(error_page_count, sizeof(char *)));
187
188 for (i = ERR_NONE, ++i; i < error_page_count; ++i) {
189 safe_free(error_text[i]);
190
191 if ((text = errorFindHardText(i))) {
192 /**\par
193 * Index any hard-coded error text into defaults.
194 */
195 error_text[i] = xstrdup(text);
196
197 } else if (i < ERR_MAX) {
198 /**\par
199 * Index precompiled fixed template files from one of two sources:
200 * (a) default language translation directory (error_default_language)
201 * (b) admin specified custom directory (error_directory)
202 */
203 ErrorPageFile errTmpl(err_type_str[i], i);
204 error_text[i] = errTmpl.loadDefault() ? xstrdup(errTmpl.text()) : NULL;
205 } else {
206 /** \par
207 * Index any unknown file names used by deny_info.
208 */
209 ErrorDynamicPageInfo *info = ErrorDynamicPages.items[i - ERR_MAX];
210 assert(info && info->id == i && info->page_name);
211
212 const char *pg = info->page_name;
213 if (info->page_redirect != Http::scNone)
214 pg = info->page_name +4;
215
216 if (strchr(pg, ':') == NULL) {
217 /** But only if they are not redirection URL. */
218 ErrorPageFile errTmpl(pg, ERR_MAX);
219 error_text[i] = errTmpl.loadDefault() ? xstrdup(errTmpl.text()) : NULL;
220 }
221 }
222 }
223
224 error_stylesheet.reset();
225
226 // look for and load stylesheet into global MemBuf for it.
227 if (Config.errorStylesheet) {
228 ErrorPageFile tmpl("StylesSheet", ERR_MAX);
229 tmpl.loadFromFile(Config.errorStylesheet);
230 error_stylesheet.Printf("%s",tmpl.text());
231 }
232
233 #if USE_SSL
234 Ssl::errorDetailInitialize();
235 #endif
236 }
237
238 void
239 errorClean(void)
240 {
241 if (error_text) {
242 int i;
243
244 for (i = ERR_NONE + 1; i < error_page_count; ++i)
245 safe_free(error_text[i]);
246
247 safe_free(error_text);
248 }
249
250 while (ErrorDynamicPages.size())
251 errorDynamicPageInfoDestroy(ErrorDynamicPages.pop_back());
252
253 error_page_count = 0;
254
255 #if USE_SSL
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.items[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.items[pageId - ERR_MAX]->page_name;
567
568 return "ERR_UNKNOWN"; /* should not happen */
569 }
570
571 ErrorState::ErrorState(err_type t, Http::StatusCode status, HttpRequest * req) :
572 type(t),
573 page_id(t),
574 err_language(NULL),
575 httpStatus(status),
576 #if USE_AUTH
577 auth_user_request (NULL),
578 #endif
579 request(NULL),
580 url(NULL),
581 xerrno(0),
582 port(0),
583 dnsError(),
584 ttl(0),
585 src_addr(),
586 redirect_url(NULL),
587 callback(NULL),
588 callback_data(NULL),
589 request_hdrs(NULL),
590 err_msg(NULL),
591 #if USE_SSL
592 detail(NULL),
593 #endif
594 detailCode(ERR_DETAIL_NONE)
595 {
596 memset(&ftp, 0, sizeof(ftp));
597
598 if (page_id >= ERR_MAX && ErrorDynamicPages.items[page_id - ERR_MAX]->page_redirect != Http::scNone)
599 httpStatus = ErrorDynamicPages.items[page_id - ERR_MAX]->page_redirect;
600
601 if (req != NULL) {
602 request = req;
603 HTTPMSGLOCK(request);
604 src_addr = req->client_addr;
605 }
606 }
607
608 void
609 errorAppendEntry(StoreEntry * entry, ErrorState * err)
610 {
611 assert(entry->mem_obj != NULL);
612 assert (entry->isEmpty());
613 debugs(4, 4, "Creating an error page for entry " << entry <<
614 " with errorstate " << err <<
615 " page id " << err->page_id);
616
617 if (entry->store_status != STORE_PENDING) {
618 debugs(4, 2, "Skipping error page due to store_status: " << entry->store_status);
619 /*
620 * If the entry is not STORE_PENDING, then no clients
621 * care about it, and we don't need to generate an
622 * error message
623 */
624 assert(EBIT_TEST(entry->flags, ENTRY_ABORTED));
625 assert(entry->mem_obj->nclients == 0);
626 delete err;
627 return;
628 }
629
630 if (err->page_id == TCP_RESET) {
631 if (err->request) {
632 debugs(4, 2, "RSTing this reply");
633 err->request->flags.resetTcp = true;
634 }
635 }
636
637 entry->lock("errorAppendEntry");
638 entry->buffer();
639 entry->replaceHttpReply( err->BuildHttpReply() );
640 entry->flush();
641 entry->complete();
642 entry->negativeCache();
643 entry->releaseRequest();
644 entry->unlock("errorAppendEntry");
645 delete err;
646 }
647
648 void
649 errorSend(const Comm::ConnectionPointer &conn, ErrorState * err)
650 {
651 HttpReply *rep;
652 debugs(4, 3, HERE << conn << ", err=" << err);
653 assert(Comm::IsConnOpen(conn));
654
655 rep = err->BuildHttpReply();
656
657 MemBuf *mb = rep->pack();
658 AsyncCall::Pointer call = commCbCall(78, 5, "errorSendComplete",
659 CommIoCbPtrFun(&errorSendComplete, err));
660 Comm::Write(conn, mb, call);
661 delete mb;
662
663 delete rep;
664 }
665
666 /**
667 \ingroup ErrorPageAPI
668 *
669 * Called by commHandleWrite() after data has been written
670 * to the client socket.
671 *
672 \note If there is a callback, the callback is responsible for
673 * closing the FD, otherwise we do it ourselves.
674 */
675 static void
676 errorSendComplete(const Comm::ConnectionPointer &conn, char *bufnotused, size_t size, comm_err_t errflag, int xerrno, void *data)
677 {
678 ErrorState *err = static_cast<ErrorState *>(data);
679 debugs(4, 3, HERE << conn << ", size=" << size);
680
681 if (errflag != COMM_ERR_CLOSING) {
682 if (err->callback) {
683 debugs(4, 3, "errorSendComplete: callback");
684 err->callback(conn->fd, err->callback_data, size);
685 } else {
686 debugs(4, 3, "errorSendComplete: comm_close");
687 conn->close();
688 }
689 }
690
691 delete err;
692 }
693
694 ErrorState::~ErrorState()
695 {
696 HTTPMSGUNLOCK(request);
697 safe_free(redirect_url);
698 safe_free(url);
699 safe_free(request_hdrs);
700 wordlistDestroy(&ftp.server_msg);
701 safe_free(ftp.request);
702 safe_free(ftp.reply);
703 #if USE_AUTH
704 auth_user_request = NULL;
705 #endif
706 safe_free(err_msg);
707 #if USE_ERR_LOCALES
708 if (err_language != Config.errorDefaultLanguage)
709 #endif
710 safe_free(err_language);
711 #if USE_SSL
712 delete detail;
713 #endif
714 }
715
716 int
717 ErrorState::Dump(MemBuf * mb)
718 {
719 MemBuf str;
720 char ntoabuf[MAX_IPSTRLEN];
721
722 str.reset();
723 /* email subject line */
724 str.Printf("CacheErrorInfo - %s", errorPageName(type));
725 mb->Printf("?subject=%s", rfc1738_escape_part(str.buf));
726 str.reset();
727 /* email body */
728 str.Printf("CacheHost: %s\r\n", getMyHostname());
729 /* - Err Msgs */
730 str.Printf("ErrPage: %s\r\n", errorPageName(type));
731
732 if (xerrno) {
733 str.Printf("Err: (%d) %s\r\n", xerrno, strerror(xerrno));
734 } else {
735 str.Printf("Err: [none]\r\n");
736 }
737 #if USE_AUTH
738 if (auth_user_request->denyMessage())
739 str.Printf("Auth ErrMsg: %s\r\n", auth_user_request->denyMessage());
740 #endif
741 if (dnsError.size() > 0)
742 str.Printf("DNS ErrMsg: %s\r\n", dnsError.termedBuf());
743
744 /* - TimeStamp */
745 str.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime));
746
747 /* - IP stuff */
748 str.Printf("ClientIP: %s\r\n", src_addr.NtoA(ntoabuf,MAX_IPSTRLEN));
749
750 if (request && request->hier.host[0] != '\0') {
751 str.Printf("ServerIP: %s\r\n", request->hier.host);
752 }
753
754 str.Printf("\r\n");
755 /* - HTTP stuff */
756 str.Printf("HTTP Request:\r\n");
757
758 if (NULL != request) {
759 Packer pck;
760 String urlpath_or_slash;
761
762 if (request->urlpath.size() != 0)
763 urlpath_or_slash = request->urlpath;
764 else
765 urlpath_or_slash = "/";
766
767 str.Printf("%s " SQUIDSTRINGPH " %s/%d.%d\n",
768 RequestMethodStr(request->method),
769 SQUIDSTRINGPRINT(urlpath_or_slash),
770 AnyP::ProtocolType_str[request->http_ver.protocol],
771 request->http_ver.major, request->http_ver.minor);
772 packerToMemInit(&pck, &str);
773 request->header.packInto(&pck);
774 packerClean(&pck);
775 }
776
777 str.Printf("\r\n");
778 /* - FTP stuff */
779
780 if (ftp.request) {
781 str.Printf("FTP Request: %s\r\n", ftp.request);
782 str.Printf("FTP Reply: %s\r\n", (ftp.reply? ftp.reply:"[none]"));
783 str.Printf("FTP Msg: ");
784 wordlistCat(ftp.server_msg, &str);
785 str.Printf("\r\n");
786 }
787
788 str.Printf("\r\n");
789 mb->Printf("&body=%s", rfc1738_escape_part(str.buf));
790 str.clean();
791 return 0;
792 }
793
794 /// \ingroup ErrorPageInternal
795 #define CVT_BUF_SZ 512
796
797 const char *
798 ErrorState::Convert(char token, bool building_deny_info_url, bool allowRecursion)
799 {
800 static MemBuf mb;
801 const char *p = NULL; /* takes priority over mb if set */
802 int do_quote = 1;
803 int no_urlescape = 0; /* if true then item is NOT to be further URL-encoded */
804 char ntoabuf[MAX_IPSTRLEN];
805
806 mb.reset();
807
808 switch (token) {
809
810 case 'a':
811 #if USE_AUTH
812 if (request && request->auth_user_request != NULL)
813 p = request->auth_user_request->username();
814 if (!p)
815 #endif
816 p = "-";
817 break;
818
819 case 'b':
820 mb.Printf("%d", getMyPort());
821 break;
822
823 case 'B':
824 if (building_deny_info_url) break;
825 p = request ? ftpUrlWith2f(request) : "[no URL]";
826 break;
827
828 case 'c':
829 if (building_deny_info_url) break;
830 p = errorPageName(type);
831 break;
832
833 case 'D':
834 if (!allowRecursion)
835 p = "%D"; // if recursion is not allowed, do not convert
836 #if USE_SSL
837 // currently only SSL error details implemented
838 else if (detail) {
839 detail->useRequest(request);
840 const String &errDetail = detail->toString();
841 if (errDetail.defined()) {
842 MemBuf *detail_mb = ConvertText(errDetail.termedBuf(), false);
843 mb.append(detail_mb->content(), detail_mb->contentSize());
844 delete detail_mb;
845 do_quote = 0;
846 }
847 }
848 #endif
849 if (!mb.contentSize())
850 mb.Printf("[No Error Detail]");
851 break;
852
853 case 'e':
854 mb.Printf("%d", xerrno);
855 break;
856
857 case 'E':
858 if (xerrno)
859 mb.Printf("(%d) %s", xerrno, strerror(xerrno));
860 else
861 mb.Printf("[No Error]");
862 break;
863
864 case 'f':
865 if (building_deny_info_url) break;
866 /* FTP REQUEST LINE */
867 if (ftp.request)
868 p = ftp.request;
869 else
870 p = "nothing";
871 break;
872
873 case 'F':
874 if (building_deny_info_url) break;
875 /* FTP REPLY LINE */
876 if (ftp.reply)
877 p = ftp.reply;
878 else
879 p = "nothing";
880 break;
881
882 case 'g':
883 if (building_deny_info_url) break;
884 /* FTP SERVER RESPONSE */
885 if (ftp.listing) {
886 mb.append(ftp.listing->content(), ftp.listing->contentSize());
887 do_quote = 0;
888 } else if (ftp.server_msg) {
889 wordlistCat(ftp.server_msg, &mb);
890 }
891 break;
892
893 case 'h':
894 mb.Printf("%s", getMyHostname());
895 break;
896
897 case 'H':
898 if (request) {
899 if (request->hier.host[0] != '\0') // if non-empty string.
900 p = request->hier.host;
901 else
902 p = request->GetHost();
903 } else if (!building_deny_info_url)
904 p = "[unknown host]";
905 break;
906
907 case 'i':
908 mb.Printf("%s", src_addr.NtoA(ntoabuf,MAX_IPSTRLEN));
909 break;
910
911 case 'I':
912 if (request && request->hier.tcpServer != NULL)
913 p = request->hier.tcpServer->remote.NtoA(ntoabuf,MAX_IPSTRLEN);
914 else if (!building_deny_info_url)
915 p = "[unknown]";
916 break;
917
918 case 'l':
919 if (building_deny_info_url) break;
920 mb.append(error_stylesheet.content(), error_stylesheet.contentSize());
921 do_quote = 0;
922 break;
923
924 case 'L':
925 if (building_deny_info_url) break;
926 if (Config.errHtmlText) {
927 mb.Printf("%s", Config.errHtmlText);
928 do_quote = 0;
929 } else
930 p = "[not available]";
931 break;
932
933 case 'm':
934 if (building_deny_info_url) break;
935 #if USE_AUTH
936 p = auth_user_request->denyMessage("[not available]");
937 #else
938 p = "-";
939 #endif
940 break;
941
942 case 'M':
943 if (request)
944 p = RequestMethodStr(request->method);
945 else if (!building_deny_info_url)
946 p= "[unknown method]";
947 break;
948
949 case 'o':
950 p = request ? request->extacl_message.termedBuf() : external_acl_message;
951 if (!p && !building_deny_info_url)
952 p = "[not available]";
953 break;
954
955 case 'p':
956 if (request) {
957 mb.Printf("%d", (int) request->port);
958 } else if (!building_deny_info_url) {
959 p = "[unknown port]";
960 }
961 break;
962
963 case 'P':
964 if (request) {
965 p = AnyP::ProtocolType_str[request->protocol];
966 } else if (!building_deny_info_url) {
967 p = "[unknown protocol]";
968 }
969 break;
970
971 case 'R':
972 if (building_deny_info_url) {
973 p = (request->urlpath.size() != 0 ? request->urlpath.termedBuf() : "/");
974 no_urlescape = 1;
975 break;
976 }
977 if (NULL != request) {
978 Packer pck;
979 String urlpath_or_slash;
980
981 if (request->urlpath.size() != 0)
982 urlpath_or_slash = request->urlpath;
983 else
984 urlpath_or_slash = "/";
985
986 mb.Printf("%s " SQUIDSTRINGPH " %s/%d.%d\n",
987 RequestMethodStr(request->method),
988 SQUIDSTRINGPRINT(urlpath_or_slash),
989 AnyP::ProtocolType_str[request->http_ver.protocol],
990 request->http_ver.major, request->http_ver.minor);
991 packerToMemInit(&pck, &mb);
992 request->header.packInto(&pck, true); //hide authorization data
993 packerClean(&pck);
994 } else if (request_hdrs) {
995 p = request_hdrs;
996 } else {
997 p = "[no request]";
998 }
999 break;
1000
1001 case 's':
1002 /* for backward compat we make %s show the full URL. Drop this in some future release. */
1003 if (building_deny_info_url) {
1004 p = request ? urlCanonical(request) : url;
1005 debugs(0, DBG_CRITICAL, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
1006 } else
1007 p = visible_appname_string;
1008 break;
1009
1010 case 'S':
1011 if (building_deny_info_url) {
1012 p = visible_appname_string;
1013 break;
1014 }
1015 /* signature may contain %-escapes, recursion */
1016 if (page_id != ERR_SQUID_SIGNATURE) {
1017 const int saved_id = page_id;
1018 page_id = ERR_SQUID_SIGNATURE;
1019 MemBuf *sign_mb = BuildContent();
1020 mb.Printf("%s", sign_mb->content());
1021 sign_mb->clean();
1022 delete sign_mb;
1023 page_id = saved_id;
1024 do_quote = 0;
1025 } else {
1026 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1027 p = "[%S]";
1028 }
1029 break;
1030
1031 case 't':
1032 mb.Printf("%s", Time::FormatHttpd(squid_curtime));
1033 break;
1034
1035 case 'T':
1036 mb.Printf("%s", mkrfc1123(squid_curtime));
1037 break;
1038
1039 case 'U':
1040 /* Using the fake-https version of canonical so error pages see https:// */
1041 /* even when the url-path cannot be shown as more than '*' */
1042 if (request)
1043 p = urlCanonicalFakeHttps(request);
1044 else if (url)
1045 p = url;
1046 else if (!building_deny_info_url)
1047 p = "[no URL]";
1048 break;
1049
1050 case 'u':
1051 if (request)
1052 p = urlCanonical(request);
1053 else if (url)
1054 p = url;
1055 else if (!building_deny_info_url)
1056 p = "[no URL]";
1057 break;
1058
1059 case 'w':
1060 if (Config.adminEmail)
1061 mb.Printf("%s", Config.adminEmail);
1062 else if (!building_deny_info_url)
1063 p = "[unknown]";
1064 break;
1065
1066 case 'W':
1067 if (building_deny_info_url) break;
1068 if (Config.adminEmail && Config.onoff.emailErrData)
1069 Dump(&mb);
1070 no_urlescape = 1;
1071 break;
1072
1073 case 'x':
1074 #if USE_SSL
1075 if (detail)
1076 mb.Printf("%s", detail->errorName());
1077 else
1078 #endif
1079 if (!building_deny_info_url)
1080 p = "[Unknown Error Code]";
1081 break;
1082
1083 case 'z':
1084 if (building_deny_info_url) break;
1085 if (dnsError.size() > 0)
1086 p = dnsError.termedBuf();
1087 else if (ftp.cwd_msg)
1088 p = ftp.cwd_msg;
1089 else
1090 p = "[unknown]";
1091 break;
1092
1093 case 'Z':
1094 if (building_deny_info_url) break;
1095 if (err_msg)
1096 p = err_msg;
1097 else
1098 p = "[unknown]";
1099 break;
1100
1101 case '%':
1102 p = "%";
1103 break;
1104
1105 default:
1106 mb.Printf("%%%c", token);
1107 do_quote = 0;
1108 break;
1109 }
1110
1111 if (!p)
1112 p = mb.buf; /* do not use mb after this assignment! */
1113
1114 assert(p);
1115
1116 debugs(4, 3, "errorConvert: %%" << token << " --> '" << p << "'" );
1117
1118 if (do_quote)
1119 p = html_quote(p);
1120
1121 if (building_deny_info_url && !no_urlescape)
1122 p = rfc1738_escape_part(p);
1123
1124 return p;
1125 }
1126
1127 void
1128 ErrorState::DenyInfoLocation(const char *name, HttpRequest *aRequest, MemBuf &result)
1129 {
1130 char const *m = name;
1131 char const *p = m;
1132 char const *t;
1133
1134 if (m[0] == '3')
1135 m += 4; // skip "3xx:"
1136
1137 while ((p = strchr(m, '%'))) {
1138 result.append(m, p - m); /* copy */
1139 t = Convert(*++p, true, true); /* convert */
1140 result.Printf("%s", t); /* copy */
1141 m = p + 1; /* advance */
1142 }
1143
1144 if (*m)
1145 result.Printf("%s", m); /* copy tail */
1146
1147 assert((size_t)result.contentSize() == strlen(result.content()));
1148 }
1149
1150 HttpReply *
1151 ErrorState::BuildHttpReply()
1152 {
1153 HttpReply *rep = new HttpReply;
1154 const char *name = errorPageName(page_id);
1155 /* no LMT for error pages; error pages expire immediately */
1156
1157 if (name[0] == '3' || (name[0] != '2' && name[0] != '4' && name[0] != '5' && strchr(name, ':'))) {
1158 /* Redirection */
1159 Http::StatusCode status = Http::scMovedTemporarily;
1160 // Use configured 3xx reply status if set.
1161 if (name[0] == '3')
1162 status = httpStatus;
1163 else {
1164 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1165 if (request->method != Http::METHOD_GET && request->method != Http::METHOD_HEAD && request->http_ver >= Http::ProtocolVersion(1,1))
1166 status = Http::scTemporaryRedirect;
1167 }
1168
1169 rep->setHeaders(status, NULL, "text/html", 0, 0, -1);
1170
1171 if (request) {
1172 MemBuf redirect_location;
1173 redirect_location.init();
1174 DenyInfoLocation(name, request, redirect_location);
1175 httpHeaderPutStrf(&rep->header, HDR_LOCATION, "%s", redirect_location.content() );
1176 }
1177
1178 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%d %s", httpStatus, "Access Denied");
1179 } else {
1180 MemBuf *content = BuildContent();
1181 rep->setHeaders(httpStatus, NULL, "text/html", content->contentSize(), 0, -1);
1182 /*
1183 * include some information for downstream caches. Implicit
1184 * replaceable content. This isn't quite sufficient. xerrno is not
1185 * necessarily meaningful to another system, so we really should
1186 * expand it. Additionally, we should identify ourselves. Someone
1187 * might want to know. Someone _will_ want to know OTOH, the first
1188 * X-CACHE-MISS entry should tell us who.
1189 */
1190 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%s %d", name, xerrno);
1191
1192 #if USE_ERR_LOCALES
1193 /*
1194 * If error page auto-negotiate is enabled in any way, send the Vary.
1195 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1196 * We have even better reasons though:
1197 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1198 */
1199 if (!Config.errorDirectory) {
1200 /* We 'negotiated' this ONLY from the Accept-Language. */
1201 rep->header.delById(HDR_VARY);
1202 rep->header.putStr(HDR_VARY, "Accept-Language");
1203 }
1204
1205 /* add the Content-Language header according to RFC section 14.12 */
1206 if (err_language) {
1207 rep->header.putStr(HDR_CONTENT_LANGUAGE, err_language);
1208 } else
1209 #endif /* USE_ERROR_LOCALES */
1210 {
1211 /* default templates are in English */
1212 /* language is known unless error_directory override used */
1213 if (!Config.errorDirectory)
1214 rep->header.putStr(HDR_CONTENT_LANGUAGE, "en");
1215 }
1216
1217 rep->body.setMb(content);
1218 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1219 }
1220
1221 // Make sure error codes get back to the client side for logging and
1222 // error tracking.
1223 if (request) {
1224 int edc = ERR_DETAIL_NONE; // error detail code
1225 #if USE_SSL
1226 if (detail)
1227 edc = detail->errorNo();
1228 else
1229 #endif
1230 if (detailCode)
1231 edc = detailCode;
1232 else
1233 edc = xerrno;
1234 request->detailError(type, edc);
1235 }
1236
1237 return rep;
1238 }
1239
1240 MemBuf *
1241 ErrorState::BuildContent()
1242 {
1243 const char *m = NULL;
1244
1245 assert(page_id > ERR_NONE && page_id < error_page_count);
1246
1247 #if USE_ERR_LOCALES
1248 ErrorPageFile *localeTmpl = NULL;
1249
1250 /** error_directory option in squid.conf overrides translations.
1251 * Custom errors are always found either in error_directory or the templates directory.
1252 * Otherwise locate the Accept-Language header
1253 */
1254 if (!Config.errorDirectory && page_id < ERR_MAX) {
1255 if (err_language && err_language != Config.errorDefaultLanguage)
1256 safe_free(err_language);
1257
1258 localeTmpl = new ErrorPageFile(err_type_str[page_id], static_cast<err_type>(page_id));
1259 if (localeTmpl->loadFor(request)) {
1260 m = localeTmpl->text();
1261 assert(localeTmpl->language());
1262 err_language = xstrdup(localeTmpl->language());
1263 }
1264 }
1265 #endif /* USE_ERR_LOCALES */
1266
1267 /** \par
1268 * If client-specific error templates are not enabled or available.
1269 * fall back to the old style squid.conf settings.
1270 */
1271 if (!m) {
1272 m = error_text[page_id];
1273 #if USE_ERR_LOCALES
1274 if (!Config.errorDirectory)
1275 err_language = Config.errorDefaultLanguage;
1276 #endif
1277 debugs(4, 2, HERE << "No existing error page language negotiated for " << errorPageName(page_id) << ". Using default error file.");
1278 }
1279
1280 MemBuf *result = ConvertText(m, true);
1281 #if USE_ERR_LOCALES
1282 if (localeTmpl)
1283 delete localeTmpl;
1284 #endif
1285 return result;
1286 }
1287
1288 MemBuf *ErrorState::ConvertText(const char *text, bool allowRecursion)
1289 {
1290 MemBuf *content = new MemBuf;
1291 const char *p;
1292 const char *m = text;
1293 assert(m);
1294 content->init();
1295
1296 while ((p = strchr(m, '%'))) {
1297 content->append(m, p - m); /* copy */
1298 const char *t = Convert(*++p, false, allowRecursion); /* convert */
1299 content->Printf("%s", t); /* copy */
1300 m = p + 1; /* advance */
1301 }
1302
1303 if (*m)
1304 content->Printf("%s", m); /* copy tail */
1305
1306 assert((size_t)content->contentSize() == strlen(content->content()));
1307
1308 return content;
1309 }