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