]> git.ipfire.org Git - thirdparty/squid.git/blob - src/errorpage.cc
Merge from trunk
[thirdparty/squid.git] / src / errorpage.cc
1
2 /*
3 * $Id$
4 *
5 * DEBUG: section 4 Error Generation
6 * AUTHOR: Duane Wessels
7 *
8 * SQUID Web Proxy Cache http://www.squid-cache.org/
9 * ----------------------------------------------------------
10 *
11 * Squid is the result of efforts by numerous individuals from
12 * the Internet community; see the CONTRIBUTORS file for full
13 * details. Many organizations have provided support for Squid's
14 * development; see the SPONSORS file for full details. Squid is
15 * Copyrighted (C) 2001 by the Regents of the University of
16 * California; see the COPYRIGHT file for full details. Squid
17 * incorporates software developed and/or copyrighted by other
18 * sources; see the CREDITS file for full details.
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
33 *
34 */
35 #include "config.h"
36
37 #include "errorpage.h"
38 #include "auth/UserRequest.h"
39 #include "SquidTime.h"
40 #include "Store.h"
41 #include "HttpReply.h"
42 #include "HttpRequest.h"
43 #include "MemObject.h"
44 #include "fde.h"
45 #include "MemBuf.h"
46 #include "rfc1738.h"
47 #include "URLScheme.h"
48 #include "wordlist.h"
49
50 /**
51 \defgroup ErrorPageInternal Error Page Internals
52 \ingroup ErrorPageAPI
53 *
54 \section Abstract Abstract:
55 * These routines are used to generate error messages to be
56 * sent to clients. The error type is used to select between
57 * the various message formats. (formats are stored in the
58 * Config.errorDirectory)
59 */
60
61
62 #ifndef DEFAULT_SQUID_ERROR_DIR
63 /** Where to look for errors if config path fails.
64 \note Please use ./configure --datadir=/path instead of patching
65 */
66 #define DEFAULT_SQUID_ERROR_DIR DEFAULT_SQUID_DATA_DIR"/errors"
67 #endif
68
69 /// \ingroup ErrorPageInternal
70 CBDATA_CLASS_INIT(ErrorState);
71
72 /* local types */
73
74 /// \ingroup ErrorPageInternal
75 typedef struct {
76 int id;
77 char *page_name;
78 } ErrorDynamicPageInfo;
79
80 /* local constant and vars */
81
82 /**
83 \ingroup ErrorPageInternal
84 *
85 \note hard coded error messages are not appended with %S
86 * automagically to give you more control on the format
87 */
88 static const struct {
89 int type; /* and page_id */
90 const char *text;
91 }
92
93 error_hard_text[] = {
94
95 {
96 ERR_SQUID_SIGNATURE,
97 "\n<br>\n"
98 "<hr>\n"
99 "<div id=\"footer\">\n"
100 "Generated %T by %h (%s)\n"
101 "</div>\n"
102 "</body></html>\n"
103 },
104 {
105 TCP_RESET,
106 "reset"
107 }
108 };
109
110 /// \ingroup ErrorPageInternal
111 static Vector<ErrorDynamicPageInfo *> ErrorDynamicPages;
112
113 /* local prototypes */
114
115 /// \ingroup ErrorPageInternal
116 static const int error_hard_text_count = sizeof(error_hard_text) / sizeof(*error_hard_text);
117
118 /// \ingroup ErrorPageInternal
119 static char **error_text = NULL;
120
121 /// \ingroup ErrorPageInternal
122 static int error_page_count = 0;
123
124 /// \ingroup ErrorPageInternal
125 static MemBuf error_stylesheet;
126
127 static char *errorTryLoadText(const char *page_name, const char *dir, bool silent = false);
128 static char *errorLoadText(const char *page_name);
129 static const char *errorFindHardText(err_type type);
130 static ErrorDynamicPageInfo *errorDynamicPageInfoCreate(int id, const char *page_name);
131 static void errorDynamicPageInfoDestroy(ErrorDynamicPageInfo * info);
132 static IOCB errorSendComplete;
133
134
135 /// \ingroup ErrorPageInternal
136 err_type &operator++ (err_type &anErr)
137 {
138 int tmp = (int)anErr;
139 anErr = (err_type)(++tmp);
140 return anErr;
141 }
142
143 /// \ingroup ErrorPageInternal
144 int operator - (err_type const &anErr, err_type const &anErr2)
145 {
146 return (int)anErr - (int)anErr2;
147 }
148
149 void
150 errorInitialize(void)
151 {
152 err_type i;
153 const char *text;
154 error_page_count = ERR_MAX + ErrorDynamicPages.size();
155 error_text = static_cast<char **>(xcalloc(error_page_count, sizeof(char *)));
156
157 for (i = ERR_NONE, ++i; i < error_page_count; ++i) {
158 safe_free(error_text[i]);
159
160 if ((text = errorFindHardText(i))) {
161 /**\par
162 * Index any hard-coded error text into defaults.
163 */
164 error_text[i] = xstrdup(text);
165
166 } else if (i < ERR_MAX) {
167 /**\par
168 * Index precompiled fixed template files from one of two sources:
169 * (a) default language translation directory (error_default_language)
170 * (b) admin specified custom directory (error_directory)
171 */
172 error_text[i] = errorLoadText(err_type_str[i]);
173
174 } else {
175 /** \par
176 * Index any unknown file names used by deny_info.
177 */
178 ErrorDynamicPageInfo *info = ErrorDynamicPages.items[i - ERR_MAX];
179 assert(info && info->id == i && info->page_name);
180
181 if (strchr(info->page_name, ':') == NULL) {
182 /** But only if they are not redirection URL. */
183 error_text[i] = errorLoadText(info->page_name);
184 }
185 }
186 }
187
188 error_stylesheet.reset();
189
190 // look for and load stylesheet into global MemBuf for it.
191 if (Config.errorStylesheet) {
192 char *temp = errorTryLoadText(Config.errorStylesheet,NULL);
193 if (temp) {
194 error_stylesheet.Printf("%s",temp);
195 safe_free(temp);
196 }
197 }
198 }
199
200 void
201 errorClean(void)
202 {
203 if (error_text) {
204 int i;
205
206 for (i = ERR_NONE + 1; i < error_page_count; i++)
207 safe_free(error_text[i]);
208
209 safe_free(error_text);
210 }
211
212 while (ErrorDynamicPages.size())
213 errorDynamicPageInfoDestroy(ErrorDynamicPages.pop_back());
214
215 error_page_count = 0;
216 }
217
218 /// \ingroup ErrorPageInternal
219 static const char *
220 errorFindHardText(err_type type)
221 {
222 int i;
223
224 for (i = 0; i < error_hard_text_count; i++)
225 if (error_hard_text[i].type == type)
226 return error_hard_text[i].text;
227
228 return NULL;
229 }
230
231 /**
232 * \ingroup ErrorPageInternal
233 *
234 * Load into the in-memory error text Index a file probably available at:
235 * (a) admin specified custom directory (error_directory)
236 * (b) default language translation directory (error_default_language)
237 * (c) English sub-directory where errors should ALWAYS exist
238 */
239 static char *
240 errorLoadText(const char *page_name)
241 {
242 char *text = NULL;
243
244 /** test error_directory configured location */
245 if (Config.errorDirectory)
246 text = errorTryLoadText(page_name, Config.errorDirectory);
247
248 #if USE_ERR_LOCALES
249 /** test error_default_language location */
250 if (!text && Config.errorDefaultLanguage) {
251 char dir[256];
252 snprintf(dir,256,"%s/%s", DEFAULT_SQUID_ERROR_DIR, Config.errorDefaultLanguage);
253 text = errorTryLoadText(page_name, dir);
254 if (!text) {
255 debugs(1, DBG_CRITICAL, "Unable to load default error language files. Reset to backups.");
256 }
257 }
258 #endif
259
260 /* test default location if failed (templates == English translation base templates) */
261 if (!text) {
262 text = errorTryLoadText(page_name, DEFAULT_SQUID_ERROR_DIR"/templates");
263 }
264
265 /* giving up if failed */
266 if (!text)
267 fatal("failed to find or read error text file.");
268
269 return text;
270 }
271
272 /// \ingroup ErrorPageInternal
273 static char *
274 errorTryLoadText(const char *page_name, const char *dir, bool silent)
275 {
276 int fd;
277 char path[MAXPATHLEN];
278 char buf[4096];
279 char *text;
280 ssize_t len;
281 MemBuf textbuf;
282
283 // maybe received compound parts, maybe an absolute page_name and no dir
284 if (dir)
285 snprintf(path, sizeof(path), "%s/%s", dir, page_name);
286 else
287 snprintf(path, sizeof(path), "%s", page_name);
288
289 fd = file_open(path, O_RDONLY | O_TEXT);
290
291 if (fd < 0) {
292 /* with dynamic locale negotiation we may see some failures before a success. */
293 if (!silent)
294 debugs(4, DBG_CRITICAL, HERE << "'" << path << "': " << xstrerror());
295 return NULL;
296 }
297
298 textbuf.init();
299
300 while ((len = FD_READ_METHOD(fd, buf, sizeof(buf))) > 0) {
301 textbuf.append(buf, len);
302 }
303
304 if (len < 0) {
305 debugs(4, DBG_CRITICAL, HERE << "failed to fully read: '" << path << "': " << xstrerror());
306 }
307
308 file_close(fd);
309
310 /* Shrink memory size down to exact size. MemBuf has a tencendy
311 * to be rather large..
312 */
313 text = xstrdup(textbuf.buf);
314
315 textbuf.clean();
316
317 return text;
318 }
319
320 /// \ingroup ErrorPageInternal
321 static ErrorDynamicPageInfo *
322 errorDynamicPageInfoCreate(int id, const char *page_name)
323 {
324 ErrorDynamicPageInfo *info = new ErrorDynamicPageInfo;
325 info->id = id;
326 info->page_name = xstrdup(page_name);
327 return info;
328 }
329
330 /// \ingroup ErrorPageInternal
331 static void
332 errorDynamicPageInfoDestroy(ErrorDynamicPageInfo * info)
333 {
334 assert(info);
335 safe_free(info->page_name);
336 delete info;
337 }
338
339 /// \ingroup ErrorPageInternal
340 static int
341 errorPageId(const char *page_name)
342 {
343 for (int i = 0; i < ERR_MAX; i++) {
344 if (strcmp(err_type_str[i], page_name) == 0)
345 return i;
346 }
347
348 for (size_t j = 0; j < ErrorDynamicPages.size(); j++) {
349 if (strcmp(ErrorDynamicPages.items[j]->page_name, page_name) == 0)
350 return j + ERR_MAX;
351 }
352
353 return ERR_NONE;
354 }
355
356 err_type
357 errorReservePageId(const char *page_name)
358 {
359 ErrorDynamicPageInfo *info;
360 int id = errorPageId(page_name);
361
362 if (id == ERR_NONE) {
363 info = errorDynamicPageInfoCreate(ERR_MAX + ErrorDynamicPages.size(), page_name);
364 ErrorDynamicPages.push_back(info);
365 id = info->id;
366 }
367
368 return (err_type)id;
369 }
370
371 /// \ingroup ErrorPageInternal
372 static const char *
373 errorPageName(int pageId)
374 {
375 if (pageId >= ERR_NONE && pageId < ERR_MAX) /* common case */
376 return err_type_str[pageId];
377
378 if (pageId >= ERR_MAX && pageId - ERR_MAX < (ssize_t)ErrorDynamicPages.size())
379 return ErrorDynamicPages.items[pageId - ERR_MAX]->page_name;
380
381 return "ERR_UNKNOWN"; /* should not happen */
382 }
383
384 ErrorState *
385 errorCon(err_type type, http_status status, HttpRequest * request)
386 {
387 ErrorState *err = new ErrorState;
388 err->page_id = type; /* has to be reset manually if needed */
389 err->err_language = NULL;
390 err->type = type;
391 err->httpStatus = status;
392
393 if (request != NULL) {
394 err->request = HTTPMSGLOCK(request);
395 err->src_addr = request->client_addr;
396 }
397
398 return err;
399 }
400
401 void
402 errorAppendEntry(StoreEntry * entry, ErrorState * err)
403 {
404 assert(entry->mem_obj != NULL);
405 assert (entry->isEmpty());
406 debugs(4, 4, "Creating an error page for entry " << entry <<
407 " with errorstate " << err <<
408 " page id " << err->page_id);
409
410 if (entry->store_status != STORE_PENDING) {
411 debugs(4, 2, "Skipping error page due to store_status: " << entry->store_status);
412 /*
413 * If the entry is not STORE_PENDING, then no clients
414 * care about it, and we don't need to generate an
415 * error message
416 */
417 assert(EBIT_TEST(entry->flags, ENTRY_ABORTED));
418 assert(entry->mem_obj->nclients == 0);
419 errorStateFree(err);
420 return;
421 }
422
423 if (err->page_id == TCP_RESET) {
424 if (err->request) {
425 debugs(4, 2, "RSTing this reply");
426 err->request->flags.setResetTCP();
427 }
428 }
429
430 entry->lock();
431 entry->buffer();
432 entry->replaceHttpReply( err->BuildHttpReply() );
433 EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT);
434 entry->flush();
435 entry->complete();
436 entry->negativeCache();
437 entry->releaseRequest();
438 entry->unlock();
439 errorStateFree(err);
440 }
441
442 void
443 errorSend(int fd, ErrorState * err)
444 {
445 HttpReply *rep;
446 debugs(4, 3, "errorSend: FD " << fd << ", err=" << err);
447 assert(fd >= 0);
448 /*
449 * ugh, this is how we make sure error codes get back to
450 * the client side for logging and error tracking.
451 */
452
453 if (err->request)
454 err->request->errType = err->type;
455
456 /* moved in front of errorBuildBuf @?@ */
457 err->flags.flag_cbdata = 1;
458
459 rep = err->BuildHttpReply();
460
461 comm_write_mbuf(fd, rep->pack(), errorSendComplete, err);
462
463 delete rep;
464 }
465
466 /**
467 \ingroup ErrorPageAPI
468 *
469 * Called by commHandleWrite() after data has been written
470 * to the client socket.
471 *
472 \note If there is a callback, the callback is responsible for
473 * closing the FD, otherwise we do it ourselves.
474 */
475 static void
476 errorSendComplete(int fd, char *bufnotused, size_t size, comm_err_t errflag, int xerrno, void *data)
477 {
478 ErrorState *err = static_cast<ErrorState *>(data);
479 debugs(4, 3, "errorSendComplete: FD " << fd << ", size=" << size);
480
481 if (errflag != COMM_ERR_CLOSING) {
482 if (err->callback) {
483 debugs(4, 3, "errorSendComplete: callback");
484 err->callback(fd, err->callback_data, size);
485 } else {
486 comm_close(fd);
487 debugs(4, 3, "errorSendComplete: comm_close");
488 }
489 }
490
491 errorStateFree(err);
492 }
493
494 void
495 errorStateFree(ErrorState * err)
496 {
497 HTTPMSGUNLOCK(err->request);
498 safe_free(err->redirect_url);
499 safe_free(err->url);
500 safe_free(err->request_hdrs);
501 wordlistDestroy(&err->ftp.server_msg);
502 safe_free(err->ftp.request);
503 safe_free(err->ftp.reply);
504 err->auth_user_request = NULL;
505 safe_free(err->err_msg);
506 #if USE_ERR_LOCALES
507 if (err->err_language != Config.errorDefaultLanguage)
508 #endif
509 safe_free(err->err_language);
510 cbdataFree(err);
511 }
512
513 int
514 ErrorState::Dump(MemBuf * mb)
515 {
516 MemBuf str;
517 const char *p = NULL; /* takes priority over mb if set */
518 char ntoabuf[MAX_IPSTRLEN];
519
520 str.reset();
521 /* email subject line */
522 str.Printf("CacheErrorInfo - %s", errorPageName(type));
523 mb->Printf("?subject=%s", rfc1738_escape_part(str.buf));
524 str.reset();
525 /* email body */
526 str.Printf("CacheHost: %s\r\n", getMyHostname());
527 /* - Err Msgs */
528 str.Printf("ErrPage: %s\r\n", errorPageName(type));
529
530 if (xerrno) {
531 str.Printf("Err: (%d) %s\r\n", xerrno, strerror(xerrno));
532 } else {
533 str.Printf("Err: [none]\r\n");
534 }
535
536 if (auth_user_request->denyMessage())
537 str.Printf("Auth ErrMsg: %s\r\n", auth_user_request->denyMessage());
538
539 if (dnsError.size() > 0)
540 str.Printf("DNS ErrMsg: %s\r\n", dnsError.termedBuf());
541
542 /* - TimeStamp */
543 str.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime));
544
545 /* - IP stuff */
546 str.Printf("ClientIP: %s\r\n", src_addr.NtoA(ntoabuf,MAX_IPSTRLEN));
547
548 if (request && request->hier.host[0] != '\0') {
549 str.Printf("ServerIP: %s\r\n", request->hier.host);
550 }
551
552 str.Printf("\r\n");
553 /* - HTTP stuff */
554 str.Printf("HTTP Request:\r\n");
555
556 if (NULL != request) {
557 Packer pck;
558 String urlpath_or_slash;
559
560 if (request->urlpath.size() != 0)
561 urlpath_or_slash = request->urlpath;
562 else
563 urlpath_or_slash = "/";
564
565 str.Printf("%s " SQUIDSTRINGPH " HTTP/%d.%d\n",
566 RequestMethodStr(request->method),
567 SQUIDSTRINGPRINT(urlpath_or_slash),
568 request->http_ver.major, request->http_ver.minor);
569 packerToMemInit(&pck, &str);
570 request->header.packInto(&pck);
571 packerClean(&pck);
572 } else if (request_hdrs) {
573 p = request_hdrs;
574 } else {
575 p = "[none]";
576 }
577
578 str.Printf("\r\n");
579 /* - FTP stuff */
580
581 if (ftp.request) {
582 str.Printf("FTP Request: %s\r\n", ftp.request);
583 str.Printf("FTP Reply: %s\r\n", ftp.reply);
584 str.Printf("FTP Msg: ");
585 wordlistCat(ftp.server_msg, &str);
586 str.Printf("\r\n");
587 }
588
589 str.Printf("\r\n");
590 mb->Printf("&body=%s", rfc1738_escape_part(str.buf));
591 str.clean();
592 return 0;
593 }
594
595 /// \ingroup ErrorPageInternal
596 #define CVT_BUF_SZ 512
597
598 const char *
599 ErrorState::Convert(char token, bool url_presentable)
600 {
601 static MemBuf mb;
602 const char *p = NULL; /* takes priority over mb if set */
603 int do_quote = 1;
604 int no_urlescape = 1; /* item is NOT to be further URL-encoded */
605 char ntoabuf[MAX_IPSTRLEN];
606
607 mb.reset();
608
609 switch (token) {
610
611 case 'a':
612 if (request && request->auth_user_request != NULL)
613 p = request->auth_user_request->username();
614 if (!p)
615 p = "-";
616 break;
617
618 case 'B':
619 if (url_presentable) break;
620 p = request ? ftpUrlWith2f(request) : "[no URL]";
621 no_urlescape = 1;
622 break;
623
624 case 'c':
625 if (url_presentable) break;
626 p = errorPageName(type);
627 break;
628
629 case 'e':
630 mb.Printf("%d", xerrno);
631 break;
632
633 case 'E':
634 if (xerrno)
635 mb.Printf("(%d) %s", xerrno, strerror(xerrno));
636 else
637 mb.Printf("[No Error]");
638 break;
639
640 case 'f':
641 if (url_presentable) break;
642 /* FTP REQUEST LINE */
643 if (ftp.request)
644 p = ftp.request;
645 else
646 p = "nothing";
647 break;
648
649 case 'F':
650 if (url_presentable) break;
651 /* FTP REPLY LINE */
652 if (ftp.request)
653 p = ftp.reply;
654 else
655 p = "nothing";
656 break;
657
658 case 'g':
659 if (url_presentable) break;
660 /* FTP SERVER MESSAGE */
661 if (ftp.server_msg)
662 wordlistCat(ftp.server_msg, &mb);
663 else if (ftp.listing) {
664 mb.append(ftp.listing->content(), ftp.listing->contentSize());
665 do_quote = 0;
666 }
667 break;
668
669 case 'h':
670 mb.Printf("%s", getMyHostname());
671 break;
672
673 case 'H':
674 if (request) {
675 if (request->hier.host[0] != '\0') // if non-empty string.
676 p = request->hier.host;
677 else
678 p = request->GetHost();
679 } else if (!url_presentable)
680 p = "[unknown host]";
681 break;
682
683 case 'i':
684 mb.Printf("%s", src_addr.NtoA(ntoabuf,MAX_IPSTRLEN));
685 break;
686
687 case 'I':
688 if (request && request->hier.host[0] != '\0') // if non-empty string
689 mb.Printf("%s", request->hier.host);
690 else if (!url_presentable)
691 p = "[unknown]";
692 break;
693
694 case 'l':
695 if (url_presentable) break;
696 mb.append(error_stylesheet.content(), error_stylesheet.contentSize());
697 do_quote = 0;
698 break;
699
700 case 'L':
701 if (url_presentable) break;
702 if (Config.errHtmlText) {
703 mb.Printf("%s", Config.errHtmlText);
704 do_quote = 0;
705 } else if (!url_presentable)
706 p = "[not available]";
707 break;
708
709 case 'm':
710 if (url_presentable) break;
711 p = auth_user_request->denyMessage("[not available]");
712 break;
713
714 case 'M':
715 p = request ? RequestMethodStr(request->method) : "[unknown method]";
716 break;
717
718 case 'o':
719 p = request ? request->extacl_message.termedBuf() : external_acl_message;
720 if (!p)
721 p = "[not available]";
722 break;
723
724 case 'p':
725 if (request) {
726 mb.Printf("%d", (int) request->port);
727 } else if (!url_presentable) {
728 p = "[unknown port]";
729 }
730 break;
731
732 case 'P':
733 p = request ? ProtocolStr[request->protocol] : "[unknown protocol]";
734 break;
735
736 case 'R':
737 if (url_presentable) {
738 p = (request->urlpath.size() != 0 ? request->urlpath.termedBuf() : "/");
739 break;
740 }
741 if (NULL != request) {
742 Packer pck;
743 String urlpath_or_slash;
744
745 if (request->urlpath.size() != 0)
746 urlpath_or_slash = request->urlpath;
747 else
748 urlpath_or_slash = "/";
749
750 mb.Printf("%s " SQUIDSTRINGPH " HTTP/%d.%d\n",
751 RequestMethodStr(request->method),
752 SQUIDSTRINGPRINT(urlpath_or_slash),
753 request->http_ver.major, request->http_ver.minor);
754 packerToMemInit(&pck, &mb);
755 request->header.packInto(&pck);
756 packerClean(&pck);
757 } else if (request_hdrs) {
758 p = request_hdrs;
759 } else {
760 p = "[no request]";
761 }
762 break;
763
764 case 's':
765 /* for backward compat we make %s show the full URL. Drop this in some future release. */
766 if (url_presentable) {
767 p = request ? urlCanonical(request) : url;
768 debugs(0,0, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
769 } else
770 p = visible_appname_string;
771 break;
772
773 case 'S':
774 if (url_presentable) break;
775 /* signature may contain %-escapes, recursion */
776 if (page_id != ERR_SQUID_SIGNATURE) {
777 const int saved_id = page_id;
778 page_id = ERR_SQUID_SIGNATURE;
779 MemBuf *sign_mb = BuildContent();
780 mb.Printf("%s", sign_mb->content());
781 sign_mb->clean();
782 delete sign_mb;
783 page_id = saved_id;
784 do_quote = 0;
785 } else {
786 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
787 p = "[%S]";
788 }
789 break;
790
791 case 't':
792 mb.Printf("%s", mkhttpdlogtime(&squid_curtime));
793 break;
794
795 case 'T':
796 mb.Printf("%s", mkrfc1123(squid_curtime));
797 break;
798
799 case 'U':
800 /* Using the fake-https version of canonical so error pages see https:// */
801 /* even when the url-path cannot be shown as more than '*' */
802 p = request ? urlCanonicalFakeHttps(request) : url ? url : "[no URL]";
803 break;
804
805 case 'u':
806 p = request ? urlCanonical(request) : url ? url : "[no URL]";
807 break;
808
809 case 'w':
810 if (Config.adminEmail)
811 mb.Printf("%s", Config.adminEmail);
812 else if (!url_presentable)
813 p = "[unknown]";
814 break;
815
816 case 'W':
817 if (url_presentable) break;
818 if (Config.adminEmail && Config.onoff.emailErrData)
819 Dump(&mb);
820 break;
821
822 case 'z':
823 if (url_presentable) break;
824 if (dnsError.size() > 0)
825 p = dnsError.termedBuf();
826 else if (ftp.cwd_msg)
827 p = ftp.cwd_msg;
828 else
829 p = "[unknown]";
830 break;
831
832 case 'Z':
833 if (url_presentable) break;
834 if (err_msg)
835 p = err_msg;
836 else
837 p = "[unknown]";
838 break;
839
840 case '%':
841 p = "%";
842 break;
843
844 default:
845 mb.Printf("%%%c", token);
846 do_quote = 0;
847 break;
848 }
849
850 if (!p)
851 p = mb.buf; /* do not use mb after this assignment! */
852
853 assert(p);
854
855 debugs(4, 3, "errorConvert: %%" << token << " --> '" << p << "'" );
856
857 if (do_quote)
858 p = html_quote(p);
859
860 if (url_presentable && !no_urlescape)
861 p = rfc1738_escape_part(p);
862
863 return p;
864 }
865
866 void
867 ErrorState::DenyInfoLocation(const char *name, HttpRequest *aRequest, MemBuf &result)
868 {
869 char const *m = name;
870 char const *p = m;
871 char const *t;
872
873 while ((p = strchr(m, '%'))) {
874 result.append(m, p - m); /* copy */
875 t = Convert(*++p, true); /* convert */
876 result.Printf("%s", t); /* copy */
877 m = p + 1; /* advance */
878 }
879
880 if (*m)
881 result.Printf("%s", m); /* copy tail */
882
883 assert((size_t)result.contentSize() == strlen(result.content()));
884 }
885
886 HttpReply *
887 ErrorState::BuildHttpReply()
888 {
889 HttpReply *rep = new HttpReply;
890 const char *name = errorPageName(page_id);
891 /* no LMT for error pages; error pages expire immediately */
892
893 if (strchr(name, ':')) {
894 /* Redirection */
895 rep->setHeaders(HTTP_MOVED_TEMPORARILY, NULL, "text/html", 0, 0, -1);
896
897 if (request) {
898 MemBuf redirect_location;
899 redirect_location.init();
900 DenyInfoLocation(name, request, redirect_location);
901 httpHeaderPutStrf(&rep->header, HDR_LOCATION, "%s", redirect_location.content() );
902 }
903
904 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%d %s", httpStatus, "Access Denied");
905 } else {
906 MemBuf *content = BuildContent();
907 rep->setHeaders(httpStatus, NULL, "text/html", content->contentSize(), 0, -1);
908 /*
909 * include some information for downstream caches. Implicit
910 * replaceable content. This isn't quite sufficient. xerrno is not
911 * necessarily meaningful to another system, so we really should
912 * expand it. Additionally, we should identify ourselves. Someone
913 * might want to know. Someone _will_ want to know OTOH, the first
914 * X-CACHE-MISS entry should tell us who.
915 */
916 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%s %d", name, xerrno);
917
918 #if USE_ERR_LOCALES
919 /*
920 * If error page auto-negotiate is enabled in any way, send the Vary.
921 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
922 * We have even better reasons though:
923 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
924 */
925 if (!Config.errorDirectory) {
926 /* We 'negotiated' this ONLY from the Accept-Language. */
927 rep->header.delById(HDR_VARY);
928 rep->header.putStr(HDR_VARY, "Accept-Language");
929 }
930
931 /* add the Content-Language header according to RFC section 14.12 */
932 if (err_language) {
933 rep->header.putStr(HDR_CONTENT_LANGUAGE, err_language);
934 } else
935 #endif /* USE_ERROR_LOCALES */
936 {
937 /* default templates are in English */
938 /* language is known unless error_directory override used */
939 if (!Config.errorDirectory)
940 rep->header.putStr(HDR_CONTENT_LANGUAGE, "en");
941 }
942
943 httpBodySet(&rep->body, content);
944 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
945 }
946
947 return rep;
948 }
949
950 MemBuf *
951 ErrorState::BuildContent()
952 {
953 MemBuf *content = new MemBuf;
954 const char *m = NULL;
955 const char *p;
956 const char *t;
957
958 assert(page_id > ERR_NONE && page_id < error_page_count);
959
960 #if USE_ERR_LOCALES
961 String hdr;
962 char dir[256];
963 int l = 0;
964
965 /** error_directory option in squid.conf overrides translations.
966 * Custom errors are always found either in error_directory or the templates directory.
967 * Otherwise locate the Accept-Language header
968 */
969 if (!Config.errorDirectory && page_id < ERR_MAX && request && request->header.getList(HDR_ACCEPT_LANGUAGE, &hdr) ) {
970
971 size_t pos = 0; // current parsing position in header string
972 char *reset = NULL; // where to reset the p pointer for each new tag file
973 char *dt = NULL;
974
975 /* prep the directory path string to prevent snprintf ... */
976 l = strlen(DEFAULT_SQUID_ERROR_DIR);
977 memcpy(dir, DEFAULT_SQUID_ERROR_DIR, l);
978 dir[ l++ ] = '/';
979 reset = dt = dir + l;
980
981 debugs(4, 6, HERE << "Testing Header: '" << hdr << "'");
982
983 while ( pos < hdr.size() ) {
984
985 /* skip any initial whitespace. */
986 while (pos < hdr.size() && xisspace(hdr[pos])) pos++;
987
988 /*
989 * Header value format:
990 * - sequence of whitespace delimited tags
991 * - each tag may suffix with ';'.* which we can ignore.
992 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
993 * with preference given to an exact match.
994 */
995 bool invalid_byte = false;
996 while (pos < hdr.size() && hdr[pos] != ';' && hdr[pos] != ',' && !xisspace(hdr[pos]) && dt < (dir+256) ) {
997 if (!invalid_byte) {
998 #if HTTP_VIOLATIONS
999 // if accepting violations we may as well accept some broken browsers
1000 // which may send us the right code, wrong ISO formatting.
1001 if (hdr[pos] == '_')
1002 *dt = '-';
1003 else
1004 #endif
1005 *dt = xtolower(hdr[pos]);
1006 // valid codes only contain A-Z, hyphen (-) and *
1007 if (*dt != '-' && *dt != '*' && (*dt < 'a' || *dt > 'z') )
1008 invalid_byte = true;
1009 else
1010 dt++; // move to next destination byte.
1011 }
1012 pos++;
1013 }
1014 *dt++ = '\0'; // nul-terminated the filename content string before system use.
1015
1016 debugs(4, 9, HERE << "STATE: dt='" << dt << "', reset='" << reset << "', pos=" << pos << ", buf='" << ((pos < hdr.size()) ? hdr.substr(pos,hdr.size()) : "") << "'");
1017
1018 /* if we found anything we might use, try it. */
1019 if (*reset != '\0' && !invalid_byte) {
1020
1021 /* wildcard uses the configured default language */
1022 if (reset[0] == '*' && reset[1] == '\0') {
1023 debugs(4, 6, HERE << "Found language '" << reset << "'. Using configured default.");
1024 m = error_text[page_id];
1025 if (!Config.errorDirectory)
1026 err_language = Config.errorDefaultLanguage;
1027 break;
1028 }
1029
1030 debugs(4, 6, HERE << "Found language '" << reset << "', testing for available template in: '" << dir << "'");
1031
1032 m = errorTryLoadText( err_type_str[page_id], dir, false);
1033
1034 if (m) {
1035 /* store the language we found for the Content-Language reply header */
1036 err_language = xstrdup(reset);
1037 break;
1038 } else if (Config.errorLogMissingLanguages) {
1039 debugs(4, DBG_IMPORTANT, "WARNING: Error Pages Missing Language: " << reset);
1040 }
1041
1042 #if HAVE_GLOB
1043 if ( (dt - reset) == 2) {
1044 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
1045 /* use first result. */
1046 debugs(4,2, HERE << "wildcard fallback errors not coded yet.");
1047 }
1048 #endif
1049 }
1050
1051 dt = reset; // reset for next tag testing. we replace the failed name instead of cloning.
1052
1053 // IFF we terminated the tag on whitespace or ';' we need to skip to the next ',' or end of header.
1054 while (pos < hdr.size() && hdr[pos] != ',') pos++;
1055 if (hdr[pos] == ',') pos++;
1056 }
1057 }
1058 #endif /* USE_ERR_LOCALES */
1059
1060 /** \par
1061 * If client-specific error templates are not enabled or available.
1062 * fall back to the old style squid.conf settings.
1063 */
1064 if (!m) {
1065 m = error_text[page_id];
1066 #if USE_ERR_LOCALES
1067 if (!Config.errorDirectory)
1068 err_language = Config.errorDefaultLanguage;
1069 #endif
1070 debugs(4, 2, HERE << "No existing error page language negotiated for " << errorPageName(page_id) << ". Using default error file.");
1071 }
1072
1073 assert(m);
1074 content->init();
1075
1076 while ((p = strchr(m, '%'))) {
1077 content->append(m, p - m); /* copy */
1078 t = Convert(*++p, false); /* convert */
1079 content->Printf("%s", t); /* copy */
1080 m = p + 1; /* advance */
1081 }
1082
1083 if (*m)
1084 content->Printf("%s", m); /* copy tail */
1085
1086 assert((size_t)content->contentSize() == strlen(content->content()));
1087
1088 return content;
1089 }