1 const char cgi_rcs[] = "$Id: cgi.c,v 1.44 2002/03/05 22:43:45 david__schmidt Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/cgi.c,v $
6 * Purpose : Declares functions to intercept request, generate
7 * html or gif answers, and to compose HTTP resonses.
8 * This only contains the framework functions, the
9 * actual handler functions are declared elsewhere.
11 * Functions declared include:
14 * Copyright : Written by and Copyright (C) 2001 the SourceForge
15 * IJBSWA team. http://ijbswa.sourceforge.net
17 * Based on the Internet Junkbuster originally written
18 * by and Copyright (C) 1997 Anonymous Coders and
19 * Junkbusters Corporation. http://www.junkbusters.com
21 * This program is free software; you can redistribute it
22 * and/or modify it under the terms of the GNU General
23 * Public License as published by the Free Software
24 * Foundation; either version 2 of the License, or (at
25 * your option) any later version.
27 * This program is distributed in the hope that it will
28 * be useful, but WITHOUT ANY WARRANTY; without even the
29 * implied warranty of MERCHANTABILITY or FITNESS FOR A
30 * PARTICULAR PURPOSE. See the GNU General Public
31 * License for more details.
33 * The GNU General Public License should be included with
34 * this file. If not, you can view it at
35 * http://www.gnu.org/copyleft/gpl.html
36 * or write to the Free Software Foundation, Inc., 59
37 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
41 * Revision 1.44 2002/03/05 22:43:45 david__schmidt
42 * - Better error reporting on OS/2
43 * - Fix double-slash comment (oops)
45 * Revision 1.43 2002/03/05 21:33:45 david__schmidt
46 * - Re-enable OS/2 building after new parms were added
47 * - Fix false out of memory report when resolving CGI templates when no IP
48 * address is available of failed attempt (a la no such domain)
50 * Revision 1.42 2002/01/21 00:33:20 jongfoster
51 * Replacing strsav() with the safer string_append() or string_join().
52 * Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
53 * Adding missing html_encode() to error message generators.
54 * Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
56 * Revision 1.41 2002/01/17 20:56:22 jongfoster
57 * Replacing hard references to the URL of the config interface
58 * with #defines from project.h
60 * Revision 1.40 2002/01/09 14:26:46 oes
61 * Added support for thread-safe gmtime_r call.
63 * Revision 1.39 2001/11/16 00:48:13 jongfoster
64 * Fixing a compiler warning
66 * Revision 1.38 2001/11/13 00:31:21 jongfoster
67 * - Adding new CGIs for use by non-JavaScript browsers:
68 * edit-actions-url-form
69 * edit-actions-add-url-form
70 * edit-actions-remove-url-form
71 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
74 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
75 * Show enablement/disablement status in almost all templates.
76 * There is a little trickiness here: apparent recursive resolution of
77 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
78 * the actual enablement status. So a similar construct,
79 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
82 * Revision 1.36 2001/10/26 17:33:27 oes
85 * Revision 1.35 2001/10/23 21:48:19 jongfoster
86 * Cleaning up error handling in CGI functions - they now send back
87 * a HTML error page and should never cause a FATAL error. (Fixes one
88 * potential source of "denial of service" attacks).
90 * CGI actions file editor that works and is actually useful.
92 * Ability to toggle JunkBuster remotely using a CGI call.
94 * You can turn off both the above features in the main configuration
95 * file, e.g. if you are running a multi-user proxy.
97 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
98 * Only show "Local support" on templates conditionally:
99 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
100 * - if not, no Local support section appears
102 * Revision 1.33 2001/10/14 22:28:41 jongfoster
103 * Fixing stupid typo.
105 * Revision 1.32 2001/10/14 22:20:18 jongfoster
106 * - Changes to CGI dispatching method to match CGI names exactly,
107 * rather than doing a prefix match.
108 * - No longer need to count the length of the CGI handler names by hand.
109 * - Adding new handler for 404 error when disptching a CGI, if none of
110 * the handlers match.
111 * - Adding new handlers for CGI actionsfile editor.
113 * Revision 1.31 2001/10/10 10:56:39 oes
114 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
116 * Revision 1.30 2001/10/02 15:30:57 oes
117 * Introduced show-request cgi
119 * Revision 1.29 2001/09/20 15:47:44 steudten
121 * Fix BUG: Modify int size to size_t size in fill_template()
122 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
124 * Revision 1.28 2001/09/19 18:00:37 oes
125 * - Deletef time() FIXME (Can't fail under Linux either, if
126 * the argument is guaranteed to be in out address space,
129 * - Pointer notation cosmetics
130 * - Fixed a minor bug in template_fill(): Failiure of
131 * pcrs_execute() now secure.
133 * Revision 1.27 2001/09/16 17:08:54 jongfoster
134 * Moving simple CGI functions from cgi.c to new file cgisimple.c
136 * Revision 1.26 2001/09/16 15:47:37 jongfoster
137 * First version of CGI-based edit interface. This is very much a
138 * work-in-progress, and you can't actually use it to edit anything
139 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
140 * to have any effect.
142 * Revision 1.25 2001/09/16 15:02:35 jongfoster
143 * Adding i.j.b/robots.txt.
144 * Inlining add_stats() since it's only ever called from one place.
146 * Revision 1.24 2001/09/16 11:38:01 jongfoster
147 * Splitting fill_template() into 2 functions:
148 * template_load() loads the file
149 * template_fill() performs the PCRS regexps.
150 * This is because the CGI edit interface has a "table row"
151 * template which is used many times in the page - this
152 * change means it's only loaded from disk once.
154 * Revision 1.23 2001/09/16 11:16:05 jongfoster
155 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
157 * Revision 1.22 2001/09/16 11:00:10 jongfoster
158 * New function alloc_http_response, for symmetry with free_http_response
160 * Revision 1.21 2001/09/13 23:53:03 jongfoster
161 * Support for both static and dynamically generated CGI pages.
162 * Correctly setting Last-Modified: and Expires: HTTP headers.
164 * Revision 1.20 2001/09/13 23:40:36 jongfoster
165 * (Cosmetic only) Indentation correction
167 * Revision 1.19 2001/09/13 23:31:25 jongfoster
168 * Moving image data to cgi.c rather than cgi.h.
170 * Revision 1.18 2001/08/05 16:06:20 jongfoster
171 * Modifiying "struct map" so that there are now separate header and
172 * "map_entry" structures. This means that functions which modify a
173 * map no longer need to return a pointer to the modified map.
174 * Also, it no longer reverses the order of the entries (which may be
175 * important with some advanced template substitutions).
177 * Revision 1.17 2001/08/05 15:57:38 oes
178 * Adapted finish_http_response to new list_to_text
180 * Revision 1.16 2001/08/01 21:33:18 jongfoster
181 * Changes to fill_template() that reduce memory usage without having
182 * an impact on performance. I also renamed some variables so as not
183 * to clash with the C++ keywords "new" and "template".
185 * Revision 1.15 2001/08/01 21:19:22 jongfoster
186 * Moving file version information to a separate CGI page.
188 * Revision 1.14 2001/08/01 00:19:03 jongfoster
189 * New function: map_conditional() for an if-then-else syntax.
190 * Changing to use new version of show_defines()
192 * Revision 1.13 2001/07/30 22:08:36 jongfoster
193 * Tidying up #defines:
194 * - All feature #defines are now of the form FEATURE_xxx
195 * - Permanently turned off WIN_GUI_EDIT
196 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
198 * Revision 1.12 2001/07/29 18:47:05 jongfoster
199 * Adding missing #include "loadcfg.h"
201 * Revision 1.11 2001/07/18 17:24:37 oes
202 * Changed to conform to new pcrs interface
204 * Revision 1.10 2001/07/13 13:53:13 oes
205 * Removed all #ifdef PCRS and related code
207 * Revision 1.9 2001/06/29 21:45:41 oes
208 * Indentation, CRLF->LF, Tab-> Space
210 * Revision 1.8 2001/06/29 13:21:46 oes
211 * - Cosmetics: renamed and reordered functions, variables,
212 * texts, improved comments etc
214 * - Removed ij_untrusted_url() The relevant
215 * info is now part of the "untrusted" page,
216 * which is generated by filters.c:trust_url()
218 * - Generators of content now call finish_http_response()
219 * themselves, making jcc.c:chat() a little less
222 * - Removed obsolete "Pragma: no-cache" from our headers
224 * - http_responses now know their head length
226 * - fill_template now uses the new interface to pcrs, so that
227 * - long jobs (like whole files) no longer have to be assembled
228 * in a fixed size buffer
229 * - the new T (trivial) option is used, and the replacement may
230 * contain Perl syntax backrefs without confusing pcrs
232 * - Introduced default_exports() which generates a set of exports
233 * common to all CGIs and other content generators
235 * - Introduced convenience function map_block_killer()
237 * - Introduced convenience function make_menu()
239 * - Introduced CGI-like function error_response() which generates
240 * the "No such domain" and "Connect failed" messages using the
243 * - cgi_show_url_info:
244 * - adapted to new CGI features
245 * - form and answers now generated from same template
246 * - http:// prefix in URL now OK
249 * - adapted to new CGI features
250 * - no longer uses csp->init_proxy_args
253 * - moved menu generation to make_menu()
255 * - add_stats now writes single export map entries instead
258 * - Moved redirect_url() to filters.c
260 * - Fixed mem leak in free_http_response(), map_block_killer(),
262 * - Removed logentry from cancelled commit
264 * Revision 1.7 2001/06/09 10:51:58 jongfoster
265 * Changing "show URL info" handler to new style.
266 * Changing BUFSIZ ==> BUFFER_SIZE
268 * Revision 1.6 2001/06/07 23:05:19 jongfoster
269 * Removing code related to old forward and ACL files.
271 * Revision 1.5 2001/06/05 19:59:16 jongfoster
272 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
274 * Revision 1.4 2001/06/04 10:41:52 swa
275 * show version string of cgi.h and cgi.c
277 * Revision 1.3 2001/06/03 19:12:16 oes
278 * introduced new cgi handling
280 * No revisions before 1.3
282 **********************************************************************/
288 #include <sys/types.h>
295 #define snprintf _snprintf
296 #endif /* def _WIN32 */
304 #include "miscutil.h"
305 #include "cgisimple.h"
306 #ifdef FEATURE_CGI_EDIT_ACTIONS
308 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
310 /* loadcfg.h is for g_bToggleIJB only */
312 const char cgi_h_rcs[] = CGI_H_VERSION;
314 static const struct cgi_dispatcher cgi_dispatchers[] = {
317 "Junkbuster main page" },
320 "Show information about the current configuration" },
323 "Show the source code version numbers" },
326 "Show the client's request headers." },
329 "Show which actions apply to a URL and why" },
332 "Toggle JunkBuster on or off" },
333 #ifdef FEATURE_CGI_EDIT_ACTIONS
336 "Edit the actions list" },
339 { "eaa", /* Shortcut for edit-actions-add-url-form */
340 cgi_edit_actions_add_url_form,
342 { "eau", /* Shortcut for edit-actions-url-form */
343 cgi_edit_actions_url_form,
345 { "ear", /* Shortcut for edit-actions-remove-url-form */
346 cgi_edit_actions_remove_url_form,
348 { "eas", /* Shortcut for edit-actions-for-url */
349 cgi_edit_actions_for_url,
351 { "easa", /* Shortcut for edit-actions-section-add */
352 cgi_edit_actions_section_add,
354 { "easr", /* Shortcut for edit-actions-section-remove */
355 cgi_edit_actions_section_remove,
357 { "eass", /* Shortcut for edit-actions-section-swap */
358 cgi_edit_actions_section_swap,
360 { "edit-actions-for-url",
361 cgi_edit_actions_for_url,
362 NULL /* Edit the actions for (a) specified URL(s) */ },
363 { "edit-actions-list",
364 cgi_edit_actions_list,
365 NULL /* Edit the actions list */ },
366 { "edit-actions-submit",
367 cgi_edit_actions_submit,
368 NULL /* Change the actions for (a) specified URL(s) */ },
369 { "edit-actions-url",
370 cgi_edit_actions_url,
371 NULL /* Change a URL pattern in the actionsfile */ },
372 { "edit-actions-url-form",
373 cgi_edit_actions_url_form,
374 NULL /* Form to change a URL pattern in the actionsfile */ },
375 { "edit-actions-add-url",
376 cgi_edit_actions_add_url,
377 NULL /* Add a URL pattern to the actionsfile */ },
378 { "edit-actions-add-url-form",
379 cgi_edit_actions_add_url_form,
380 NULL /* Form to add a URL pattern to the actionsfile */ },
381 { "edit-actions-remove-url",
382 cgi_edit_actions_remove_url,
383 NULL /* Remove a URL pattern from the actionsfile */ },
384 { "edit-actions-remove-url-form",
385 cgi_edit_actions_remove_url_form,
386 NULL /* Form to remove a URL pattern from the actionsfile */ },
387 { "edit-actions-section-add",
388 cgi_edit_actions_section_add,
389 NULL /* Remove a section from the actionsfile */ },
390 { "edit-actions-section-remove",
391 cgi_edit_actions_section_remove,
392 NULL /* Remove a section from the actionsfile */ },
393 { "edit-actions-section-swap",
394 cgi_edit_actions_section_swap,
395 NULL /* Swap two sections in the actionsfile */ },
396 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
399 NULL /* Sends a robots.txt file to tell robots to go away. */ },
402 NULL /* Send the transparent or \"Junkbuster\" gif */ },
405 NULL /* Send a transparent gif (short name) */ },
406 { NULL, /* NULL Indicates end of list and default page */
408 NULL /* Unknown CGI page */ }
415 * Hint: You can encode your own GIFs like this:
416 * perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o,", unpack("C", $c)); }'
419 const char image_junkbuster_gif_data[] =
420 "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
421 "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
422 "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
423 "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
424 "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
425 "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
426 "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
429 const int image_junkbuster_gif_length = sizeof(image_junkbuster_gif_data) - 1;
432 const char image_blank_gif_data[] =
433 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
434 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
435 "\000\001\000\000\002\002D\001\000;";
437 const int image_blank_gif_length = sizeof(image_blank_gif_data) - 1;
440 static struct http_response cgi_error_memory_response[1];
443 static struct http_response *dispatch_known_cgi(struct client_state * csp,
445 static struct map *parse_cgi_parameters(char *argstring);
448 /*********************************************************************
450 * Function : dispatch_cgi
452 * Description : Checks if a request URL has either the magical
453 * hostname CGI_SITE_1_HOST (usully http://i.j.b/) or
454 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
455 * http://ijbswa.sourceforge.net/config). If so, it passes
456 * the (rest of the) path onto dispatch_known_cgi, which
457 * calls the relevant CGI handler function.
460 * 1 : csp = Current client state (buffers, headers, etc...)
462 * Returns : http_response if match, NULL if nonmatch or handler fail
464 *********************************************************************/
465 struct http_response *dispatch_cgi(struct client_state *csp)
467 const char *host = csp->http->host;
468 const char *path = csp->http->path;
471 * Should we intercept ?
474 /* Note: "example.com" and "example.com." are equivalent hostnames. */
476 /* Either the host matches CGI_SITE_1_HOST ..*/
477 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
478 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
479 && (path[0] == '/') )
481 /* ..then the path will all be for us. Remove leading '/' */
484 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
485 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
486 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
487 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
489 /* take everything following CGI_SITE_2_PATH */
490 path += strlen(CGI_SITE_2_PATH);
493 /* skip the forward slash after CGI_SITE_2_PATH */
496 else if (*path != '\0')
499 * wierdness: URL is /configXXX, where XXX is some string
500 * Do *NOT* intercept.
512 * This is a CGI call.
515 return dispatch_known_cgi(csp, path);
519 /*********************************************************************
521 * Function : dispatch_known_cgi
523 * Description : Processes a CGI once dispatch_cgi has determined that
524 * it matches one of the magic prefixes. Parses the path
525 * as a cgi name plus query string, prepares a map that
526 * maps CGI parameter names to their values, initializes
527 * the http_response struct, and calls the relevant CGI
531 * 1 : csp = Current client state (buffers, headers, etc...)
532 * 2 : path = Path of CGI, with the CGI prefix removed.
533 * Should not have a leading "/".
535 * Returns : http_response, or NULL on handler failure or out of
538 *********************************************************************/
539 static struct http_response *dispatch_known_cgi(struct client_state * csp,
542 const struct cgi_dispatcher *d;
543 struct map *param_list;
544 struct http_response *rsp;
545 char *query_args_start;
549 if (NULL == (path_copy = strdup(path)))
551 return cgi_error_memory();
554 query_args_start = path_copy;
555 while (*query_args_start && *query_args_start != '?')
559 if (*query_args_start == '?')
561 *query_args_start++ = '\0';
564 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
567 return cgi_error_memory();
573 * path_copy = CGI call name
574 * param_list = CGI params, as map
577 /* Get mem for response or fail*/
578 if (NULL == (rsp = alloc_http_response()))
581 free_map(param_list);
582 return cgi_error_memory();
585 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
586 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
587 csp->ip_addr_str, csp->http->cmd);
589 /* Find and start the right CGI function*/
590 for (d = cgi_dispatchers; FOREVER; d++)
592 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
594 err = (d->handler)(csp, rsp, param_list);
596 free_map(param_list);
597 if (err == JB_ERR_CGI_PARAMS)
599 err = cgi_error_bad_param(csp, rsp);
604 return finish_http_response(rsp);
608 /* Error in handler, probably out-of-memory */
609 free_http_response(rsp);
610 return cgi_error_memory();
617 /*********************************************************************
619 * Function : parse_cgi_parameters
621 * Description : Parse a URL-encoded argument string into name/value
622 * pairs and store them in a struct map list.
625 * 1 : string = string to be parsed. Will be trashed.
627 * Returns : pointer to param list, or NULL if out of memory.
629 *********************************************************************/
630 static struct map *parse_cgi_parameters(char *argstring)
633 char *vector[BUFFER_SIZE];
635 struct map *cgi_params;
637 if (NULL == (cgi_params = new_map()))
642 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
644 for (i = 0; i < pairs; i++)
646 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
649 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
651 free_map(cgi_params);
662 /*********************************************************************
664 * Function : error_response
666 * Description : returns an http_response that explains the reason
667 * why a request failed.
670 * 1 : csp = Current client state (buffers, headers, etc...)
671 * 2 : templatename = Which template should be used for the answer
672 * 3 : sys_err = system error number
674 * Returns : A http_response. If we run out of memory, this
675 * will be cgi_error_memory().
677 *********************************************************************/
678 struct http_response *error_response(struct client_state *csp,
679 const char *templatename,
683 struct http_response *rsp;
684 struct map * exports = default_exports(csp, NULL);
687 return cgi_error_memory();
690 if (NULL == (rsp = alloc_http_response()))
693 return cgi_error_memory();
696 err = map(exports, "host", 1, html_encode(csp->http->host), 0);
697 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
698 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
699 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
702 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
705 /* Some failures, like "404 no such domain", don't have an IP address. */
706 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
714 free_http_response(rsp);
715 return cgi_error_memory();
718 if (!strcmp(templatename, "no-such-domain"))
720 rsp->status = strdup("404 No such domain");
721 if (rsp->status == NULL)
724 free_http_response(rsp);
725 return cgi_error_memory();
728 else if (!strcmp(templatename, "connect-failed"))
730 rsp->status = strdup("503 Connect failed");
731 if (rsp->status == NULL)
734 free_http_response(rsp);
735 return cgi_error_memory();
739 err = template_fill_for_cgi(csp, templatename, exports, rsp);
742 free_http_response(rsp);
743 return cgi_error_memory();
746 return finish_http_response(rsp);
750 /*********************************************************************
752 * Function : cgi_init_error_messages
754 * Description : Call at the start of the program to initialize
755 * the error message used by cgi_error_memory().
761 *********************************************************************/
762 void cgi_init_error_messages(void)
764 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
765 cgi_error_memory_response->head =
766 "HTTP/1.0 500 Internal JunkBuster Proxy Error\r\n"
767 "Content-Type: text/html\r\n"
769 cgi_error_memory_response->body =
771 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
773 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
774 "<p>JunkBuster <b>ran out of memory</b> while processing your request.</p>\r\n"
775 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
779 cgi_error_memory_response->head_length =
780 strlen(cgi_error_memory_response->head);
781 cgi_error_memory_response->content_length =
782 strlen(cgi_error_memory_response->body);
786 /*********************************************************************
788 * Function : cgi_error_memory
790 * Description : Called if a CGI function runs out of memory.
791 * Returns a statically-allocated error response.
794 * 1 : csp = Current client state (buffers, headers, etc...)
795 * 2 : rsp = http_response data structure for output
796 * 3 : template_name = Name of template that could not
799 * Returns : JB_ERR_OK on success
800 * JB_ERR_MEMORY on out-of-memory error.
802 *********************************************************************/
803 struct http_response *cgi_error_memory(void)
805 /* assert that it's been initialized. */
806 assert(cgi_error_memory_response->head);
808 return cgi_error_memory_response;
812 /*********************************************************************
814 * Function : cgi_error_no_template
816 * Description : Almost-CGI function that is called if a templae
817 * cannot be loaded. Note this is not a true CGI,
818 * it takes a template name rather than a map of
822 * 1 : csp = Current client state (buffers, headers, etc...)
823 * 2 : rsp = http_response data structure for output
824 * 3 : template_name = Name of template that could not
827 * Returns : JB_ERR_OK on success
828 * JB_ERR_MEMORY on out-of-memory error.
830 *********************************************************************/
831 jb_err cgi_error_no_template(struct client_state *csp,
832 struct http_response *rsp,
833 const char *template_name)
835 static const char status[] =
836 "500 Internal JunkBuster Proxy Error";
837 static const char body_prefix[] =
839 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
841 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
842 "<p>JunkBuster encountered an error while processing your request:</p>\r\n"
843 "<p><b>Could not load template file <code>";
844 static const char body_suffix[] =
845 "</code></b></p>\r\n"
846 "<p>Please contact your proxy administrator.</p>\r\n"
847 "<p>If you are the proxy administrator, please put the required file "
848 "in the <code><i>(confdir)</i>/templates</code> directory. The "
849 "location of the <code><i>(confdir)</i></code> directory "
850 "is specified in the main JunkBuster <code>config</code> "
851 "file. (It's typically the JunkBuster install directory"
853 ", or <code>/etc/junkbuster/</code>"
854 #endif /* ndef _WIN32 */
861 assert(template_name);
863 /* Reset rsp, if needed */
867 rsp->content_length = 0;
868 rsp->head_length = 0;
871 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
872 if (rsp->body == NULL)
874 return JB_ERR_MEMORY;
876 strcpy(rsp->body, body_prefix);
877 strcat(rsp->body, template_name);
878 strcat(rsp->body, body_suffix);
880 rsp->status = strdup(status);
881 if (rsp->body == NULL)
883 return JB_ERR_MEMORY;
890 /*********************************************************************
892 * Function : cgi_error_bad_param
894 * Description : CGI function that is called if the parameters
895 * (query string) for a CGI were wrong.
898 * 1 : csp = Current client state (buffers, headers, etc...)
899 * 2 : rsp = http_response data structure for output
901 * CGI Parameters : none
903 * Returns : JB_ERR_OK on success
904 * JB_ERR_MEMORY on out-of-memory error.
906 *********************************************************************/
907 jb_err cgi_error_bad_param(struct client_state *csp,
908 struct http_response *rsp)
915 if (NULL == (exports = default_exports(csp, NULL)))
917 return JB_ERR_MEMORY;
920 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
924 /*********************************************************************
926 * Function : get_http_time
928 * Description : Get the time in a format suitable for use in a
929 * HTTP header - e.g.:
930 * "Sun, 06 Nov 1994 08:49:37 GMT"
933 * 1 : time_offset = Time returned will be current time
934 * plus this number of seconds.
935 * 2 : buf = Destination for result. Must be long enough
936 * to hold 29 characters plus a trailing zero.
940 *********************************************************************/
941 void get_http_time(int time_offset, char *buf)
943 static const char day_names[7][4] =
944 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
945 static const char month_names[12][4] =
946 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
947 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
954 time(¤t_time); /* get current time */
956 current_time += time_offset;
958 /* get and save the gmt */
962 t = gmtime_r(¤t_time, &dummy);
964 t = gmtime(¤t_time);
968 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
970 "%s, %02d %s %4d %02d:%02d:%02d GMT",
971 day_names[t->tm_wday],
973 month_names[t->tm_mon],
983 /*********************************************************************
985 * Function : finish_http_response
987 * Description : Fill in the missing headers in an http response,
988 * and flatten the headers to an http head.
991 * 1 : rsp = pointer to http_response to be processed
993 * Returns : A http_response, usually the rsp parameter.
994 * On error, free()s rsp and returns cgi_error_memory()
996 *********************************************************************/
997 struct http_response *finish_http_response(struct http_response *rsp)
999 char buf[BUFFER_SIZE];
1002 /* Special case - do NOT change this statically allocated response,
1003 * which is ready for output anyway.
1005 if (rsp == cgi_error_memory_response)
1011 * Fill in the HTTP Status
1013 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1014 err = enlist_first(rsp->headers, buf);
1017 * Set the Content-Length
1019 if (rsp->content_length == 0)
1021 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1025 sprintf(buf, "Content-Length: %d", rsp->content_length);
1026 err = enlist(rsp->headers, buf);
1030 * Fill in the default headers:
1032 * Content-Type: default to text/html if not already specified.
1033 * Date: set to current date/time.
1034 * Last-Modified: set to date/time the page was last changed.
1035 * Expires: set to date/time page next needs reloading.
1036 * Cache-Control: set to "no-cache" if applicable.
1038 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1040 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1045 * Set Expires to about 10 min into the future so it'll get reloaded
1046 * occasionally, e.g. if IJB gets upgraded.
1051 get_http_time(0, buf);
1052 err = enlist_unique_header(rsp->headers, "Date", buf);
1055 /* Some date in the past. */
1056 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1060 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1061 err = enlist_unique_header(rsp->headers, "Expires", buf);
1067 * Compliant browsers should not cache this due to the "Cache-Control"
1068 * setting. However, to be certain, we also set both "Last-Modified"
1069 * and "Expires" to the current time.
1071 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1073 get_http_time(0, buf);
1074 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1075 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1076 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1083 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1085 free_http_response(rsp);
1086 return cgi_error_memory();
1088 rsp->head_length = strlen(rsp->head);
1095 /*********************************************************************
1097 * Function : alloc_http_response
1099 * Description : Allocates a new http_response structure.
1103 * Returns : pointer to a new http_response, or NULL.
1105 *********************************************************************/
1106 struct http_response *alloc_http_response(void)
1108 return (struct http_response *) zalloc(sizeof(struct http_response));
1113 /*********************************************************************
1115 * Function : free_http_response
1117 * Description : Free the memory occupied by an http_response
1118 * and its depandant structures.
1121 * 1 : rsp = pointer to http_response to be freed
1125 *********************************************************************/
1126 void free_http_response(struct http_response *rsp)
1129 * Must special case cgi_error_memory_response, which is never freed.
1131 if (rsp && (rsp != cgi_error_memory_response))
1136 destroy_list(rsp->headers);
1143 /*********************************************************************
1145 * Function : template_load
1147 * Description : CGI support function that loads a given HTML
1148 * template from the confdir, ignoring comment
1152 * 1 : csp = Current client state (buffers, headers, etc...)
1153 * 2 : template_ptr = Destination for pointer to loaded
1155 * 3 : template = name of the HTML template to be used
1157 * Returns : JB_ERR_OK on success
1158 * JB_ERR_MEMORY on out-of-memory error.
1159 * JB_ERR_FILE if the template file cannot be read
1161 *********************************************************************/
1162 jb_err template_load(struct client_state *csp, char ** template_ptr,
1163 const char *templatename)
1165 char *templates_dir_path;
1169 char buf[BUFFER_SIZE];
1172 assert(template_ptr);
1173 assert(templatename);
1175 *template_ptr = NULL;
1178 * Open template file or fail
1181 templates_dir_path = make_path(csp->config->confdir, "templates");
1182 if (templates_dir_path == NULL)
1184 return JB_ERR_MEMORY;
1187 full_path = make_path(templates_dir_path, templatename);
1188 free(templates_dir_path);
1189 if (full_path == NULL)
1191 return JB_ERR_MEMORY;
1194 file_buffer = strdup("");
1195 if (file_buffer == NULL)
1198 return JB_ERR_MEMORY;
1201 if (NULL == (fp = fopen(full_path, "r")))
1203 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1211 * Read the file, ignoring comments.
1213 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1214 * This is unlikely in practise.
1216 while (fgets(buf, BUFFER_SIZE, fp))
1218 /* skip lines starting with '#' */
1224 if (string_append(&file_buffer, buf))
1227 return JB_ERR_MEMORY;
1232 *template_ptr = file_buffer;
1238 /*********************************************************************
1240 * Function : template_fill
1242 * Description : CGI support function that fills in a pre-loaded
1243 * HTML template by replacing @name@ with value using
1244 * pcrs, for each item in the output map.
1246 * Note that a leading '$' charachter in the export map's
1247 * values will be stripped and toggle on backreference
1251 * 1 : template_ptr = IN: Template to be filled out.
1253 * OUT: Filled out template.
1254 * Caller must free().
1255 * 2 : exports = map with fill in symbol -> name pairs
1257 * Returns : JB_ERR_OK on success
1258 * JB_ERR_MEMORY on out-of-memory error
1260 *********************************************************************/
1261 jb_err template_fill(char **template_ptr, const struct map *exports)
1263 struct map_entry *m;
1265 char buf[BUFFER_SIZE];
1266 char *tmp_out_buffer;
1272 assert(template_ptr);
1273 assert(*template_ptr);
1276 file_buffer = *template_ptr;
1277 size = strlen(file_buffer) + 1;
1280 * Assemble pcrs joblist from exports map
1282 for (m = exports->first; m != NULL; m = m->next)
1284 if (*m->name == '$')
1287 * First character of name is '$', so remove this flag
1288 * character and allow backreferences ($1 etc) in the
1289 * "replace with" text.
1291 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1297 * Treat the "replace with" text as a literal string -
1298 * no quoting needed, no backreferences allowed.
1299 * ("Trivial" ['T'] flag).
1303 /* Enclose name in @@ */
1304 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1308 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1310 /* Make and run job. */
1311 job = pcrs_compile(buf, m->value, flags, &error);
1314 if (error == PCRS_ERR_NOMEM)
1317 *template_ptr = NULL;
1318 return JB_ERR_MEMORY;
1322 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1323 /* Hope it wasn't important and silently ignore the invalid job */
1328 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1331 if (NULL == tmp_out_buffer)
1333 *template_ptr = NULL;
1334 return JB_ERR_MEMORY;
1336 file_buffer = tmp_out_buffer;
1343 *template_ptr = file_buffer;
1348 /*********************************************************************
1350 * Function : template_fill_for_cgi
1352 * Description : CGI support function that loads a HTML template
1353 * and fills it in. Handles file-not-found errors
1354 * by sending a HTML error message. For convenience,
1355 * this function also frees the passed "exports" map.
1358 * 1 : csp = Client state
1359 * 2 : templatename = name of the HTML template to be used
1360 * 3 : exports = map with fill in symbol -> name pairs.
1361 * Will be freed by this function.
1363 * Returns : JB_ERR_OK on success
1364 * JB_ERR_MEMORY on out-of-memory error
1366 *********************************************************************/
1367 jb_err template_fill_for_cgi(struct client_state *csp,
1368 const char *templatename,
1369 struct map *exports,
1370 struct http_response *rsp)
1375 assert(templatename);
1379 err = template_load(csp, &rsp->body, templatename);
1380 if (err == JB_ERR_FILE)
1383 return cgi_error_no_template(csp, rsp, templatename);
1388 return err; /* JB_ERR_MEMORY */
1390 err = template_fill(&rsp->body, exports);
1396 /*********************************************************************
1398 * Function : default_exports
1400 * Description : returns a struct map list that contains exports
1401 * which are common to all CGI functions.
1404 * 1 : csp = Current client state (buffers, headers, etc...)
1405 * 2 : caller = name of CGI who calls us and which should
1406 * be excluded from the generated menu. May be
1408 * Returns : NULL if no memory, else a new map. Caller frees.
1410 *********************************************************************/
1411 struct map *default_exports(const struct client_state *csp, const char *caller)
1415 struct map * exports;
1416 int local_help_exists = 0;
1420 exports = new_map();
1421 if (exports == NULL)
1426 err = map(exports, "version", 1, html_encode(VERSION), 0);
1427 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
1428 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
1429 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
1430 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
1431 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
1432 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
1433 if (!err) err = map_conditional(exports, "enabled-display", g_bToggleIJB);
1435 snprintf(buf, 20, "%d", csp->config->hport);
1436 if (!err) err = map(exports, "my-port", 1, buf, 1);
1438 if(!strcmp(CODE_STATUS, "stable"))
1440 if (!err) err = map_block_killer(exports, "unstable");
1443 if (csp->config->admin_address != NULL)
1445 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
1446 local_help_exists = 1;
1450 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
1453 if (csp->config->proxy_info_url != NULL)
1455 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
1456 local_help_exists = 1;
1460 if (!err) err = map_block_killer(exports, "have-proxy-info");
1463 if (local_help_exists == 0)
1465 if (!err) err = map_block_killer(exports, "have-help-info");
1478 /*********************************************************************
1480 * Function : map_block_killer
1482 * Description : Convenience function.
1483 * Adds a "killer" for the conditional HTML-template
1484 * block <name>, i.e. a substitution of the regex
1485 * "if-<name>-start.*if-<name>-end" to the given
1489 * 1 : exports = map to extend
1490 * 2 : name = name of conditional block
1492 * Returns : JB_ERR_OK on success
1493 * JB_ERR_MEMORY on out-of-memory error.
1495 *********************************************************************/
1496 jb_err map_block_killer(struct map *exports, const char *name)
1498 char buf[1000]; /* Will do, since the names are hardwired */
1502 assert(strlen(name) < 490);
1504 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1505 return map(exports, buf, 1, "", 1);
1509 /*********************************************************************
1511 * Function : map_block_keep
1513 * Description : Convenience function. Removes the markers used
1514 * by map-block-killer, to save a few bytes.
1515 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
1518 * 1 : exports = map to extend
1519 * 2 : name = name of conditional block
1521 * Returns : JB_ERR_OK on success
1522 * JB_ERR_MEMORY on out-of-memory error.
1524 *********************************************************************/
1525 jb_err map_block_keep(struct map *exports, const char *name)
1528 char buf[500]; /* Will do, since the names are hardwired */
1532 assert(strlen(name) < 490);
1534 snprintf(buf, 500, "if-%s-start", name);
1535 err = map(exports, buf, 1, "", 1);
1542 snprintf(buf, 500, "if-%s-end", name);
1543 return map(exports, buf, 1, "", 1);
1547 /*********************************************************************
1549 * Function : map_conditional
1551 * Description : Convenience function.
1552 * Adds an "if-then-else" for the conditional HTML-template
1553 * block <name>, i.e. a substitution of the form:
1560 * The control structure and one of the alternatives
1564 * 1 : exports = map to extend
1565 * 2 : name = name of conditional block
1566 * 3 : choose_first = nonzero for first, zero for second.
1568 * Returns : JB_ERR_OK on success
1569 * JB_ERR_MEMORY on out-of-memory error.
1571 *********************************************************************/
1572 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
1574 char buf[1000]; /* Will do, since the names are hardwired */
1579 assert(strlen(name) < 480);
1581 snprintf(buf, 1000, (choose_first
1582 ? "else-not-%s@.*@endif-%s"
1583 : "if-%s-then@.*@else-not-%s"),
1586 err = map(exports, buf, 1, "", 1);
1592 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1593 return map(exports, buf, 1, "", 1);
1597 /*********************************************************************
1599 * Function : make_menu
1601 * Description : Returns an HTML-formatted menu of the available
1602 * unhidden CGIs, excluding the one given in <self>.
1604 * Parameters : self = name of CGI to leave out, can be NULL
1606 * Returns : menu string, or NULL on out-of-memory error.
1608 *********************************************************************/
1609 char *make_menu(const char *self)
1611 const struct cgi_dispatcher *d;
1612 char *result = strdup("");
1616 self = "NO-SUCH-CGI!";
1619 /* List available unhidden CGI's and export as "other-cgis" */
1620 for (d = cgi_dispatchers; d->name; d++)
1622 if (d->description && strcmp(d->name, self))
1624 string_append(&result, "<li><a href=\"" CGI_PREFIX);
1625 string_append(&result, d->name);
1626 string_append(&result, "\">");
1627 string_append(&result, d->description);
1628 string_append(&result, "</a></li>\n");
1636 /*********************************************************************
1638 * Function : dump_map
1640 * Description : HTML-dump a map for debugging
1643 * 1 : the_map = map to dump
1645 * Returns : string with HTML
1647 *********************************************************************/
1648 char *dump_map(const struct map *the_map)
1650 struct map_entry *cur_entry;
1651 char *ret = strdup("");
1653 string_append(&ret, "<table>\n");
1655 for (cur_entry = the_map->first;
1656 (cur_entry != NULL) && (ret != NULL);
1657 cur_entry = cur_entry->next)
1659 string_append(&ret, "<tr><td><b>");
1660 string_join (&ret, html_encode(cur_entry->name));
1661 string_append(&ret, "</b></td><td>");
1662 string_join (&ret, html_encode(cur_entry->value));
1663 string_append(&ret, "</td></tr>\n");
1666 string_append(&ret, "</table>\n");