]> git.ipfire.org Git - thirdparty/squid.git/blob - src/errorpage.cc
Fix segfault in %F error page token
[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 "config.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): TemplateFile(name) { 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]);
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);
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");
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): silent(false), wasLoaded(false), templateName(name)
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, DBG_CRITICAL, "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 fatal("failed to find or read error text file.");
303
304 return true;
305 }
306
307 bool
308 TemplateFile::tryLoadTemplate(const char *lang)
309 {
310 assert(lang);
311
312 char path[MAXPATHLEN];
313 /* TODO: prep the directory path string to prevent snprintf ... */
314 snprintf(path, sizeof(path), "%s/%s/%s",
315 DEFAULT_SQUID_ERROR_DIR, lang, templateName.termedBuf());
316 path[MAXPATHLEN-1] = '\0';
317
318 if (loadFromFile(path))
319 return true;
320
321 #if HAVE_GLOB
322 if ( strlen(lang) == 2) {
323 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
324 /* use first result. */
325 debugs(4,2, HERE << "wildcard fallback errors not coded yet.");
326 }
327 #endif
328
329 return false;
330 }
331
332 bool
333 TemplateFile::loadFromFile(const char *path)
334 {
335 int fd;
336 char buf[4096];
337 ssize_t len;
338
339 if (loaded()) // already loaded?
340 return true;
341
342 fd = file_open(path, O_RDONLY | O_TEXT);
343
344 if (fd < 0) {
345 /* with dynamic locale negotiation we may see some failures before a success. */
346 if (!silent)
347 debugs(4, DBG_CRITICAL, HERE << "'" << path << "': " << xstrerror());
348 wasLoaded = false;
349 return wasLoaded;
350 }
351
352 while ((len = FD_READ_METHOD(fd, buf, sizeof(buf))) > 0) {
353 if (!parse(buf, len, false)) {
354 debugs(4, DBG_CRITICAL, HERE << " parse error while reading template file: " << path);
355 wasLoaded = false;
356 return wasLoaded;
357 }
358 }
359 parse(buf, 0, true);
360
361 if (len < 0) {
362 debugs(4, DBG_CRITICAL, HERE << "failed to fully read: '" << path << "': " << xstrerror());
363 }
364
365 file_close(fd);
366
367 wasLoaded = true;
368 return wasLoaded;
369 }
370
371 bool strHdrAcptLangGetItem(const String &hdr, char *lang, int langLen, size_t &pos)
372 {
373 while (pos < hdr.size()) {
374 char *dt = lang;
375
376 if (!pos) {
377 /* skip any initial whitespace. */
378 while (pos < hdr.size() && xisspace(hdr[pos])) pos++;
379 } else {
380 // IFF we terminated the tag on whitespace or ';' we need to skip to the next ',' or end of header.
381 while (pos < hdr.size() && hdr[pos] != ',') pos++;
382 if (hdr[pos] == ',') pos++;
383 }
384
385 /*
386 * Header value format:
387 * - sequence of whitespace delimited tags
388 * - each tag may suffix with ';'.* which we can ignore.
389 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
390 * with preference given to an exact match.
391 */
392 bool invalid_byte = false;
393 while (pos < hdr.size() && hdr[pos] != ';' && hdr[pos] != ',' && !xisspace(hdr[pos]) && dt < (lang + (langLen -1)) ) {
394 if (!invalid_byte) {
395 #if USE_HTTP_VIOLATIONS
396 // if accepting violations we may as well accept some broken browsers
397 // which may send us the right code, wrong ISO formatting.
398 if (hdr[pos] == '_')
399 *dt = '-';
400 else
401 #endif
402 *dt = xtolower(hdr[pos]);
403 // valid codes only contain A-Z, hyphen (-) and *
404 if (*dt != '-' && *dt != '*' && (*dt < 'a' || *dt > 'z') )
405 invalid_byte = true;
406 else
407 dt++; // move to next destination byte.
408 }
409 pos++;
410 }
411 *dt++ = '\0'; // nul-terminated the filename content string before system use.
412
413 debugs(4, 9, HERE << "STATE: dt='" << dt << "', lang='" << lang << "', pos=" << pos << ", buf='" << ((pos < hdr.size()) ? hdr.substr(pos,hdr.size()) : "") << "'");
414
415 /* if we found anything we might use, try it. */
416 if (*lang != '\0' && !invalid_byte)
417 return true;
418 }
419 return false;
420 }
421
422 bool
423 TemplateFile::loadFor(HttpRequest *request)
424 {
425 String hdr;
426
427 #if USE_ERR_LOCALES
428 if (loaded()) // already loaded?
429 return true;
430
431 if (!request || !request->header.getList(HDR_ACCEPT_LANGUAGE, &hdr) )
432 return false;
433
434 char lang[256];
435 size_t pos = 0; // current parsing position in header string
436
437 debugs(4, 6, HERE << "Testing Header: '" << hdr << "'");
438
439 while ( strHdrAcptLangGetItem(hdr, lang, 256, pos) ) {
440
441 /* wildcard uses the configured default language */
442 if (lang[0] == '*' && lang[1] == '\0') {
443 debugs(4, 6, HERE << "Found language '" << lang << "'. Using configured default.");
444 return false;
445 }
446
447 debugs(4, 6, HERE << "Found language '" << lang << "', testing for available template");
448
449 if (tryLoadTemplate(lang)) {
450 /* store the language we found for the Content-Language reply header */
451 errLanguage = lang;
452 break;
453 } else if (Config.errorLogMissingLanguages) {
454 debugs(4, DBG_IMPORTANT, "WARNING: Error Pages Missing Language: " << lang);
455 }
456 }
457 #endif
458
459 return loaded();
460 }
461
462 /// \ingroup ErrorPageInternal
463 static ErrorDynamicPageInfo *
464 errorDynamicPageInfoCreate(int id, const char *page_name)
465 {
466 ErrorDynamicPageInfo *info = new ErrorDynamicPageInfo;
467 info->id = id;
468 info->page_name = xstrdup(page_name);
469 info->page_redirect = static_cast<http_status>(atoi(page_name));
470
471 /* WARNING on redirection status:
472 * 2xx are permitted, but not documented officially.
473 * - might be useful for serving static files (PAC etc) in special cases
474 * 3xx require a URL suitable for Location: header.
475 * - the current design does not allow for a Location: URI as well as a local file template
476 * although this possibility is explicitly permitted in the specs.
477 * 4xx-5xx require a local file template.
478 * - sending Location: on these codes with no body is invalid by the specs.
479 * - current result is Squid crashing or XSS problems as dynamic deny_info load random disk files.
480 * - a future redesign of the file loading may result in loading remote objects sent inline as local body.
481 */
482 if (info->page_redirect == HTTP_STATUS_NONE)
483 ; // special case okay.
484 else if (info->page_redirect < 200 || info->page_redirect > 599) {
485 // out of range
486 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " is not valid on '" << page_name << "'");
487 self_destruct();
488 } else if ( /* >= 200 && */ info->page_redirect < 300 && strchr(&(page_name[4]), ':')) {
489 // 2xx require a local template file
490 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " requires a template on '" << page_name << "'");
491 self_destruct();
492 } else if (info->page_redirect >= 300 && info->page_redirect <= 399 && !strchr(&(page_name[4]), ':')) {
493 // 3xx require an absolute URL
494 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " requires a URL on '" << page_name << "'");
495 self_destruct();
496 } else if (info->page_redirect >= 400 /* && <= 599 */ && strchr(&(page_name[4]), ':')) {
497 // 4xx/5xx require a local template file
498 debugs(0, DBG_CRITICAL, "FATAL: status " << info->page_redirect << " requires a template on '" << page_name << "'");
499 self_destruct();
500 }
501 // else okay.
502
503 return info;
504 }
505
506 /// \ingroup ErrorPageInternal
507 static void
508 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo * info)
509 {
510 assert(info);
511 safe_free(info->page_name);
512 delete info;
513 }
514
515 /// \ingroup ErrorPageInternal
516 static int
517 errorPageId(const char *page_name)
518 {
519 for (int i = 0; i < ERR_MAX; i++) {
520 if (strcmp(err_type_str[i], page_name) == 0)
521 return i;
522 }
523
524 for (size_t j = 0; j < ErrorDynamicPages.size(); j++) {
525 if (strcmp(ErrorDynamicPages.items[j]->page_name, page_name) == 0)
526 return j + ERR_MAX;
527 }
528
529 return ERR_NONE;
530 }
531
532 err_type
533 errorReservePageId(const char *page_name)
534 {
535 ErrorDynamicPageInfo *info;
536 int id = errorPageId(page_name);
537
538 if (id == ERR_NONE) {
539 info = errorDynamicPageInfoCreate(ERR_MAX + ErrorDynamicPages.size(), page_name);
540 ErrorDynamicPages.push_back(info);
541 id = info->id;
542 }
543
544 return (err_type)id;
545 }
546
547 /// \ingroup ErrorPageInternal
548 const char *
549 errorPageName(int pageId)
550 {
551 if (pageId >= ERR_NONE && pageId < ERR_MAX) /* common case */
552 return err_type_str[pageId];
553
554 if (pageId >= ERR_MAX && pageId - ERR_MAX < (ssize_t)ErrorDynamicPages.size())
555 return ErrorDynamicPages.items[pageId - ERR_MAX]->page_name;
556
557 return "ERR_UNKNOWN"; /* should not happen */
558 }
559
560 ErrorState *
561 errorCon(err_type type, http_status status, HttpRequest * request)
562 {
563 ErrorState *err = new ErrorState;
564 err->page_id = type; /* has to be reset manually if needed */
565 err->err_language = NULL;
566 err->type = type;
567 err->httpStatus = status;
568 if (err->page_id >= ERR_MAX && ErrorDynamicPages.items[err->page_id - ERR_MAX]->page_redirect != HTTP_STATUS_NONE)
569 err->httpStatus = ErrorDynamicPages.items[err->page_id - ERR_MAX]->page_redirect;
570
571 if (request != NULL) {
572 err->request = HTTPMSGLOCK(request);
573 err->src_addr = request->client_addr;
574 request->detailError(type, ERR_DETAIL_NONE);
575 }
576
577 return err;
578 }
579
580 void
581 errorAppendEntry(StoreEntry * entry, ErrorState * err)
582 {
583 assert(entry->mem_obj != NULL);
584 assert (entry->isEmpty());
585 debugs(4, 4, "Creating an error page for entry " << entry <<
586 " with errorstate " << err <<
587 " page id " << err->page_id);
588
589 if (entry->store_status != STORE_PENDING) {
590 debugs(4, 2, "Skipping error page due to store_status: " << entry->store_status);
591 /*
592 * If the entry is not STORE_PENDING, then no clients
593 * care about it, and we don't need to generate an
594 * error message
595 */
596 assert(EBIT_TEST(entry->flags, ENTRY_ABORTED));
597 assert(entry->mem_obj->nclients == 0);
598 errorStateFree(err);
599 return;
600 }
601
602 if (err->page_id == TCP_RESET) {
603 if (err->request) {
604 debugs(4, 2, "RSTing this reply");
605 err->request->flags.setResetTCP();
606 }
607 }
608
609 entry->lock();
610 entry->buffer();
611 entry->replaceHttpReply( err->BuildHttpReply() );
612 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
613 entry->flush();
614 entry->complete();
615 entry->negativeCache();
616 entry->releaseRequest();
617 entry->unlock();
618 errorStateFree(err);
619 }
620
621 void
622 errorSend(const Comm::ConnectionPointer &conn, ErrorState * err)
623 {
624 HttpReply *rep;
625 debugs(4, 3, HERE << conn << ", err=" << err);
626 assert(Comm::IsConnOpen(conn));
627 /*
628 * ugh, this is how we make sure error codes get back to
629 * the client side for logging and error tracking.
630 */
631
632 if (err->request)
633 err->request->detailError(err->type, err->xerrno);
634
635 /* moved in front of errorBuildBuf @?@ */
636 err->flags.flag_cbdata = 1;
637
638 rep = err->BuildHttpReply();
639
640 MemBuf *mb = rep->pack();
641 AsyncCall::Pointer call = commCbCall(78, 5, "errorSendComplete",
642 CommIoCbPtrFun(&errorSendComplete, err));
643 Comm::Write(conn, mb, call);
644 delete mb;
645
646 delete rep;
647 }
648
649 /**
650 \ingroup ErrorPageAPI
651 *
652 * Called by commHandleWrite() after data has been written
653 * to the client socket.
654 *
655 \note If there is a callback, the callback is responsible for
656 * closing the FD, otherwise we do it ourselves.
657 */
658 static void
659 errorSendComplete(const Comm::ConnectionPointer &conn, char *bufnotused, size_t size, comm_err_t errflag, int xerrno, void *data)
660 {
661 ErrorState *err = static_cast<ErrorState *>(data);
662 debugs(4, 3, HERE << conn << ", size=" << size);
663
664 if (errflag != COMM_ERR_CLOSING) {
665 if (err->callback) {
666 debugs(4, 3, "errorSendComplete: callback");
667 err->callback(conn->fd, err->callback_data, size);
668 } else {
669 debugs(4, 3, "errorSendComplete: comm_close");
670 conn->close();
671 }
672 }
673
674 errorStateFree(err);
675 }
676
677 void
678 errorStateFree(ErrorState * err)
679 {
680 HTTPMSGUNLOCK(err->request);
681 safe_free(err->redirect_url);
682 safe_free(err->url);
683 safe_free(err->request_hdrs);
684 wordlistDestroy(&err->ftp.server_msg);
685 safe_free(err->ftp.request);
686 safe_free(err->ftp.reply);
687 #if USE_AUTH
688 err->auth_user_request = NULL;
689 #endif
690 safe_free(err->err_msg);
691 #if USE_ERR_LOCALES
692 if (err->err_language != Config.errorDefaultLanguage)
693 #endif
694 safe_free(err->err_language);
695 #if USE_SSL
696 delete err->detail;
697 #endif
698 cbdataFree(err);
699 }
700
701 int
702 ErrorState::Dump(MemBuf * mb)
703 {
704 MemBuf str;
705 char ntoabuf[MAX_IPSTRLEN];
706
707 str.reset();
708 /* email subject line */
709 str.Printf("CacheErrorInfo - %s", errorPageName(type));
710 mb->Printf("?subject=%s", rfc1738_escape_part(str.buf));
711 str.reset();
712 /* email body */
713 str.Printf("CacheHost: %s\r\n", getMyHostname());
714 /* - Err Msgs */
715 str.Printf("ErrPage: %s\r\n", errorPageName(type));
716
717 if (xerrno) {
718 str.Printf("Err: (%d) %s\r\n", xerrno, strerror(xerrno));
719 } else {
720 str.Printf("Err: [none]\r\n");
721 }
722 #if USE_AUTH
723 if (auth_user_request->denyMessage())
724 str.Printf("Auth ErrMsg: %s\r\n", auth_user_request->denyMessage());
725 #endif
726 if (dnsError.size() > 0)
727 str.Printf("DNS ErrMsg: %s\r\n", dnsError.termedBuf());
728
729 /* - TimeStamp */
730 str.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime));
731
732 /* - IP stuff */
733 str.Printf("ClientIP: %s\r\n", src_addr.NtoA(ntoabuf,MAX_IPSTRLEN));
734
735 if (request && request->hier.host[0] != '\0') {
736 str.Printf("ServerIP: %s\r\n", request->hier.host);
737 }
738
739 str.Printf("\r\n");
740 /* - HTTP stuff */
741 str.Printf("HTTP Request:\r\n");
742
743 if (NULL != request) {
744 Packer pck;
745 String urlpath_or_slash;
746
747 if (request->urlpath.size() != 0)
748 urlpath_or_slash = request->urlpath;
749 else
750 urlpath_or_slash = "/";
751
752 str.Printf("%s " SQUIDSTRINGPH " %s/%d.%d\n",
753 RequestMethodStr(request->method),
754 SQUIDSTRINGPRINT(urlpath_or_slash),
755 AnyP::ProtocolType_str[request->http_ver.protocol],
756 request->http_ver.major, request->http_ver.minor);
757 packerToMemInit(&pck, &str);
758 request->header.packInto(&pck);
759 packerClean(&pck);
760 }
761
762 str.Printf("\r\n");
763 /* - FTP stuff */
764
765 if (ftp.request) {
766 str.Printf("FTP Request: %s\r\n", ftp.request);
767 str.Printf("FTP Reply: %s\r\n", ftp.reply);
768 str.Printf("FTP Msg: ");
769 wordlistCat(ftp.server_msg, &str);
770 str.Printf("\r\n");
771 }
772
773 str.Printf("\r\n");
774 mb->Printf("&body=%s", rfc1738_escape_part(str.buf));
775 str.clean();
776 return 0;
777 }
778
779 /// \ingroup ErrorPageInternal
780 #define CVT_BUF_SZ 512
781
782 const char *
783 ErrorState::Convert(char token, bool building_deny_info_url, bool allowRecursion)
784 {
785 static MemBuf mb;
786 const char *p = NULL; /* takes priority over mb if set */
787 int do_quote = 1;
788 int no_urlescape = 0; /* if true then item is NOT to be further URL-encoded */
789 char ntoabuf[MAX_IPSTRLEN];
790
791 mb.reset();
792
793 switch (token) {
794
795 case 'a':
796 #if USE_AUTH
797 if (request && request->auth_user_request != NULL)
798 p = request->auth_user_request->username();
799 if (!p)
800 #endif
801 p = "-";
802 break;
803
804 case 'b':
805 mb.Printf("%d", getMyPort());
806 break;
807
808 case 'B':
809 if (building_deny_info_url) break;
810 p = request ? ftpUrlWith2f(request) : "[no URL]";
811 break;
812
813 case 'c':
814 if (building_deny_info_url) break;
815 p = errorPageName(type);
816 break;
817
818 case 'D':
819 if (!allowRecursion)
820 p = "%D"; // if recursion is not allowed, do not convert
821 #if USE_SSL
822 // currently only SSL error details implemented
823 else if (detail) {
824 detail->useRequest(request);
825 const String &errDetail = detail->toString();
826 if (errDetail.defined()) {
827 MemBuf *detail_mb = ConvertText(errDetail.termedBuf(), false);
828 mb.append(detail_mb->content(), detail_mb->contentSize());
829 delete detail_mb;
830 do_quote = 0;
831 }
832 }
833 #endif
834 if (!mb.contentSize())
835 mb.Printf("[No Error Detail]");
836 break;
837
838 case 'e':
839 mb.Printf("%d", xerrno);
840 break;
841
842 case 'E':
843 if (xerrno)
844 mb.Printf("(%d) %s", xerrno, strerror(xerrno));
845 else
846 mb.Printf("[No Error]");
847 break;
848
849 case 'f':
850 if (building_deny_info_url) break;
851 /* FTP REQUEST LINE */
852 if (ftp.request)
853 p = ftp.request;
854 else
855 p = "nothing";
856 break;
857
858 case 'F':
859 if (building_deny_info_url) break;
860 /* FTP REPLY LINE */
861 if (ftp.reply)
862 p = ftp.reply;
863 else
864 p = "nothing";
865 break;
866
867 case 'g':
868 if (building_deny_info_url) break;
869 /* FTP SERVER RESPONSE */
870 if (ftp.listing) {
871 mb.append(ftp.listing->content(), ftp.listing->contentSize());
872 do_quote = 0;
873 } else if (ftp.server_msg) {
874 wordlistCat(ftp.server_msg, &mb);
875 }
876 break;
877
878 case 'h':
879 mb.Printf("%s", getMyHostname());
880 break;
881
882 case 'H':
883 if (request) {
884 if (request->hier.host[0] != '\0') // if non-empty string.
885 p = request->hier.host;
886 else
887 p = request->GetHost();
888 } else if (!building_deny_info_url)
889 p = "[unknown host]";
890 break;
891
892 case 'i':
893 mb.Printf("%s", src_addr.NtoA(ntoabuf,MAX_IPSTRLEN));
894 break;
895
896 case 'I':
897 if (request && request->hier.tcpServer != NULL)
898 p = request->hier.tcpServer->remote.NtoA(ntoabuf,MAX_IPSTRLEN);
899 else if (!building_deny_info_url)
900 p = "[unknown]";
901 break;
902
903 case 'l':
904 if (building_deny_info_url) break;
905 mb.append(error_stylesheet.content(), error_stylesheet.contentSize());
906 do_quote = 0;
907 break;
908
909 case 'L':
910 if (building_deny_info_url) break;
911 if (Config.errHtmlText) {
912 mb.Printf("%s", Config.errHtmlText);
913 do_quote = 0;
914 } else
915 p = "[not available]";
916 break;
917
918 case 'm':
919 if (building_deny_info_url) break;
920 #if USE_AUTH
921 p = auth_user_request->denyMessage("[not available]");
922 #else
923 p = "-";
924 #endif
925 break;
926
927 case 'M':
928 if (request)
929 p = RequestMethodStr(request->method);
930 else if (!building_deny_info_url)
931 p= "[unknown method]";
932 break;
933
934 case 'o':
935 p = request ? request->extacl_message.termedBuf() : external_acl_message;
936 if (!p && !building_deny_info_url)
937 p = "[not available]";
938 break;
939
940 case 'p':
941 if (request) {
942 mb.Printf("%d", (int) request->port);
943 } else if (!building_deny_info_url) {
944 p = "[unknown port]";
945 }
946 break;
947
948 case 'P':
949 if (request) {
950 p = AnyP::ProtocolType_str[request->protocol];
951 } else if (!building_deny_info_url) {
952 p = "[unknown protocol]";
953 }
954 break;
955
956 case 'R':
957 if (building_deny_info_url) {
958 p = (request->urlpath.size() != 0 ? request->urlpath.termedBuf() : "/");
959 break;
960 }
961 if (NULL != request) {
962 Packer pck;
963 String urlpath_or_slash;
964
965 if (request->urlpath.size() != 0)
966 urlpath_or_slash = request->urlpath;
967 else
968 urlpath_or_slash = "/";
969
970 mb.Printf("%s " SQUIDSTRINGPH " %s/%d.%d\n",
971 RequestMethodStr(request->method),
972 SQUIDSTRINGPRINT(urlpath_or_slash),
973 AnyP::ProtocolType_str[request->http_ver.protocol],
974 request->http_ver.major, request->http_ver.minor);
975 packerToMemInit(&pck, &mb);
976 request->header.packInto(&pck);
977 packerClean(&pck);
978 } else if (request_hdrs) {
979 p = request_hdrs;
980 } else {
981 p = "[no request]";
982 }
983 break;
984
985 case 's':
986 /* for backward compat we make %s show the full URL. Drop this in some future release. */
987 if (building_deny_info_url) {
988 p = request ? urlCanonical(request) : url;
989 debugs(0,0, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
990 } else
991 p = visible_appname_string;
992 break;
993
994 case 'S':
995 if (building_deny_info_url) {
996 p = visible_appname_string;
997 break;
998 }
999 /* signature may contain %-escapes, recursion */
1000 if (page_id != ERR_SQUID_SIGNATURE) {
1001 const int saved_id = page_id;
1002 page_id = ERR_SQUID_SIGNATURE;
1003 MemBuf *sign_mb = BuildContent();
1004 mb.Printf("%s", sign_mb->content());
1005 sign_mb->clean();
1006 delete sign_mb;
1007 page_id = saved_id;
1008 do_quote = 0;
1009 } else {
1010 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
1011 p = "[%S]";
1012 }
1013 break;
1014
1015 case 't':
1016 mb.Printf("%s", Time::FormatHttpd(squid_curtime));
1017 break;
1018
1019 case 'T':
1020 mb.Printf("%s", mkrfc1123(squid_curtime));
1021 break;
1022
1023 case 'U':
1024 /* Using the fake-https version of canonical so error pages see https:// */
1025 /* even when the url-path cannot be shown as more than '*' */
1026 if (request)
1027 p = urlCanonicalFakeHttps(request);
1028 else if (url)
1029 p = url;
1030 else if (!building_deny_info_url)
1031 p = "[no URL]";
1032 break;
1033
1034 case 'u':
1035 if (request)
1036 p = urlCanonical(request);
1037 else if (url)
1038 p = url;
1039 else if (!building_deny_info_url)
1040 p = "[no URL]";
1041 break;
1042
1043 case 'w':
1044 if (Config.adminEmail)
1045 mb.Printf("%s", Config.adminEmail);
1046 else if (!building_deny_info_url)
1047 p = "[unknown]";
1048 break;
1049
1050 case 'W':
1051 if (building_deny_info_url) break;
1052 if (Config.adminEmail && Config.onoff.emailErrData)
1053 Dump(&mb);
1054 no_urlescape = 1;
1055 break;
1056
1057 case 'x':
1058 #if USE_SSL
1059 if (detail)
1060 mb.Printf("%s", detail->errorName());
1061 else
1062 #endif
1063 if (!building_deny_info_url)
1064 p = "[Unknown Error Code]";
1065 break;
1066
1067 case 'z':
1068 if (building_deny_info_url) break;
1069 if (dnsError.size() > 0)
1070 p = dnsError.termedBuf();
1071 else if (ftp.cwd_msg)
1072 p = ftp.cwd_msg;
1073 else
1074 p = "[unknown]";
1075 break;
1076
1077 case 'Z':
1078 if (building_deny_info_url) break;
1079 if (err_msg)
1080 p = err_msg;
1081 else
1082 p = "[unknown]";
1083 break;
1084
1085 case '%':
1086 p = "%";
1087 break;
1088
1089 default:
1090 mb.Printf("%%%c", token);
1091 do_quote = 0;
1092 break;
1093 }
1094
1095 if (!p)
1096 p = mb.buf; /* do not use mb after this assignment! */
1097
1098 assert(p);
1099
1100 debugs(4, 3, "errorConvert: %%" << token << " --> '" << p << "'" );
1101
1102 if (do_quote)
1103 p = html_quote(p);
1104
1105 if (building_deny_info_url && !no_urlescape)
1106 p = rfc1738_escape_part(p);
1107
1108 return p;
1109 }
1110
1111 void
1112 ErrorState::DenyInfoLocation(const char *name, HttpRequest *aRequest, MemBuf &result)
1113 {
1114 char const *m = name;
1115 char const *p = m;
1116 char const *t;
1117
1118 if (m[0] == '3')
1119 m += 4; // skip "3xx:"
1120
1121 while ((p = strchr(m, '%'))) {
1122 result.append(m, p - m); /* copy */
1123 t = Convert(*++p, true, true); /* convert */
1124 result.Printf("%s", t); /* copy */
1125 m = p + 1; /* advance */
1126 }
1127
1128 if (*m)
1129 result.Printf("%s", m); /* copy tail */
1130
1131 assert((size_t)result.contentSize() == strlen(result.content()));
1132 }
1133
1134 HttpReply *
1135 ErrorState::BuildHttpReply()
1136 {
1137 HttpReply *rep = new HttpReply;
1138 const char *name = errorPageName(page_id);
1139 /* no LMT for error pages; error pages expire immediately */
1140
1141 if (name[0] == '3' || (name[0] != '2' && name[0] != '4' && name[0] != '5' && strchr(name, ':'))) {
1142 /* Redirection */
1143 http_status status = HTTP_MOVED_TEMPORARILY;
1144 // Use configured 3xx reply status if set.
1145 if (name[0] == '3')
1146 status = httpStatus;
1147 else {
1148 // Use 307 for HTTP/1.1 non-GET/HEAD requests.
1149 if (request->method != METHOD_GET && request->method != METHOD_HEAD && request->http_ver >= HttpVersion(1,1))
1150 status = HTTP_TEMPORARY_REDIRECT;
1151 }
1152
1153 rep->setHeaders(status, NULL, "text/html", 0, 0, -1);
1154
1155 if (request) {
1156 MemBuf redirect_location;
1157 redirect_location.init();
1158 DenyInfoLocation(name, request, redirect_location);
1159 httpHeaderPutStrf(&rep->header, HDR_LOCATION, "%s", redirect_location.content() );
1160 }
1161
1162 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%d %s", httpStatus, "Access Denied");
1163 } else {
1164 MemBuf *content = BuildContent();
1165 rep->setHeaders(httpStatus, NULL, "text/html", content->contentSize(), 0, -1);
1166 /*
1167 * include some information for downstream caches. Implicit
1168 * replaceable content. This isn't quite sufficient. xerrno is not
1169 * necessarily meaningful to another system, so we really should
1170 * expand it. Additionally, we should identify ourselves. Someone
1171 * might want to know. Someone _will_ want to know OTOH, the first
1172 * X-CACHE-MISS entry should tell us who.
1173 */
1174 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%s %d", name, xerrno);
1175
1176 #if USE_ERR_LOCALES
1177 /*
1178 * If error page auto-negotiate is enabled in any way, send the Vary.
1179 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
1180 * We have even better reasons though:
1181 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
1182 */
1183 if (!Config.errorDirectory) {
1184 /* We 'negotiated' this ONLY from the Accept-Language. */
1185 rep->header.delById(HDR_VARY);
1186 rep->header.putStr(HDR_VARY, "Accept-Language");
1187 }
1188
1189 /* add the Content-Language header according to RFC section 14.12 */
1190 if (err_language) {
1191 rep->header.putStr(HDR_CONTENT_LANGUAGE, err_language);
1192 } else
1193 #endif /* USE_ERROR_LOCALES */
1194 {
1195 /* default templates are in English */
1196 /* language is known unless error_directory override used */
1197 if (!Config.errorDirectory)
1198 rep->header.putStr(HDR_CONTENT_LANGUAGE, "en");
1199 }
1200
1201 httpBodySet(&rep->body, content);
1202 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
1203 }
1204
1205 return rep;
1206 }
1207
1208 MemBuf *
1209 ErrorState::BuildContent()
1210 {
1211 const char *m = NULL;
1212
1213 assert(page_id > ERR_NONE && page_id < error_page_count);
1214
1215 #if USE_ERR_LOCALES
1216 ErrorPageFile *localeTmpl = NULL;
1217
1218 /** error_directory option in squid.conf overrides translations.
1219 * Custom errors are always found either in error_directory or the templates directory.
1220 * Otherwise locate the Accept-Language header
1221 */
1222 if (!Config.errorDirectory && page_id < ERR_MAX) {
1223 if (err_language && err_language != Config.errorDefaultLanguage)
1224 safe_free(err_language);
1225
1226 localeTmpl = new ErrorPageFile(err_type_str[page_id]);
1227 if (localeTmpl->loadFor(request)) {
1228 m = localeTmpl->text();
1229 assert(localeTmpl->language());
1230 err_language = xstrdup(localeTmpl->language());
1231 }
1232 }
1233 #endif /* USE_ERR_LOCALES */
1234
1235 /** \par
1236 * If client-specific error templates are not enabled or available.
1237 * fall back to the old style squid.conf settings.
1238 */
1239 if (!m) {
1240 m = error_text[page_id];
1241 #if USE_ERR_LOCALES
1242 if (!Config.errorDirectory)
1243 err_language = Config.errorDefaultLanguage;
1244 #endif
1245 debugs(4, 2, HERE << "No existing error page language negotiated for " << errorPageName(page_id) << ". Using default error file.");
1246 }
1247
1248 MemBuf *result = ConvertText(m, true);
1249 #if USE_ERR_LOCALES
1250 if (localeTmpl)
1251 delete localeTmpl;
1252 #endif
1253 return result;
1254 }
1255
1256 MemBuf *ErrorState::ConvertText(const char *text, bool allowRecursion)
1257 {
1258 MemBuf *content = new MemBuf;
1259 const char *p;
1260 const char *m = text;
1261 assert(m);
1262 content->init();
1263
1264 while ((p = strchr(m, '%'))) {
1265 content->append(m, p - m); /* copy */
1266 const char *t = Convert(*++p, false, allowRecursion); /* convert */
1267 content->Printf("%s", t); /* copy */
1268 m = p + 1; /* advance */
1269 }
1270
1271 if (*m)
1272 content->Printf("%s", m); /* copy tail */
1273
1274 assert((size_t)content->contentSize() == strlen(content->content()));
1275
1276 return content;
1277 }