]> git.ipfire.org Git - thirdparty/squid.git/blob - src/errorpage.cc
Merge form 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
36 #include "auth/UserRequest.h"
37 #include "comm/Connection.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 comm_write_mbuf(conn, mb, errorSendComplete, err);
465 delete mb;
466 delete rep;
467 }
468
469 /**
470 \ingroup ErrorPageAPI
471 *
472 * Called by commHandleWrite() after data has been written
473 * to the client socket.
474 *
475 \note If there is a callback, the callback is responsible for
476 * closing the FD, otherwise we do it ourselves.
477 */
478 static void
479 errorSendComplete(const Comm::ConnectionPointer &conn, char *bufnotused, size_t size, comm_err_t errflag, int xerrno, void *data)
480 {
481 ErrorState *err = static_cast<ErrorState *>(data);
482 debugs(4, 3, HERE << conn << ", size=" << size);
483
484 if (errflag != COMM_ERR_CLOSING) {
485 if (err->callback) {
486 debugs(4, 3, "errorSendComplete: callback");
487 err->callback(conn->fd, err->callback_data, size);
488 } else {
489 debugs(4, 3, "errorSendComplete: comm_close");
490 conn->close();
491 }
492 }
493
494 errorStateFree(err);
495 }
496
497 void
498 errorStateFree(ErrorState * err)
499 {
500 HTTPMSGUNLOCK(err->request);
501 safe_free(err->redirect_url);
502 safe_free(err->url);
503 safe_free(err->request_hdrs);
504 wordlistDestroy(&err->ftp.server_msg);
505 safe_free(err->ftp.request);
506 safe_free(err->ftp.reply);
507 err->auth_user_request = NULL;
508 safe_free(err->err_msg);
509 #if USE_ERR_LOCALES
510 if (err->err_language != Config.errorDefaultLanguage)
511 #endif
512 safe_free(err->err_language);
513 cbdataFree(err);
514 }
515
516 int
517 ErrorState::Dump(MemBuf * mb)
518 {
519 MemBuf str;
520 const char *p = NULL; /* takes priority over mb if set */
521 char ntoabuf[MAX_IPSTRLEN];
522
523 str.reset();
524 /* email subject line */
525 str.Printf("CacheErrorInfo - %s", errorPageName(type));
526 mb->Printf("?subject=%s", rfc1738_escape_part(str.buf));
527 str.reset();
528 /* email body */
529 str.Printf("CacheHost: %s\r\n", getMyHostname());
530 /* - Err Msgs */
531 str.Printf("ErrPage: %s\r\n", errorPageName(type));
532
533 if (xerrno) {
534 str.Printf("Err: (%d) %s\r\n", xerrno, strerror(xerrno));
535 } else {
536 str.Printf("Err: [none]\r\n");
537 }
538
539 if (auth_user_request->denyMessage())
540 str.Printf("Auth ErrMsg: %s\r\n", auth_user_request->denyMessage());
541
542 if (dnsError.size() > 0)
543 str.Printf("DNS ErrMsg: %s\r\n", dnsError.termedBuf());
544
545 /* - TimeStamp */
546 str.Printf("TimeStamp: %s\r\n\r\n", mkrfc1123(squid_curtime));
547
548 /* - IP stuff */
549 str.Printf("ClientIP: %s\r\n", src_addr.NtoA(ntoabuf,MAX_IPSTRLEN));
550
551 if (request && request->hier.host[0] != '\0') {
552 str.Printf("ServerIP: %s\r\n", request->hier.host);
553 }
554
555 str.Printf("\r\n");
556 /* - HTTP stuff */
557 str.Printf("HTTP Request:\r\n");
558
559 if (NULL != request) {
560 Packer pck;
561 String urlpath_or_slash;
562
563 if (request->urlpath.size() != 0)
564 urlpath_or_slash = request->urlpath;
565 else
566 urlpath_or_slash = "/";
567
568 str.Printf("%s " SQUIDSTRINGPH " HTTP/%d.%d\n",
569 RequestMethodStr(request->method),
570 SQUIDSTRINGPRINT(urlpath_or_slash),
571 request->http_ver.major, request->http_ver.minor);
572 packerToMemInit(&pck, &str);
573 request->header.packInto(&pck);
574 packerClean(&pck);
575 } else if (request_hdrs) {
576 p = request_hdrs;
577 } else {
578 p = "[none]";
579 }
580
581 str.Printf("\r\n");
582 /* - FTP stuff */
583
584 if (ftp.request) {
585 str.Printf("FTP Request: %s\r\n", ftp.request);
586 str.Printf("FTP Reply: %s\r\n", ftp.reply);
587 str.Printf("FTP Msg: ");
588 wordlistCat(ftp.server_msg, &str);
589 str.Printf("\r\n");
590 }
591
592 str.Printf("\r\n");
593 mb->Printf("&body=%s", rfc1738_escape_part(str.buf));
594 str.clean();
595 return 0;
596 }
597
598 /// \ingroup ErrorPageInternal
599 #define CVT_BUF_SZ 512
600
601 const char *
602 ErrorState::Convert(char token, bool building_deny_info_url)
603 {
604 static MemBuf mb;
605 const char *p = NULL; /* takes priority over mb if set */
606 int do_quote = 1;
607 int no_urlescape = 0; /* if true then item is NOT to be further URL-encoded */
608 char ntoabuf[MAX_IPSTRLEN];
609
610 mb.reset();
611
612 switch (token) {
613
614 case 'a':
615 if (request && request->auth_user_request != NULL)
616 p = request->auth_user_request->username();
617 if (!p)
618 p = "-";
619 break;
620
621 case 'B':
622 if (building_deny_info_url) break;
623 p = request ? ftpUrlWith2f(request) : "[no URL]";
624 break;
625
626 case 'c':
627 if (building_deny_info_url) break;
628 p = errorPageName(type);
629 break;
630
631 case 'e':
632 mb.Printf("%d", xerrno);
633 break;
634
635 case 'E':
636 if (xerrno)
637 mb.Printf("(%d) %s", xerrno, strerror(xerrno));
638 else
639 mb.Printf("[No Error]");
640 break;
641
642 case 'f':
643 if (building_deny_info_url) break;
644 /* FTP REQUEST LINE */
645 if (ftp.request)
646 p = ftp.request;
647 else
648 p = "nothing";
649 break;
650
651 case 'F':
652 if (building_deny_info_url) break;
653 /* FTP REPLY LINE */
654 if (ftp.request)
655 p = ftp.reply;
656 else
657 p = "nothing";
658 break;
659
660 case 'g':
661 if (building_deny_info_url) break;
662 /* FTP SERVER MESSAGE */
663 if (ftp.server_msg)
664 wordlistCat(ftp.server_msg, &mb);
665 else if (ftp.listing) {
666 mb.append(ftp.listing->content(), ftp.listing->contentSize());
667 do_quote = 0;
668 }
669 break;
670
671 case 'h':
672 mb.Printf("%s", getMyHostname());
673 break;
674
675 case 'H':
676 if (request) {
677 if (request->hier.host[0] != '\0') // if non-empty string.
678 p = request->hier.host;
679 else
680 p = request->GetHost();
681 } else if (!building_deny_info_url)
682 p = "[unknown host]";
683 break;
684
685 case 'i':
686 mb.Printf("%s", src_addr.NtoA(ntoabuf,MAX_IPSTRLEN));
687 break;
688
689 case 'I':
690 if (request && request->hier.host[0] != '\0') // if non-empty string
691 mb.Printf("%s", request->hier.host);
692 else if (!building_deny_info_url)
693 p = "[unknown]";
694 break;
695
696 case 'l':
697 if (building_deny_info_url) break;
698 mb.append(error_stylesheet.content(), error_stylesheet.contentSize());
699 do_quote = 0;
700 break;
701
702 case 'L':
703 if (building_deny_info_url) break;
704 if (Config.errHtmlText) {
705 mb.Printf("%s", Config.errHtmlText);
706 do_quote = 0;
707 } else
708 p = "[not available]";
709 break;
710
711 case 'm':
712 if (building_deny_info_url) break;
713 p = auth_user_request->denyMessage("[not available]");
714 break;
715
716 case 'M':
717 if (request)
718 p = RequestMethodStr(request->method);
719 else if (!building_deny_info_url)
720 p= "[unknown method]";
721 break;
722
723 case 'o':
724 p = request ? request->extacl_message.termedBuf() : external_acl_message;
725 if (!p && !building_deny_info_url)
726 p = "[not available]";
727 break;
728
729 case 'p':
730 if (request) {
731 mb.Printf("%d", (int) request->port);
732 } else if (!building_deny_info_url) {
733 p = "[unknown port]";
734 }
735 break;
736
737 case 'P':
738 if (request) {
739 p = ProtocolStr[request->protocol];
740 } else if (!building_deny_info_url) {
741 p = "[unknown protocol]";
742 }
743 break;
744
745 case 'R':
746 if (building_deny_info_url) {
747 p = (request->urlpath.size() != 0 ? request->urlpath.termedBuf() : "/");
748 break;
749 }
750 if (NULL != request) {
751 Packer pck;
752 String urlpath_or_slash;
753
754 if (request->urlpath.size() != 0)
755 urlpath_or_slash = request->urlpath;
756 else
757 urlpath_or_slash = "/";
758
759 mb.Printf("%s " SQUIDSTRINGPH " HTTP/%d.%d\n",
760 RequestMethodStr(request->method),
761 SQUIDSTRINGPRINT(urlpath_or_slash),
762 request->http_ver.major, request->http_ver.minor);
763 packerToMemInit(&pck, &mb);
764 request->header.packInto(&pck);
765 packerClean(&pck);
766 } else if (request_hdrs) {
767 p = request_hdrs;
768 } else {
769 p = "[no request]";
770 }
771 break;
772
773 case 's':
774 /* for backward compat we make %s show the full URL. Drop this in some future release. */
775 if (building_deny_info_url) {
776 p = request ? urlCanonical(request) : url;
777 debugs(0,0, "WARNING: deny_info now accepts coded tags. Use %u to get the full URL instead of %s");
778 } else
779 p = visible_appname_string;
780 break;
781
782 case 'S':
783 if (building_deny_info_url) {
784 p = visible_appname_string;
785 break;
786 }
787 /* signature may contain %-escapes, recursion */
788 if (page_id != ERR_SQUID_SIGNATURE) {
789 const int saved_id = page_id;
790 page_id = ERR_SQUID_SIGNATURE;
791 MemBuf *sign_mb = BuildContent();
792 mb.Printf("%s", sign_mb->content());
793 sign_mb->clean();
794 delete sign_mb;
795 page_id = saved_id;
796 do_quote = 0;
797 } else {
798 /* wow, somebody put %S into ERR_SIGNATURE, stop recursion */
799 p = "[%S]";
800 }
801 break;
802
803 case 't':
804 mb.Printf("%s", mkhttpdlogtime(&squid_curtime));
805 break;
806
807 case 'T':
808 mb.Printf("%s", mkrfc1123(squid_curtime));
809 break;
810
811 case 'U':
812 /* Using the fake-https version of canonical so error pages see https:// */
813 /* even when the url-path cannot be shown as more than '*' */
814 if (request)
815 p = urlCanonicalFakeHttps(request);
816 else if (url)
817 p = url;
818 else if (!building_deny_info_url)
819 p = "[no URL]";
820 break;
821
822 case 'u':
823 if (request)
824 p = urlCanonical(request);
825 else if (url)
826 p = url;
827 else if (!building_deny_info_url)
828 p = "[no URL]";
829 break;
830
831 case 'w':
832 if (Config.adminEmail)
833 mb.Printf("%s", Config.adminEmail);
834 else if (!building_deny_info_url)
835 p = "[unknown]";
836 break;
837
838 case 'W':
839 if (building_deny_info_url) break;
840 if (Config.adminEmail && Config.onoff.emailErrData)
841 Dump(&mb);
842 no_urlescape = 1;
843 break;
844
845 case 'z':
846 if (building_deny_info_url) break;
847 if (dnsError.size() > 0)
848 p = dnsError.termedBuf();
849 else if (ftp.cwd_msg)
850 p = ftp.cwd_msg;
851 else
852 p = "[unknown]";
853 break;
854
855 case 'Z':
856 if (building_deny_info_url) break;
857 if (err_msg)
858 p = err_msg;
859 else
860 p = "[unknown]";
861 break;
862
863 case '%':
864 p = "%";
865 break;
866
867 default:
868 mb.Printf("%%%c", token);
869 do_quote = 0;
870 break;
871 }
872
873 if (!p)
874 p = mb.buf; /* do not use mb after this assignment! */
875
876 assert(p);
877
878 debugs(4, 3, "errorConvert: %%" << token << " --> '" << p << "'" );
879
880 if (do_quote)
881 p = html_quote(p);
882
883 if (building_deny_info_url && !no_urlescape)
884 p = rfc1738_escape_part(p);
885
886 return p;
887 }
888
889 void
890 ErrorState::DenyInfoLocation(const char *name, HttpRequest *aRequest, MemBuf &result)
891 {
892 char const *m = name;
893 char const *p = m;
894 char const *t;
895
896 while ((p = strchr(m, '%'))) {
897 result.append(m, p - m); /* copy */
898 t = Convert(*++p, true); /* convert */
899 result.Printf("%s", t); /* copy */
900 m = p + 1; /* advance */
901 }
902
903 if (*m)
904 result.Printf("%s", m); /* copy tail */
905
906 assert((size_t)result.contentSize() == strlen(result.content()));
907 }
908
909 HttpReply *
910 ErrorState::BuildHttpReply()
911 {
912 HttpReply *rep = new HttpReply;
913 const char *name = errorPageName(page_id);
914 /* no LMT for error pages; error pages expire immediately */
915
916 if (strchr(name, ':')) {
917 /* Redirection */
918 rep->setHeaders(HTTP_MOVED_TEMPORARILY, NULL, "text/html", 0, 0, -1);
919
920 if (request) {
921 MemBuf redirect_location;
922 redirect_location.init();
923 DenyInfoLocation(name, request, redirect_location);
924 httpHeaderPutStrf(&rep->header, HDR_LOCATION, "%s", redirect_location.content() );
925 }
926
927 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%d %s", httpStatus, "Access Denied");
928 } else {
929 MemBuf *content = BuildContent();
930 rep->setHeaders(httpStatus, NULL, "text/html", content->contentSize(), 0, -1);
931 /*
932 * include some information for downstream caches. Implicit
933 * replaceable content. This isn't quite sufficient. xerrno is not
934 * necessarily meaningful to another system, so we really should
935 * expand it. Additionally, we should identify ourselves. Someone
936 * might want to know. Someone _will_ want to know OTOH, the first
937 * X-CACHE-MISS entry should tell us who.
938 */
939 httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%s %d", name, xerrno);
940
941 #if USE_ERR_LOCALES
942 /*
943 * If error page auto-negotiate is enabled in any way, send the Vary.
944 * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this.
945 * We have even better reasons though:
946 * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching
947 */
948 if (!Config.errorDirectory) {
949 /* We 'negotiated' this ONLY from the Accept-Language. */
950 rep->header.delById(HDR_VARY);
951 rep->header.putStr(HDR_VARY, "Accept-Language");
952 }
953
954 /* add the Content-Language header according to RFC section 14.12 */
955 if (err_language) {
956 rep->header.putStr(HDR_CONTENT_LANGUAGE, err_language);
957 } else
958 #endif /* USE_ERROR_LOCALES */
959 {
960 /* default templates are in English */
961 /* language is known unless error_directory override used */
962 if (!Config.errorDirectory)
963 rep->header.putStr(HDR_CONTENT_LANGUAGE, "en");
964 }
965
966 httpBodySet(&rep->body, content);
967 /* do not memBufClean() or delete the content, it was absorbed by httpBody */
968 }
969
970 return rep;
971 }
972
973 MemBuf *
974 ErrorState::BuildContent()
975 {
976 MemBuf *content = new MemBuf;
977 const char *m = NULL;
978 const char *p;
979 const char *t;
980
981 assert(page_id > ERR_NONE && page_id < error_page_count);
982
983 #if USE_ERR_LOCALES
984 String hdr;
985 char dir[256];
986 int l = 0;
987
988 /** error_directory option in squid.conf overrides translations.
989 * Custom errors are always found either in error_directory or the templates directory.
990 * Otherwise locate the Accept-Language header
991 */
992 if (!Config.errorDirectory && page_id < ERR_MAX && request && request->header.getList(HDR_ACCEPT_LANGUAGE, &hdr) ) {
993
994 size_t pos = 0; // current parsing position in header string
995 char *reset = NULL; // where to reset the p pointer for each new tag file
996 char *dt = NULL;
997
998 /* prep the directory path string to prevent snprintf ... */
999 l = strlen(DEFAULT_SQUID_ERROR_DIR);
1000 memcpy(dir, DEFAULT_SQUID_ERROR_DIR, l);
1001 dir[ l++ ] = '/';
1002 reset = dt = dir + l;
1003
1004 debugs(4, 6, HERE << "Testing Header: '" << hdr << "'");
1005
1006 while ( pos < hdr.size() ) {
1007
1008 /* skip any initial whitespace. */
1009 while (pos < hdr.size() && xisspace(hdr[pos])) pos++;
1010
1011 /*
1012 * Header value format:
1013 * - sequence of whitespace delimited tags
1014 * - each tag may suffix with ';'.* which we can ignore.
1015 * - IFF a tag contains only two characters we can wildcard ANY translations matching: <it> '-'? .*
1016 * with preference given to an exact match.
1017 */
1018 bool invalid_byte = false;
1019 while (pos < hdr.size() && hdr[pos] != ';' && hdr[pos] != ',' && !xisspace(hdr[pos]) && dt < (dir+256) ) {
1020 if (!invalid_byte) {
1021 #if USE_HTTP_VIOLATIONS
1022 // if accepting violations we may as well accept some broken browsers
1023 // which may send us the right code, wrong ISO formatting.
1024 if (hdr[pos] == '_')
1025 *dt = '-';
1026 else
1027 #endif
1028 *dt = xtolower(hdr[pos]);
1029 // valid codes only contain A-Z, hyphen (-) and *
1030 if (*dt != '-' && *dt != '*' && (*dt < 'a' || *dt > 'z') )
1031 invalid_byte = true;
1032 else
1033 dt++; // move to next destination byte.
1034 }
1035 pos++;
1036 }
1037 *dt++ = '\0'; // nul-terminated the filename content string before system use.
1038
1039 debugs(4, 9, HERE << "STATE: dt='" << dt << "', reset='" << reset << "', pos=" << pos << ", buf='" << ((pos < hdr.size()) ? hdr.substr(pos,hdr.size()) : "") << "'");
1040
1041 /* if we found anything we might use, try it. */
1042 if (*reset != '\0' && !invalid_byte) {
1043
1044 /* wildcard uses the configured default language */
1045 if (reset[0] == '*' && reset[1] == '\0') {
1046 debugs(4, 6, HERE << "Found language '" << reset << "'. Using configured default.");
1047 m = error_text[page_id];
1048 if (!Config.errorDirectory)
1049 err_language = Config.errorDefaultLanguage;
1050 break;
1051 }
1052
1053 debugs(4, 6, HERE << "Found language '" << reset << "', testing for available template in: '" << dir << "'");
1054
1055 m = errorTryLoadText( err_type_str[page_id], dir, false);
1056
1057 if (m) {
1058 /* store the language we found for the Content-Language reply header */
1059 err_language = xstrdup(reset);
1060 break;
1061 } else if (Config.errorLogMissingLanguages) {
1062 debugs(4, DBG_IMPORTANT, "WARNING: Error Pages Missing Language: " << reset);
1063 }
1064
1065 #if HAVE_GLOB
1066 if ( (dt - reset) == 2) {
1067 /* TODO glob the error directory for sub-dirs matching: <tag> '-*' */
1068 /* use first result. */
1069 debugs(4,2, HERE << "wildcard fallback errors not coded yet.");
1070 }
1071 #endif
1072 }
1073
1074 dt = reset; // reset for next tag testing. we replace the failed name instead of cloning.
1075
1076 // IFF we terminated the tag on whitespace or ';' we need to skip to the next ',' or end of header.
1077 while (pos < hdr.size() && hdr[pos] != ',') pos++;
1078 if (hdr[pos] == ',') pos++;
1079 }
1080 }
1081 #endif /* USE_ERR_LOCALES */
1082
1083 /** \par
1084 * If client-specific error templates are not enabled or available.
1085 * fall back to the old style squid.conf settings.
1086 */
1087 if (!m) {
1088 m = error_text[page_id];
1089 #if USE_ERR_LOCALES
1090 if (!Config.errorDirectory)
1091 err_language = Config.errorDefaultLanguage;
1092 #endif
1093 debugs(4, 2, HERE << "No existing error page language negotiated for " << errorPageName(page_id) << ". Using default error file.");
1094 }
1095
1096 assert(m);
1097 content->init();
1098
1099 while ((p = strchr(m, '%'))) {
1100 content->append(m, p - m); /* copy */
1101 t = Convert(*++p, false); /* convert */
1102 content->Printf("%s", t); /* copy */
1103 m = p + 1; /* advance */
1104 }
1105
1106 if (*m)
1107 content->Printf("%s", m); /* copy tail */
1108
1109 assert((size_t)content->contentSize() == strlen(content->content()));
1110
1111 return content;
1112 }