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