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