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