]> git.ipfire.org Git - thirdparty/squid.git/blob - src/errorpage.cc
Polish: update Ip::Address to follow Squid coding guidelines
[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();
638 entry->buffer();
639 entry->replaceHttpReply( err->BuildHttpReply() );
640 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
641 entry->flush();
642 entry->complete();
643 entry->negativeCache();
644 entry->releaseRequest();
645 entry->unlock();
646 delete err;
647 }
648
649 void
650 errorSend(const Comm::ConnectionPointer &conn, ErrorState * err)
651 {
652 HttpReply *rep;
653 debugs(4, 3, HERE << conn << ", err=" << err);
654 assert(Comm::IsConnOpen(conn));
655
656 rep = err->BuildHttpReply();
657
658 MemBuf *mb = rep->pack();
659 AsyncCall::Pointer call = commCbCall(78, 5, "errorSendComplete",
660 CommIoCbPtrFun(&errorSendComplete, err));
661 Comm::Write(conn, mb, call);
662 delete mb;
663
664 delete rep;
665 }
666
667 /**
668 \ingroup ErrorPageAPI
669 *
670 * Called by commHandleWrite() after data has been written
671 * to the client socket.
672 *
673 \note If there is a callback, the callback is responsible for
674 * closing the FD, otherwise we do it ourselves.
675 */
676 static void
677 errorSendComplete(const Comm::ConnectionPointer &conn, char *bufnotused, size_t size, comm_err_t errflag, int xerrno, void *data)
678 {
679 ErrorState *err = static_cast<ErrorState *>(data);
680 debugs(4, 3, HERE << conn << ", size=" << size);
681
682 if (errflag != COMM_ERR_CLOSING) {
683 if (err->callback) {
684 debugs(4, 3, "errorSendComplete: callback");
685 err->callback(conn->fd, err->callback_data, size);
686 } else {
687 debugs(4, 3, "errorSendComplete: comm_close");
688 conn->close();
689 }
690 }
691
692 delete err;
693 }
694
695 ErrorState::~ErrorState()
696 {
697 HTTPMSGUNLOCK(request);
698 safe_free(redirect_url);
699 safe_free(url);
700 safe_free(request_hdrs);
701 wordlistDestroy(&ftp.server_msg);
702 safe_free(ftp.request);
703 safe_free(ftp.reply);
704 #if USE_AUTH
705 auth_user_request = NULL;
706 #endif
707 safe_free(err_msg);
708 #if USE_ERR_LOCALES
709 if (err_language != Config.errorDefaultLanguage)
710 #endif
711 safe_free(err_language);
712 #if USE_SSL
713 delete detail;
714 #endif
715 }
716
717 int
718 ErrorState::Dump(MemBuf * mb)
719 {
720 MemBuf str;
721 char ntoabuf[MAX_IPSTRLEN];
722
723 str.reset();
724 /* email subject line */
725 str.Printf("CacheErrorInfo - %s", errorPageName(type));
726 mb->Printf("?subject=%s", rfc1738_escape_part(str.buf));
727 str.reset();
728 /* email body */
729 str.Printf("CacheHost: %s\r\n", getMyHostname());
730 /* - Err Msgs */
731 str.Printf("ErrPage: %s\r\n", errorPageName(type));
732
733 if (xerrno) {
734 str.Printf("Err: (%d) %s\r\n", xerrno, strerror(xerrno));
735 } else {
736 str.Printf("Err: [none]\r\n");
737 }
738 #if USE_AUTH
739 if (auth_user_request->denyMessage())
740 str.Printf("Auth ErrMsg: %s\r\n", auth_user_request->denyMessage());
741 #endif
742 if (dnsError.size() > 0)
743 str.Printf("DNS ErrMsg: %s\r\n", dnsError.termedBuf());
744
745 /* - TimeStamp */
746 str.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime));
747
748 /* - IP stuff */
749 str.Printf("ClientIP: %s\r\n", src_addr.toStr(ntoabuf,MAX_IPSTRLEN));
750
751 if (request && request->hier.host[0] != '\0') {
752 str.Printf("ServerIP: %s\r\n", request->hier.host);
753 }
754
755 str.Printf("\r\n");
756 /* - HTTP stuff */
757 str.Printf("HTTP Request:\r\n");
758
759 if (NULL != request) {
760 Packer pck;
761 String urlpath_or_slash;
762
763 if (request->urlpath.size() != 0)
764 urlpath_or_slash = request->urlpath;
765 else
766 urlpath_or_slash = "/";
767
768 str.Printf("%s " SQUIDSTRINGPH " %s/%d.%d\n",
769 RequestMethodStr(request->method),
770 SQUIDSTRINGPRINT(urlpath_or_slash),
771 AnyP::ProtocolType_str[request->http_ver.protocol],
772 request->http_ver.major, request->http_ver.minor);
773 packerToMemInit(&pck, &str);
774 request->header.packInto(&pck);
775 packerClean(&pck);
776 }
777
778 str.Printf("\r\n");
779 /* - FTP stuff */
780
781 if (ftp.request) {
782 str.Printf("FTP Request: %s\r\n", ftp.request);
783 str.Printf("FTP Reply: %s\r\n", (ftp.reply? ftp.reply:"[none]"));
784 str.Printf("FTP Msg: ");
785 wordlistCat(ftp.server_msg, &str);
786 str.Printf("\r\n");
787 }
788
789 str.Printf("\r\n");
790 mb->Printf("&body=%s", rfc1738_escape_part(str.buf));
791 str.clean();
792 return 0;
793 }
794
795 /// \ingroup ErrorPageInternal
796 #define CVT_BUF_SZ 512
797
798 const char *
799 ErrorState::Convert(char token, bool building_deny_info_url, bool allowRecursion)
800 {
801 static MemBuf mb;
802 const char *p = NULL; /* takes priority over mb if set */
803 int do_quote = 1;
804 int no_urlescape = 0; /* if true then item is NOT to be further URL-encoded */
805 char ntoabuf[MAX_IPSTRLEN];
806
807 mb.reset();
808
809 switch (token) {
810
811 case 'a':
812 #if USE_AUTH
813 if (request && request->auth_user_request != NULL)
814 p = request->auth_user_request->username();
815 if (!p)
816 #endif
817 p = "-";
818 break;
819
820 case 'b':
821 mb.Printf("%d", getMyPort());
822 break;
823
824 case 'B':
825 if (building_deny_info_url) break;
826 p = request ? ftpUrlWith2f(request) : "[no URL]";
827 break;
828
829 case 'c':
830 if (building_deny_info_url) break;
831 p = errorPageName(type);
832 break;
833
834 case 'D':
835 if (!allowRecursion)
836 p = "%D"; // if recursion is not allowed, do not convert
837 #if USE_SSL
838 // currently only SSL error details implemented
839 else if (detail) {
840 detail->useRequest(request);
841 const String &errDetail = detail->toString();
842 if (errDetail.defined()) {
843 MemBuf *detail_mb = ConvertText(errDetail.termedBuf(), false);
844 mb.append(detail_mb->content(), detail_mb->contentSize());
845 delete detail_mb;
846 do_quote = 0;
847 }
848 }
849 #endif
850 if (!mb.contentSize())
851 mb.Printf("[No Error Detail]");
852 break;
853
854 case 'e':
855 mb.Printf("%d", xerrno);
856 break;
857
858 case 'E':
859 if (xerrno)
860 mb.Printf("(%d) %s", xerrno, strerror(xerrno));
861 else
862 mb.Printf("[No Error]");
863 break;
864
865 case 'f':
866 if (building_deny_info_url) break;
867 /* FTP REQUEST LINE */
868 if (ftp.request)
869 p = ftp.request;
870 else
871 p = "nothing";
872 break;
873
874 case 'F':
875 if (building_deny_info_url) break;
876 /* FTP REPLY LINE */
877 if (ftp.reply)
878 p = ftp.reply;
879 else
880 p = "nothing";
881 break;
882
883 case 'g':
884 if (building_deny_info_url) break;
885 /* FTP SERVER RESPONSE */
886 if (ftp.listing) {
887 mb.append(ftp.listing->content(), ftp.listing->contentSize());
888 do_quote = 0;
889 } else if (ftp.server_msg) {
890 wordlistCat(ftp.server_msg, &mb);
891 }
892 break;
893
894 case 'h':
895 mb.Printf("%s", getMyHostname());
896 break;
897
898 case 'H':
899 if (request) {
900 if (request->hier.host[0] != '\0') // if non-empty string.
901 p = request->hier.host;
902 else
903 p = request->GetHost();
904 } else if (!building_deny_info_url)
905 p = "[unknown host]";
906 break;
907
908 case 'i':
909 mb.Printf("%s", src_addr.toStr(ntoabuf,MAX_IPSTRLEN));
910 break;
911
912 case 'I':
913 if (request && request->hier.tcpServer != NULL)
914 p = request->hier.tcpServer->remote.toStr(ntoabuf,MAX_IPSTRLEN);
915 else if (!building_deny_info_url)
916 p = "[unknown]";
917 break;
918
919 case 'l':
920 if (building_deny_info_url) break;
921 mb.append(error_stylesheet.content(), error_stylesheet.contentSize());
922 do_quote = 0;
923 break;
924
925 case 'L':
926 if (building_deny_info_url) break;
927 if (Config.errHtmlText) {
928 mb.Printf("%s", Config.errHtmlText);
929 do_quote = 0;
930 } else
931 p = "[not available]";
932 break;
933
934 case 'm':
935 if (building_deny_info_url) break;
936 #if USE_AUTH
937 p = auth_user_request->denyMessage("[not available]");
938 #else
939 p = "-";
940 #endif
941 break;
942
943 case 'M':
944 if (request)
945 p = RequestMethodStr(request->method);
946 else if (!building_deny_info_url)
947 p= "[unknown method]";
948 break;
949
950 case 'o':
951 p = request ? request->extacl_message.termedBuf() : external_acl_message;
952 if (!p && !building_deny_info_url)
953 p = "[not available]";
954 break;
955
956 case 'p':
957 if (request) {
958 mb.Printf("%d", (int) request->port);
959 } else if (!building_deny_info_url) {
960 p = "[unknown port]";
961 }
962 break;
963
964 case 'P':
965 if (request) {
966 p = AnyP::ProtocolType_str[request->protocol];
967 } else if (!building_deny_info_url) {
968 p = "[unknown protocol]";
969 }
970 break;
971
972 case 'R':
973 if (building_deny_info_url) {
974 p = (request->urlpath.size() != 0 ? request->urlpath.termedBuf() : "/");
975 no_urlescape = 1;
976 break;
977 }
978 if (NULL != request) {
979 Packer pck;
980 String urlpath_or_slash;
981
982 if (request->urlpath.size() != 0)
983 urlpath_or_slash = request->urlpath;
984 else
985 urlpath_or_slash = "/";
986
987 mb.Printf("%s " SQUIDSTRINGPH " %s/%d.%d\n",
988 RequestMethodStr(request->method),
989 SQUIDSTRINGPRINT(urlpath_or_slash),
990 AnyP::ProtocolType_str[request->http_ver.protocol],
991 request->http_ver.major, request->http_ver.minor);
992 packerToMemInit(&pck, &mb);
993 request->header.packInto(&pck, true); //hide authorization data
994 packerClean(&pck);
995 } else if (request_hdrs) {
996 p = request_hdrs;
997 } else {
998 p = "[no request]";
999 }
1000 break;
1001
1002 case 's':
1003 /* for backward compat we make %s show the full URL. Drop this in some future release. */
1004 if (building_deny_info_url) {
1005 p = request ? urlCanonical(request) : url;
1006 debugs(0, DBG_CRITICAL, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
1007 } else
1008 p = visible_appname_string;
1009 break;
1010
1011 case 'S':
1012 if (building_deny_info_url) {
1013 p = visible_appname_string;
1014 break;
1015 }
1016 /* signature may contain %-escapes, recursion */
1017 if (page_id != ERR_SQUID_SIGNATURE) {
1018 const int saved_id = page_id;
1019 page_id = ERR_SQUID_SIGNATURE;
1020 MemBuf *sign_mb = BuildContent();
1021 mb.Printf("%s", sign_mb->content());
1022 sign_mb->clean();
1023 delete sign_mb;
1024 page_id = saved_id;
1025 do_quote = 0;
1026 } else {
1027 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1028 p = "[%S]";
1029 }
1030 break;
1031
1032 case 't':
1033 mb.Printf("%s", Time::FormatHttpd(squid_curtime));
1034 break;
1035
1036 case 'T':
1037 mb.Printf("%s", mkrfc1123(squid_curtime));
1038 break;
1039
1040 case 'U':
1041 /* Using the fake-https version of canonical so error pages see https:// */
1042 /* even when the url-path cannot be shown as more than '*' */
1043 if (request)
1044 p = urlCanonicalFakeHttps(request);
1045 else if (url)
1046 p = url;
1047 else if (!building_deny_info_url)
1048 p = "[no URL]";
1049 break;
1050
1051 case 'u':
1052 if (request)
1053 p = urlCanonical(request);
1054 else if (url)
1055 p = url;
1056 else if (!building_deny_info_url)
1057 p = "[no URL]";
1058 break;
1059
1060 case 'w':
1061 if (Config.adminEmail)
1062 mb.Printf("%s", Config.adminEmail);
1063 else if (!building_deny_info_url)
1064 p = "[unknown]";
1065 break;
1066
1067 case 'W':
1068 if (building_deny_info_url) break;
1069 if (Config.adminEmail && Config.onoff.emailErrData)
1070 Dump(&mb);
1071 no_urlescape = 1;
1072 break;
1073
1074 case 'x':
1075 #if USE_SSL
1076 if (detail)
1077 mb.Printf("%s", detail->errorName());
1078 else
1079 #endif
1080 if (!building_deny_info_url)
1081 p = "[Unknown Error Code]";
1082 break;
1083
1084 case 'z':
1085 if (building_deny_info_url) break;
1086 if (dnsError.size() > 0)
1087 p = dnsError.termedBuf();
1088 else if (ftp.cwd_msg)
1089 p = ftp.cwd_msg;
1090 else
1091 p = "[unknown]";
1092 break;
1093
1094 case 'Z':
1095 if (building_deny_info_url) break;
1096 if (err_msg)
1097 p = err_msg;
1098 else
1099 p = "[unknown]";
1100 break;
1101
1102 case '%':
1103 p = "%";
1104 break;
1105
1106 default:
1107 mb.Printf("%%%c", token);
1108 do_quote = 0;
1109 break;
1110 }
1111
1112 if (!p)
1113 p = mb.buf; /* do not use mb after this assignment! */
1114
1115 assert(p);
1116
1117 debugs(4, 3, "errorConvert: %%" << token << " --> '" << p << "'" );
1118
1119 if (do_quote)
1120 p = html_quote(p);
1121
1122 if (building_deny_info_url && !no_urlescape)
1123 p = rfc1738_escape_part(p);
1124
1125 return p;
1126 }
1127
1128 void
1129 ErrorState::DenyInfoLocation(const char *name, HttpRequest *aRequest, MemBuf &result)
1130 {
1131 char const *m = name;
1132 char const *p = m;
1133 char const *t;
1134
1135 if (m[0] == '3')
1136 m += 4; // skip "3xx:"
1137
1138 while ((p = strchr(m, '%'))) {
1139 result.append(m, p - m); /* copy */
1140 t = Convert(*++p, true, true); /* convert */
1141 result.Printf("%s", t); /* copy */
1142 m = p + 1; /* advance */
1143 }
1144
1145 if (*m)
1146 result.Printf("%s", m); /* copy tail */
1147
1148 assert((size_t)result.contentSize() == strlen(result.content()));
1149 }
1150
1151 HttpReply *
1152 ErrorState::BuildHttpReply()
1153 {
1154 HttpReply *rep = new HttpReply;
1155 const char *name = errorPageName(page_id);
1156 /* no LMT for error pages; error pages expire immediately */
1157
1158 if (name[0] == '3' || (name[0] != '2' && name[0] != '4' && name[0] != '5' && strchr(name, ':'))) {
1159 /* Redirection */
1160 Http::StatusCode status = Http::scMovedTemporarily;
1161 // Use configured 3xx reply status if set.
1162 if (name[0] == '3')
1163 status = httpStatus;
1164 else {
1165 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1166 if (request->method != Http::METHOD_GET && request->method != Http::METHOD_HEAD && request->http_ver >= Http::ProtocolVersion(1,1))
1167 status = Http::scTemporaryRedirect;
1168 }
1169
1170 rep->setHeaders(status, NULL, "text/html", 0, 0, -1);
1171
1172 if (request) {
1173 MemBuf redirect_location;
1174 redirect_location.init();
1175 DenyInfoLocation(name, request, redirect_location);
1176 httpHeaderPutStrf(&rep->header, HDR_LOCATION, "%s", redirect_location.content() );
1177 }
1178
1179 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%d %s", httpStatus, "Access Denied");
1180 } else {
1181 MemBuf *content = BuildContent();
1182 rep->setHeaders(httpStatus, NULL, "text/html", content->contentSize(), 0, -1);
1183 /*
1184 * include some information for downstream caches. Implicit
1185 * replaceable content. This isn't quite sufficient. xerrno is not
1186 * necessarily meaningful to another system, so we really should
1187 * expand it. Additionally, we should identify ourselves. Someone
1188 * might want to know. Someone _will_ want to know OTOH, the first
1189 * X-CACHE-MISS entry should tell us who.
1190 */
1191 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%s %d", name, xerrno);
1192
1193 #if USE_ERR_LOCALES
1194 /*
1195 * If error page auto-negotiate is enabled in any way, send the Vary.
1196 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1197 * We have even better reasons though:
1198 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1199 */
1200 if (!Config.errorDirectory) {
1201 /* We 'negotiated' this ONLY from the Accept-Language. */
1202 rep->header.delById(HDR_VARY);
1203 rep->header.putStr(HDR_VARY, "Accept-Language");
1204 }
1205
1206 /* add the Content-Language header according to RFC section 14.12 */
1207 if (err_language) {
1208 rep->header.putStr(HDR_CONTENT_LANGUAGE, err_language);
1209 } else
1210 #endif /* USE_ERROR_LOCALES */
1211 {
1212 /* default templates are in English */
1213 /* language is known unless error_directory override used */
1214 if (!Config.errorDirectory)
1215 rep->header.putStr(HDR_CONTENT_LANGUAGE, "en");
1216 }
1217
1218 rep->body.setMb(content);
1219 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1220 }
1221
1222 // Make sure error codes get back to the client side for logging and
1223 // error tracking.
1224 if (request) {
1225 int edc = ERR_DETAIL_NONE; // error detail code
1226 #if USE_SSL
1227 if (detail)
1228 edc = detail->errorNo();
1229 else
1230 #endif
1231 if (detailCode)
1232 edc = detailCode;
1233 else
1234 edc = xerrno;
1235 request->detailError(type, edc);
1236 }
1237
1238 return rep;
1239 }
1240
1241 MemBuf *
1242 ErrorState::BuildContent()
1243 {
1244 const char *m = NULL;
1245
1246 assert(page_id > ERR_NONE && page_id < error_page_count);
1247
1248 #if USE_ERR_LOCALES
1249 ErrorPageFile *localeTmpl = NULL;
1250
1251 /** error_directory option in squid.conf overrides translations.
1252 * Custom errors are always found either in error_directory or the templates directory.
1253 * Otherwise locate the Accept-Language header
1254 */
1255 if (!Config.errorDirectory && page_id < ERR_MAX) {
1256 if (err_language && err_language != Config.errorDefaultLanguage)
1257 safe_free(err_language);
1258
1259 localeTmpl = new ErrorPageFile(err_type_str[page_id], static_cast<err_type>(page_id));
1260 if (localeTmpl->loadFor(request)) {
1261 m = localeTmpl->text();
1262 assert(localeTmpl->language());
1263 err_language = xstrdup(localeTmpl->language());
1264 }
1265 }
1266 #endif /* USE_ERR_LOCALES */
1267
1268 /** \par
1269 * If client-specific error templates are not enabled or available.
1270 * fall back to the old style squid.conf settings.
1271 */
1272 if (!m) {
1273 m = error_text[page_id];
1274 #if USE_ERR_LOCALES
1275 if (!Config.errorDirectory)
1276 err_language = Config.errorDefaultLanguage;
1277 #endif
1278 debugs(4, 2, HERE << "No existing error page language negotiated for " << errorPageName(page_id) << ". Using default error file.");
1279 }
1280
1281 MemBuf *result = ConvertText(m, true);
1282 #if USE_ERR_LOCALES
1283 if (localeTmpl)
1284 delete localeTmpl;
1285 #endif
1286 return result;
1287 }
1288
1289 MemBuf *ErrorState::ConvertText(const char *text, bool allowRecursion)
1290 {
1291 MemBuf *content = new MemBuf;
1292 const char *p;
1293 const char *m = text;
1294 assert(m);
1295 content->init();
1296
1297 while ((p = strchr(m, '%'))) {
1298 content->append(m, p - m); /* copy */
1299 const char *t = Convert(*++p, false, allowRecursion); /* convert */
1300 content->Printf("%s", t); /* copy */
1301 m = p + 1; /* advance */
1302 }
1303
1304 if (*m)
1305 content->Printf("%s", m); /* copy tail */
1306
1307 assert((size_t)content->contentSize() == strlen(content->content()));
1308
1309 return content;
1310 }