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