]> git.ipfire.org Git - thirdparty/squid.git/blob - src/errorpage.cc
Sync from HEAD
[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 = external_acl_message ? external_acl_message : "[not available]";
720 break;
721
722 case 'p':
723 if (request) {
724 mb.Printf("%d", (int) request->port);
725 } else if (!url_presentable) {
726 p = "[unknown port]";
727 }
728 break;
729
730 case 'P':
731 p = request ? ProtocolStr[request->protocol] : "[unknown protocol]";
732 break;
733
734 case 'R':
735 if (url_presentable) {
736 p = (request->urlpath.size() != 0 ? request->urlpath.termedBuf() : "/");
737 break;
738 }
739 if (NULL != request) {
740 Packer pck;
741 String urlpath_or_slash;
742
743 if (request->urlpath.size() != 0)
744 urlpath_or_slash = request->urlpath;
745 else
746 urlpath_or_slash = "/";
747
748 mb.Printf("%s " SQUIDSTRINGPH " HTTP/%d.%d\n",
749 RequestMethodStr(request->method),
750 SQUIDSTRINGPRINT(urlpath_or_slash),
751 request->http_ver.major, request->http_ver.minor);
752 packerToMemInit(&pck, &mb);
753 request->header.packInto(&pck);
754 packerClean(&pck);
755 } else if (request_hdrs) {
756 p = request_hdrs;
757 } else {
758 p = "[no request]";
759 }
760 break;
761
762 case 's':
763 /* for backward compat we make %s show the full URL. Drop this in some future release. */
764 if (url_presentable) {
765 p = request ? urlCanonical(request) : url;
766 debugs(0,0, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
767 } else
768 p = visible_appname_string;
769 break;
770
771 case 'S':
772 if (url_presentable) break;
773 /* signature may contain %-escapes, recursion */
774 if (page_id != ERR_SQUID_SIGNATURE) {
775 const int saved_id = page_id;
776 page_id = ERR_SQUID_SIGNATURE;
777 MemBuf *sign_mb = BuildContent();
778 mb.Printf("%s", sign_mb->content());
779 sign_mb->clean();
780 delete sign_mb;
781 page_id = saved_id;
782 do_quote = 0;
783 } else {
784 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
785 p = "[%S]";
786 }
787 break;
788
789 case 't':
790 mb.Printf("%s", mkhttpdlogtime(&squid_curtime));
791 break;
792
793 case 'T':
794 mb.Printf("%s", mkrfc1123(squid_curtime));
795 break;
796
797 case 'U':
798 /* Using the fake-https version of canonical so error pages see https:// */
799 /* even when the url-path cannot be shown as more than '*' */
800 p = request ? urlCanonicalFakeHttps(request) : url ? url : "[no URL]";
801 break;
802
803 case 'u':
804 p = request ? urlCanonical(request) : url ? url : "[no URL]";
805 break;
806
807 case 'w':
808 if (Config.adminEmail)
809 mb.Printf("%s", Config.adminEmail);
810 else if (!url_presentable)
811 p = "[unknown]";
812 break;
813
814 case 'W':
815 if (url_presentable) break;
816 if (Config.adminEmail && Config.onoff.emailErrData)
817 Dump(&mb);
818 break;
819
820 case 'z':
821 if (url_presentable) break;
822 if (dnsError.size() > 0)
823 p = dnsError.termedBuf();
824 else if (ftp.cwd_msg)
825 p = ftp.cwd_msg;
826 else
827 p = "[unknown]";
828 break;
829
830 case 'Z':
831 if (url_presentable) break;
832 if (err_msg)
833 p = err_msg;
834 else
835 p = "[unknown]";
836 break;
837
838 case '%':
839 p = "%";
840 break;
841
842 default:
843 mb.Printf("%%%c", token);
844 do_quote = 0;
845 break;
846 }
847
848 if (!p)
849 p = mb.buf; /* do not use mb after this assignment! */
850
851 assert(p);
852
853 debugs(4, 3, "errorConvert: %%" << token << " --> '" << p << "'" );
854
855 if (do_quote)
856 p = html_quote(p);
857
858 if (url_presentable && !no_urlescape)
859 p = rfc1738_escape_part(p);
860
861 return p;
862 }
863
864 void
865 ErrorState::DenyInfoLocation(const char *name, HttpRequest *aRequest, MemBuf &result)
866 {
867 char const *m = name;
868 char const *p = m;
869 char const *t;
870
871 while ((p = strchr(m, '%'))) {
872 result.append(m, p - m); /* copy */
873 t = Convert(*++p, true); /* convert */
874 result.Printf("%s", t); /* copy */
875 m = p + 1; /* advance */
876 }
877
878 if (*m)
879 result.Printf("%s", m); /* copy tail */
880
881 assert((size_t)result.contentSize() == strlen(result.content()));
882 }
883
884 HttpReply *
885 ErrorState::BuildHttpReply()
886 {
887 HttpReply *rep = new HttpReply;
888 const char *name = errorPageName(page_id);
889 /* no LMT for error pages; error pages expire immediately */
890 HttpVersion version(1, 0);
891
892 if (strchr(name, ':')) {
893 /* Redirection */
894 rep->setHeaders(version, HTTP_MOVED_TEMPORARILY, NULL, "text/html", 0, 0, -1);
895
896 if (request) {
897 MemBuf redirect_location;
898 redirect_location.init();
899 DenyInfoLocation(name, request, redirect_location);
900 httpHeaderPutStrf(&rep->header, HDR_LOCATION, "%s", redirect_location.content() );
901 }
902
903 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%d %s", httpStatus, "Access Denied");
904 } else {
905 MemBuf *content = BuildContent();
906 rep->setHeaders(version, httpStatus, NULL, "text/html", content->contentSize(), 0, -1);
907 /*
908 * include some information for downstream caches. Implicit
909 * replaceable content. This isn't quite sufficient. xerrno is not
910 * necessarily meaningful to another system, so we really should
911 * expand it. Additionally, we should identify ourselves. Someone
912 * might want to know. Someone _will_ want to know OTOH, the first
913 * X-CACHE-MISS entry should tell us who.
914 */
915 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%s %d", name, xerrno);
916
917 #if USE_ERR_LOCALES
918 /*
919 * If error page auto-negotiate is enabled in any way, send the Vary.
920 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
921 * We have even better reasons though:
922 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
923 */
924 if (!Config.errorDirectory) {
925 /* We 'negotiated' this ONLY from the Accept-Language. */
926 rep->header.delById(HDR_VARY);
927 rep->header.putStr(HDR_VARY, "Accept-Language");
928 }
929
930 /* add the Content-Language header according to RFC section 14.12 */
931 if (err_language) {
932 rep->header.putStr(HDR_CONTENT_LANGUAGE, err_language);
933 } else
934 #endif /* USE_ERROR_LOCALES */
935 {
936 /* default templates are in English */
937 /* language is known unless error_directory override used */
938 if (!Config.errorDirectory)
939 rep->header.putStr(HDR_CONTENT_LANGUAGE, "en");
940 }
941
942 httpBodySet(&rep->body, content);
943 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
944 }
945
946 return rep;
947 }
948
949 MemBuf *
950 ErrorState::BuildContent()
951 {
952 MemBuf *content = new MemBuf;
953 const char *m = NULL;
954 const char *p;
955 const char *t;
956
957 assert(page_id > ERR_NONE && page_id < error_page_count);
958
959 #if USE_ERR_LOCALES
960 String hdr;
961 char dir[256];
962 int l = 0;
963
964 /** error_directory option in squid.conf overrides translations.
965 * Custom errors are always found either in error_directory or the templates directory.
966 * Otherwise locate the Accept-Language header
967 */
968 if (!Config.errorDirectory && page_id < ERR_MAX && request && request->header.getList(HDR_ACCEPT_LANGUAGE, &hdr) ) {
969
970 size_t pos = 0; // current parsing position in header string
971 char *reset = NULL; // where to reset the p pointer for each new tag file
972 char *dt = NULL;
973
974 /* prep the directory path string to prevent snprintf ... */
975 l = strlen(DEFAULT_SQUID_ERROR_DIR);
976 memcpy(dir, DEFAULT_SQUID_ERROR_DIR, l);
977 dir[ l++ ] = '/';
978 reset = dt = dir + l;
979
980 debugs(4, 6, HERE << "Testing Header: '" << hdr << "'");
981
982 while ( pos < hdr.size() ) {
983
984 /* skip any initial whitespace. */
985 while (pos < hdr.size() && xisspace(hdr[pos])) pos++;
986
987 /*
988 * Header value format:
989 * - sequence of whitespace delimited tags
990 * - each tag may suffix with ';'.* which we can ignore.
991 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
992 * with preference given to an exact match.
993 */
994 bool invalid_byte = false;
995 while (pos < hdr.size() && hdr[pos] != ';' && hdr[pos] != ',' && !xisspace(hdr[pos]) && dt < (dir+256) ) {
996 if (!invalid_byte) {
997 #if HTTP_VIOLATIONS
998 // if accepting violations we may as well accept some broken browsers
999 // which may send us the right code, wrong ISO formatting.
1000 if (hdr[pos] == '_')
1001 *dt = '-';
1002 else
1003 #endif
1004 *dt = xtolower(hdr[pos]);
1005 // valid codes only contain A-Z, hyphen (-) and *
1006 if (*dt != '-' && *dt != '*' && (*dt < 'a' || *dt > 'z') )
1007 invalid_byte = true;
1008 else
1009 dt++; // move to next destination byte.
1010 }
1011 pos++;
1012 }
1013 *dt++ = '\0'; // nul-terminated the filename content string before system use.
1014
1015 debugs(4, 9, HERE << "STATE: dt='" << dt << "', reset='" << reset << "', pos=" << pos << ", buf='" << ((pos < hdr.size()) ? hdr.substr(pos,hdr.size()) : "") << "'");
1016
1017 /* if we found anything we might use, try it. */
1018 if (*reset != '\0' && !invalid_byte) {
1019
1020 /* wildcard uses the configured default language */
1021 if (reset[0] == '*' && reset[1] == '\0') {
1022 debugs(4, 6, HERE << "Found language '" << reset << "'. Using configured default.");
1023 m = error_text[page_id];
1024 if (!Config.errorDirectory)
1025 err_language = Config.errorDefaultLanguage;
1026 break;
1027 }
1028
1029 debugs(4, 6, HERE << "Found language '" << reset << "', testing for available template in: '" << dir << "'");
1030
1031 m = errorTryLoadText( err_type_str[page_id], dir, false);
1032
1033 if (m) {
1034 /* store the language we found for the Content-Language reply header */
1035 err_language = xstrdup(reset);
1036 break;
1037 } else if (Config.errorLogMissingLanguages) {
1038 debugs(4, DBG_IMPORTANT, "WARNING: Error Pages Missing Language: " << reset);
1039 }
1040
1041 #if HAVE_GLOB
1042 if ( (dt - reset) == 2) {
1043 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
1044 /* use first result. */
1045 debugs(4,2, HERE << "wildcard fallback errors not coded yet.");
1046 }
1047 #endif
1048 }
1049
1050 dt = reset; // reset for next tag testing. we replace the failed name instead of cloning.
1051
1052 // IFF we terminated the tag on whitespace or ';' we need to skip to the next ',' or end of header.
1053 while (pos < hdr.size() && hdr[pos] != ',') pos++;
1054 if (hdr[pos] == ',') pos++;
1055 }
1056 }
1057 #endif /* USE_ERR_LOCALES */
1058
1059 /** \par
1060 * If client-specific error templates are not enabled or available.
1061 * fall back to the old style squid.conf settings.
1062 */
1063 if (!m) {
1064 m = error_text[page_id];
1065 #if USE_ERR_LOCALES
1066 if (!Config.errorDirectory)
1067 err_language = Config.errorDefaultLanguage;
1068 #endif
1069 debugs(4, 2, HERE << "No existing error page language negotiated for " << errorPageName(page_id) << ". Using default error file.");
1070 }
1071
1072 assert(m);
1073 content->init();
1074
1075 while ((p = strchr(m, '%'))) {
1076 content->append(m, p - m); /* copy */
1077 t = Convert(*++p, false); /* convert */
1078 content->Printf("%s", t); /* copy */
1079 m = p + 1; /* advance */
1080 }
1081
1082 if (*m)
1083 content->Printf("%s", m); /* copy tail */
1084
1085 assert((size_t)content->contentSize() == strlen(content->content()));
1086
1087 return content;
1088 }