1 const char cgi_rcs[] = "$Id: cgi.c,v 1.39 2001/11/16 00:48:13 jongfoster 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.39 2001/11/16 00:48:13 jongfoster
42 * Fixing a compiler warning
44 * Revision 1.38 2001/11/13 00:31:21 jongfoster
45 * - Adding new CGIs for use by non-JavaScript browsers:
46 * edit-actions-url-form
47 * edit-actions-add-url-form
48 * edit-actions-remove-url-form
49 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
52 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
53 * Show enablement/disablement status in almost all templates.
54 * There is a little trickiness here: apparent recursive resolution of
55 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
56 * the actual enablement status. So a similar construct,
57 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
60 * Revision 1.36 2001/10/26 17:33:27 oes
63 * Revision 1.35 2001/10/23 21:48:19 jongfoster
64 * Cleaning up error handling in CGI functions - they now send back
65 * a HTML error page and should never cause a FATAL error. (Fixes one
66 * potential source of "denial of service" attacks).
68 * CGI actions file editor that works and is actually useful.
70 * Ability to toggle JunkBuster remotely using a CGI call.
72 * You can turn off both the above features in the main configuration
73 * file, e.g. if you are running a multi-user proxy.
75 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
76 * Only show "Local support" on templates conditionally:
77 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
78 * - if not, no Local support section appears
80 * Revision 1.33 2001/10/14 22:28:41 jongfoster
83 * Revision 1.32 2001/10/14 22:20:18 jongfoster
84 * - Changes to CGI dispatching method to match CGI names exactly,
85 * rather than doing a prefix match.
86 * - No longer need to count the length of the CGI handler names by hand.
87 * - Adding new handler for 404 error when disptching a CGI, if none of
89 * - Adding new handlers for CGI actionsfile editor.
91 * Revision 1.31 2001/10/10 10:56:39 oes
92 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
94 * Revision 1.30 2001/10/02 15:30:57 oes
95 * Introduced show-request cgi
97 * Revision 1.29 2001/09/20 15:47:44 steudten
99 * Fix BUG: Modify int size to size_t size in fill_template()
100 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
102 * Revision 1.28 2001/09/19 18:00:37 oes
103 * - Deletef time() FIXME (Can't fail under Linux either, if
104 * the argument is guaranteed to be in out address space,
107 * - Pointer notation cosmetics
108 * - Fixed a minor bug in template_fill(): Failiure of
109 * pcrs_execute() now secure.
111 * Revision 1.27 2001/09/16 17:08:54 jongfoster
112 * Moving simple CGI functions from cgi.c to new file cgisimple.c
114 * Revision 1.26 2001/09/16 15:47:37 jongfoster
115 * First version of CGI-based edit interface. This is very much a
116 * work-in-progress, and you can't actually use it to edit anything
117 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
118 * to have any effect.
120 * Revision 1.25 2001/09/16 15:02:35 jongfoster
121 * Adding i.j.b/robots.txt.
122 * Inlining add_stats() since it's only ever called from one place.
124 * Revision 1.24 2001/09/16 11:38:01 jongfoster
125 * Splitting fill_template() into 2 functions:
126 * template_load() loads the file
127 * template_fill() performs the PCRS regexps.
128 * This is because the CGI edit interface has a "table row"
129 * template which is used many times in the page - this
130 * change means it's only loaded from disk once.
132 * Revision 1.23 2001/09/16 11:16:05 jongfoster
133 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
135 * Revision 1.22 2001/09/16 11:00:10 jongfoster
136 * New function alloc_http_response, for symmetry with free_http_response
138 * Revision 1.21 2001/09/13 23:53:03 jongfoster
139 * Support for both static and dynamically generated CGI pages.
140 * Correctly setting Last-Modified: and Expires: HTTP headers.
142 * Revision 1.20 2001/09/13 23:40:36 jongfoster
143 * (Cosmetic only) Indentation correction
145 * Revision 1.19 2001/09/13 23:31:25 jongfoster
146 * Moving image data to cgi.c rather than cgi.h.
148 * Revision 1.18 2001/08/05 16:06:20 jongfoster
149 * Modifiying "struct map" so that there are now separate header and
150 * "map_entry" structures. This means that functions which modify a
151 * map no longer need to return a pointer to the modified map.
152 * Also, it no longer reverses the order of the entries (which may be
153 * important with some advanced template substitutions).
155 * Revision 1.17 2001/08/05 15:57:38 oes
156 * Adapted finish_http_response to new list_to_text
158 * Revision 1.16 2001/08/01 21:33:18 jongfoster
159 * Changes to fill_template() that reduce memory usage without having
160 * an impact on performance. I also renamed some variables so as not
161 * to clash with the C++ keywords "new" and "template".
163 * Revision 1.15 2001/08/01 21:19:22 jongfoster
164 * Moving file version information to a separate CGI page.
166 * Revision 1.14 2001/08/01 00:19:03 jongfoster
167 * New function: map_conditional() for an if-then-else syntax.
168 * Changing to use new version of show_defines()
170 * Revision 1.13 2001/07/30 22:08:36 jongfoster
171 * Tidying up #defines:
172 * - All feature #defines are now of the form FEATURE_xxx
173 * - Permanently turned off WIN_GUI_EDIT
174 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
176 * Revision 1.12 2001/07/29 18:47:05 jongfoster
177 * Adding missing #include "loadcfg.h"
179 * Revision 1.11 2001/07/18 17:24:37 oes
180 * Changed to conform to new pcrs interface
182 * Revision 1.10 2001/07/13 13:53:13 oes
183 * Removed all #ifdef PCRS and related code
185 * Revision 1.9 2001/06/29 21:45:41 oes
186 * Indentation, CRLF->LF, Tab-> Space
188 * Revision 1.8 2001/06/29 13:21:46 oes
189 * - Cosmetics: renamed and reordered functions, variables,
190 * texts, improved comments etc
192 * - Removed ij_untrusted_url() The relevant
193 * info is now part of the "untrusted" page,
194 * which is generated by filters.c:trust_url()
196 * - Generators of content now call finish_http_response()
197 * themselves, making jcc.c:chat() a little less
200 * - Removed obsolete "Pragma: no-cache" from our headers
202 * - http_responses now know their head length
204 * - fill_template now uses the new interface to pcrs, so that
205 * - long jobs (like whole files) no longer have to be assembled
206 * in a fixed size buffer
207 * - the new T (trivial) option is used, and the replacement may
208 * contain Perl syntax backrefs without confusing pcrs
210 * - Introduced default_exports() which generates a set of exports
211 * common to all CGIs and other content generators
213 * - Introduced convenience function map_block_killer()
215 * - Introduced convenience function make_menu()
217 * - Introduced CGI-like function error_response() which generates
218 * the "No such domain" and "Connect failed" messages using the
221 * - cgi_show_url_info:
222 * - adapted to new CGI features
223 * - form and answers now generated from same template
224 * - http:// prefix in URL now OK
227 * - adapted to new CGI features
228 * - no longer uses csp->init_proxy_args
231 * - moved menu generation to make_menu()
233 * - add_stats now writes single export map entries instead
236 * - Moved redirect_url() to filters.c
238 * - Fixed mem leak in free_http_response(), map_block_killer(),
240 * - Removed logentry from cancelled commit
242 * Revision 1.7 2001/06/09 10:51:58 jongfoster
243 * Changing "show URL info" handler to new style.
244 * Changing BUFSIZ ==> BUFFER_SIZE
246 * Revision 1.6 2001/06/07 23:05:19 jongfoster
247 * Removing code related to old forward and ACL files.
249 * Revision 1.5 2001/06/05 19:59:16 jongfoster
250 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
252 * Revision 1.4 2001/06/04 10:41:52 swa
253 * show version string of cgi.h and cgi.c
255 * Revision 1.3 2001/06/03 19:12:16 oes
256 * introduced new cgi handling
258 * No revisions before 1.3
260 **********************************************************************/
266 #include <sys/types.h>
273 #define snprintf _snprintf
274 #endif /* def _WIN32 */
282 #include "miscutil.h"
283 #include "cgisimple.h"
284 #ifdef FEATURE_CGI_EDIT_ACTIONS
286 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
288 /* loadcfg.h is for g_bToggleIJB only */
290 const char cgi_h_rcs[] = CGI_H_VERSION;
292 static const struct cgi_dispatcher cgi_dispatchers[] = {
295 "Junkbuster main page" },
298 "Show information about the current configuration" },
301 "Show the source code version numbers" },
304 "Show the client's request headers." },
307 "Show which actions apply to a URL and why" },
310 "Toggle JunkBuster on or off" },
311 #ifdef FEATURE_CGI_EDIT_ACTIONS
314 "Edit the actions list" },
315 { "edit-actions-for-url",
316 cgi_edit_actions_for_url,
317 NULL /* Edit the actions for (a) specified URL(s) */ },
318 { "edit-actions-list",
319 cgi_edit_actions_list,
320 NULL /* Edit the actions list */ },
321 { "edit-actions-submit",
322 cgi_edit_actions_submit,
323 NULL /* Change the actions for (a) specified URL(s) */ },
324 { "edit-actions-url",
325 cgi_edit_actions_url,
326 NULL /* Change a URL pattern in the actionsfile */ },
327 { "edit-actions-url-form",
328 cgi_edit_actions_url_form,
329 NULL /* Form to change a URL pattern in the actionsfile */ },
330 { "edit-actions-add-url",
331 cgi_edit_actions_add_url,
332 NULL /* Add a URL pattern to the actionsfile */ },
333 { "edit-actions-add-url-form",
334 cgi_edit_actions_add_url_form,
335 NULL /* Form to add a URL pattern to the actionsfile */ },
336 { "edit-actions-remove-url",
337 cgi_edit_actions_remove_url,
338 NULL /* Remove a URL pattern from the actionsfile */ },
339 { "edit-actions-remove-url-form",
340 cgi_edit_actions_remove_url_form,
341 NULL /* Form to remove a URL pattern from the actionsfile */ },
342 { "edit-actions-section-remove",
343 cgi_edit_actions_section_remove,
344 NULL /* Remove a section from the actionsfile */ },
345 { "edit-actions-section-add",
346 cgi_edit_actions_section_add,
347 NULL /* Remove a section from the actionsfile */ },
348 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
351 NULL /* Sends a robots.txt file to tell robots to go away. */ },
354 NULL /* Send the transparent or \"Junkbuster\" gif */ },
355 { NULL, /* NULL Indicates end of list and default page */
357 NULL /* Unknown CGI page */ }
364 * Hint: You can encode your own GIFs like this:
365 * perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o,", unpack("C", $c)); }'
368 const char image_junkbuster_gif_data[] =
369 "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
370 "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
371 "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
372 "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
373 "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
374 "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
375 "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
378 const int image_junkbuster_gif_length = sizeof(image_junkbuster_gif_data) - 1;
381 const char image_blank_gif_data[] =
382 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
383 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
384 "\000\001\000\000\002\002D\001\000;";
386 const int image_blank_gif_length = sizeof(image_blank_gif_data) - 1;
389 static struct http_response cgi_error_memory_response[1];
392 static struct http_response *dispatch_known_cgi(struct client_state * csp,
394 static struct map *parse_cgi_parameters(char *argstring);
397 /*********************************************************************
399 * Function : dispatch_cgi
401 * Description : Checks if a request URL has either the magical hostname
402 * i.j.b or matches HOME_PAGE_URL/config/. If so, it passes
403 * the (rest of the) path onto dispatch_known_cgi, which
404 * calls the relevant CGI handler function.
407 * 1 : csp = Current client state (buffers, headers, etc...)
409 * Returns : http_response if match, NULL if nonmatch or handler fail
411 *********************************************************************/
412 struct http_response *dispatch_cgi(struct client_state *csp)
414 const char *host = csp->http->host;
415 const char *path = csp->http->path;
418 * Should we intercept ?
421 /* Either the host matches CGI_PREFIX_HOST ..*/
422 if ( (0 == strcmpic(host, CGI_PREFIX_HOST))
423 && (path[0] == '/') )
425 /* ..then the path will all be for us. Remove leading '/' */
428 /* Or it's the host part HOME_PAGE_URL, and the path /config/ */
429 else if ( (0 == strcmpic(host, HOME_PAGE_URL + 7 ))
430 && (0 == strncmpic(path,"/config", 7)) )
432 /* take everything following "/config" */
436 /* skip the forward slash after "/config" */
439 else if (*path != '\0')
441 /* wierdness: URL is /configXXX, where XXX is some string */
452 * This is a CGI call.
455 return dispatch_known_cgi(csp, path);
459 /*********************************************************************
461 * Function : dispatch_known_cgi
463 * Description : Processes a CGI once dispatch_cgi has determined that
464 * it matches one of the magic prefixes. Parses the path
465 * as a cgi name plus query string, prepares a map that
466 * maps CGI parameter names to their values, initializes
467 * the http_response struct, and calls the relevant CGI
471 * 1 : csp = Current client state (buffers, headers, etc...)
472 * 2 : path = Path of CGI, with the CGI prefix removed.
473 * Should not have a leading "/".
475 * Returns : http_response, or NULL on handler failure or out of
478 *********************************************************************/
479 static struct http_response *dispatch_known_cgi(struct client_state * csp,
482 const struct cgi_dispatcher *d;
483 struct map *param_list;
484 struct http_response *rsp;
485 char *query_args_start;
489 if (NULL == (path_copy = strdup(path)))
491 return cgi_error_memory();
494 query_args_start = path_copy;
495 while (*query_args_start && *query_args_start != '?')
499 if (*query_args_start == '?')
501 *query_args_start++ = '\0';
504 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
507 return cgi_error_memory();
513 * path_copy = CGI call name
514 * param_list = CGI params, as map
517 /* Get mem for response or fail*/
518 if (NULL == (rsp = alloc_http_response()))
521 free_map(param_list);
522 return cgi_error_memory();
525 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
526 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
527 csp->ip_addr_str, csp->http->cmd);
529 /* Find and start the right CGI function*/
530 for (d = cgi_dispatchers; FOREVER; d++)
532 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
534 err = (d->handler)(csp, rsp, param_list);
536 free_map(param_list);
537 if (err == JB_ERR_CGI_PARAMS)
539 err = cgi_error_bad_param(csp, rsp);
544 return finish_http_response(rsp);
548 /* Error in handler, probably out-of-memory */
549 free_http_response(rsp);
550 return cgi_error_memory();
557 /*********************************************************************
559 * Function : parse_cgi_parameters
561 * Description : Parse a URL-encoded argument string into name/value
562 * pairs and store them in a struct map list.
565 * 1 : string = string to be parsed. Will be trashed.
567 * Returns : pointer to param list, or NULL if out of memory.
569 *********************************************************************/
570 static struct map *parse_cgi_parameters(char *argstring)
573 char *vector[BUFFER_SIZE];
575 struct map *cgi_params;
577 if (NULL == (cgi_params = new_map()))
582 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
584 for (i = 0; i < pairs; i++)
586 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
589 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
591 free_map(cgi_params);
602 /*********************************************************************
604 * Function : error_response
606 * Description : returns an http_response that explains the reason
607 * why a request failed.
610 * 1 : csp = Current client state (buffers, headers, etc...)
611 * 2 : templatename = Which template should be used for the answer
612 * 3 : sys_err = system error number
614 * Returns : A http_response. If we run out of memory, this
615 * will be cgi_error_memory().
617 *********************************************************************/
618 struct http_response *error_response(struct client_state *csp,
619 const char *templatename,
623 struct http_response *rsp;
624 struct map * exports = default_exports(csp, NULL);
627 return cgi_error_memory();
630 if (NULL == (rsp = alloc_http_response()))
633 return cgi_error_memory();
636 err = map(exports, "host-html", 1, html_encode(csp->http->host), 0);
637 if (!err) err = map(exports, "hostport", 1, csp->http->hostport, 1);
638 if (!err) err = map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
639 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
640 if (!err) err = map(exports, "path-html", 1, html_encode(csp->http->path), 0);
641 if (!err) err = map(exports, "error", 1, safe_strerror(sys_err), 0);
642 if (!err) err = map(exports, "host-ip", 1, csp->http->host_ip_addr_str, 1);
647 free_http_response(rsp);
648 return cgi_error_memory();
651 if (!strcmp(templatename, "no-such-domain"))
653 rsp->status = strdup("404 No such domain");
654 if (rsp->status == NULL)
657 free_http_response(rsp);
658 return cgi_error_memory();
661 else if (!strcmp(templatename, "connect-failed"))
663 rsp->status = strdup("503 Connect failed");
664 if (rsp->status == NULL)
667 free_http_response(rsp);
668 return cgi_error_memory();
672 err = template_fill_for_cgi(csp, templatename, exports, rsp);
675 free_http_response(rsp);
676 return cgi_error_memory();
679 return finish_http_response(rsp);
683 /*********************************************************************
685 * Function : cgi_init_error_messages
687 * Description : Call at the start of the program to initialize
688 * the error message used by cgi_error_memory().
694 *********************************************************************/
695 void cgi_init_error_messages(void)
697 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
698 cgi_error_memory_response->head =
699 "HTTP/1.0 500 Internal JunkBuster Proxy Error\r\n"
700 "Content-Type: text/html\r\n"
702 cgi_error_memory_response->body =
704 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
706 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
707 "<p>JunkBuster <b>ran out of memory</b> whilst processing your request.</p>\r\n"
708 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
712 cgi_error_memory_response->head_length =
713 strlen(cgi_error_memory_response->head);
714 cgi_error_memory_response->content_length =
715 strlen(cgi_error_memory_response->body);
719 /*********************************************************************
721 * Function : cgi_error_memory
723 * Description : Called if a CGI function runs out of memory.
724 * Returns a statically-allocated error response.
727 * 1 : csp = Current client state (buffers, headers, etc...)
728 * 2 : rsp = http_response data structure for output
729 * 3 : template_name = Name of template that could not
732 * Returns : JB_ERR_OK on success
733 * JB_ERR_MEMORY on out-of-memory error.
735 *********************************************************************/
736 struct http_response *cgi_error_memory(void)
738 /* assert that it's been initialized. */
739 assert(cgi_error_memory_response->head);
741 return cgi_error_memory_response;
745 /*********************************************************************
747 * Function : cgi_error_no_template
749 * Description : Almost-CGI function that is called if a templae
750 * cannot be loaded. Note this is not a true CGI,
751 * it takes a template name rather than a map of
755 * 1 : csp = Current client state (buffers, headers, etc...)
756 * 2 : rsp = http_response data structure for output
757 * 3 : template_name = Name of template that could not
760 * Returns : JB_ERR_OK on success
761 * JB_ERR_MEMORY on out-of-memory error.
763 *********************************************************************/
764 jb_err cgi_error_no_template(struct client_state *csp,
765 struct http_response *rsp,
766 const char *template_name)
768 static const char status[] =
769 "500 Internal JunkBuster Proxy Error";
770 static const char body_prefix[] =
772 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
774 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
775 "<p>JunkBuster encountered an error whilst processing your request:</p>\r\n"
776 "<p><b>Could not load template file <code>";
777 static const char body_suffix[] =
778 "</code></b></p>\r\n"
779 "<p>Please contact your proxy administrator.</p>\r\n"
780 "<p>If you are the proxy administrator, please put the required file "
781 "in the <code><i>(confdir)</i>/templates</code> directory. The "
782 "location of the <code><i>(confdir)</i></code> directory "
783 "is specified in the main JunkBuster <code>config</code> "
784 "file. (It's typically the JunkBuster install directory"
786 ", or <code>/etc/junkbuster/</code>"
787 #endif /* ndef _WIN32 */
794 assert(template_name);
796 /* Reset rsp, if needed */
800 rsp->content_length = 0;
801 rsp->head_length = 0;
804 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
805 if (rsp->body == NULL)
807 return JB_ERR_MEMORY;
809 strcpy(rsp->body, body_prefix);
810 strcat(rsp->body, template_name);
811 strcat(rsp->body, body_suffix);
813 rsp->status = strdup(status);
814 if (rsp->body == NULL)
816 return JB_ERR_MEMORY;
823 /*********************************************************************
825 * Function : cgi_error_bad_param
827 * Description : CGI function that is called if the parameters
828 * (query string) for a CGI were wrong.
831 * 1 : csp = Current client state (buffers, headers, etc...)
832 * 2 : rsp = http_response data structure for output
834 * CGI Parameters : none
836 * Returns : JB_ERR_OK on success
837 * JB_ERR_MEMORY on out-of-memory error.
839 *********************************************************************/
840 jb_err cgi_error_bad_param(struct client_state *csp,
841 struct http_response *rsp)
848 if (NULL == (exports = default_exports(csp, NULL)))
850 return JB_ERR_MEMORY;
853 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
857 /*********************************************************************
859 * Function : get_http_time
861 * Description : Get the time in a format suitable for use in a
862 * HTTP header - e.g.:
863 * "Sun, 06 Nov 1994 08:49:37 GMT"
866 * 1 : time_offset = Time returned will be current time
867 * plus this number of seconds.
868 * 2 : buf = Destination for result. Must be long enough
869 * to hold 29 characters plus a trailing zero.
873 *********************************************************************/
874 void get_http_time(int time_offset, char *buf)
876 static const char day_names[7][4] =
877 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
878 static const char month_names[12][4] =
879 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
880 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
887 time(¤t_time); /* get current time */
889 current_time += time_offset;
891 /* get and save the gmt */
895 t = gmtime_r(¤t_time, &dummy);
897 t = gmtime(¤t_time);
901 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
903 "%s, %02d %s %4d %02d:%02d:%02d GMT",
904 day_names[t->tm_wday],
906 month_names[t->tm_mon],
916 /*********************************************************************
918 * Function : finish_http_response
920 * Description : Fill in the missing headers in an http response,
921 * and flatten the headers to an http head.
924 * 1 : rsp = pointer to http_response to be processed
926 * Returns : A http_response, usually the rsp parameter.
927 * On error, free()s rsp and returns cgi_error_memory()
929 *********************************************************************/
930 struct http_response *finish_http_response(struct http_response *rsp)
932 char buf[BUFFER_SIZE];
935 /* Special case - do NOT change this statically allocated response,
936 * which is ready for output anyway.
938 if (rsp == cgi_error_memory_response)
944 * Fill in the HTTP Status
946 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
947 err = enlist_first(rsp->headers, buf);
950 * Set the Content-Length
952 if (rsp->content_length == 0)
954 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
958 sprintf(buf, "Content-Length: %d", rsp->content_length);
959 err = enlist(rsp->headers, buf);
963 * Fill in the default headers:
965 * Content-Type: default to text/html if not already specified.
966 * Date: set to current date/time.
967 * Last-Modified: set to date/time the page was last changed.
968 * Expires: set to date/time page next needs reloading.
969 * Cache-Control: set to "no-cache" if applicable.
971 * See http://www.w3.org/Protocols/rfc2068/rfc2068
973 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
978 * Set Expires to about 10 min into the future so it'll get reloaded
979 * occasionally, e.g. if IJB gets upgraded.
984 get_http_time(0, buf);
985 err = enlist_unique_header(rsp->headers, "Date", buf);
988 /* Some date in the past. */
989 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
993 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
994 err = enlist_unique_header(rsp->headers, "Expires", buf);
1000 * Compliant browsers should not cache this due to the "Cache-Control"
1001 * setting. However, to be certain, we also set both "Last-Modified"
1002 * and "Expires" to the current time.
1004 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1006 get_http_time(0, buf);
1007 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1008 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1009 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1016 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1018 free_http_response(rsp);
1019 return cgi_error_memory();
1021 rsp->head_length = strlen(rsp->head);
1028 /*********************************************************************
1030 * Function : alloc_http_response
1032 * Description : Allocates a new http_response structure.
1036 * Returns : pointer to a new http_response, or NULL.
1038 *********************************************************************/
1039 struct http_response *alloc_http_response(void)
1041 return (struct http_response *) zalloc(sizeof(struct http_response));
1046 /*********************************************************************
1048 * Function : free_http_response
1050 * Description : Free the memory occupied by an http_response
1051 * and its depandant structures.
1054 * 1 : rsp = pointer to http_response to be freed
1058 *********************************************************************/
1059 void free_http_response(struct http_response *rsp)
1062 * Must special case cgi_error_memory_response, which is never freed.
1064 if (rsp && (rsp != cgi_error_memory_response))
1069 destroy_list(rsp->headers);
1076 /*********************************************************************
1078 * Function : template_load
1080 * Description : CGI support function that loads a given HTML
1081 * template from the confdir, ignoring comment
1085 * 1 : csp = Current client state (buffers, headers, etc...)
1086 * 2 : template_ptr = Destination for pointer to loaded
1088 * 3 : template = name of the HTML template to be used
1090 * Returns : JB_ERR_OK on success
1091 * JB_ERR_MEMORY on out-of-memory error.
1092 * JB_ERR_FILE if the template file cannot be read
1094 *********************************************************************/
1095 jb_err template_load(struct client_state *csp, char ** template_ptr,
1096 const char *templatename)
1098 char *templates_dir_path;
1102 char buf[BUFFER_SIZE];
1105 assert(template_ptr);
1106 assert(templatename);
1108 *template_ptr = NULL;
1111 * Open template file or fail
1114 templates_dir_path = make_path(csp->config->confdir, "templates");
1115 if (templates_dir_path == NULL)
1117 return JB_ERR_MEMORY;
1120 full_path = make_path(templates_dir_path, templatename);
1121 free(templates_dir_path);
1122 if (full_path == NULL)
1124 return JB_ERR_MEMORY;
1127 file_buffer = strdup("");
1128 if (file_buffer == NULL)
1131 return JB_ERR_MEMORY;
1134 if (NULL == (fp = fopen(full_path, "r")))
1136 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1144 * Read the file, ignoring comments.
1146 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1147 * This is unlikely in practise.
1149 while (fgets(buf, BUFFER_SIZE, fp))
1151 /* skip lines starting with '#' */
1157 if (string_append(&file_buffer, buf))
1160 return JB_ERR_MEMORY;
1165 *template_ptr = file_buffer;
1171 /*********************************************************************
1173 * Function : template_fill
1175 * Description : CGI support function that fills in a pre-loaded
1176 * HTML template by replacing @name@ with value using
1177 * pcrs, for each item in the output map.
1179 * Note that a leading '$' charachter in the export map's
1180 * values will be stripped and toggle on backreference
1184 * 1 : template_ptr = IN: Template to be filled out.
1186 * OUT: Filled out template.
1187 * Caller must free().
1188 * 2 : exports = map with fill in symbol -> name pairs
1190 * Returns : JB_ERR_OK on success
1191 * JB_ERR_MEMORY on out-of-memory error
1193 *********************************************************************/
1194 jb_err template_fill(char **template_ptr, const struct map *exports)
1196 struct map_entry *m;
1198 char buf[BUFFER_SIZE];
1199 char *tmp_out_buffer;
1205 assert(template_ptr);
1206 assert(*template_ptr);
1209 file_buffer = *template_ptr;
1210 size = strlen(file_buffer) + 1;
1213 * Assemble pcrs joblist from exports map
1215 for (m = exports->first; m != NULL; m = m->next)
1217 if (*m->name == '$')
1220 * First character of name is '$', so remove this flag
1221 * character and allow backreferences ($1 etc) in the
1222 * "replace with" text.
1224 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1230 * Treat the "replace with" text as a literal string -
1231 * no quoting needed, no backreferences allowed.
1232 * ("Trivial" ['T'] flag).
1236 /* Enclose name in @@ */
1237 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1241 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1243 /* Make and run job. */
1244 job = pcrs_compile(buf, m->value, flags, &error);
1247 if (error == PCRS_ERR_NOMEM)
1250 *template_ptr = NULL;
1251 return JB_ERR_MEMORY;
1255 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1256 /* Hope it wasn't important and silently ignore the invalid job */
1261 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1264 if (NULL == tmp_out_buffer)
1266 *template_ptr = NULL;
1267 return JB_ERR_MEMORY;
1269 file_buffer = tmp_out_buffer;
1276 *template_ptr = file_buffer;
1281 /*********************************************************************
1283 * Function : template_fill_for_cgi
1285 * Description : CGI support function that loads a HTML template
1286 * and fills it in. Handles file-not-found errors
1287 * by sending a HTML error message. For convenience,
1288 * this function also frees the passed "exports" map.
1291 * 1 : csp = Client state
1292 * 2 : templatename = name of the HTML template to be used
1293 * 3 : exports = map with fill in symbol -> name pairs.
1294 * Will be freed by this function.
1296 * Returns : JB_ERR_OK on success
1297 * JB_ERR_MEMORY on out-of-memory error
1299 *********************************************************************/
1300 jb_err template_fill_for_cgi(struct client_state *csp,
1301 const char *templatename,
1302 struct map *exports,
1303 struct http_response *rsp)
1308 assert(templatename);
1312 err = template_load(csp, &rsp->body, templatename);
1313 if (err == JB_ERR_FILE)
1316 return cgi_error_no_template(csp, rsp, templatename);
1321 return err; /* JB_ERR_MEMORY */
1323 err = template_fill(&rsp->body, exports);
1329 /*********************************************************************
1331 * Function : default_exports
1333 * Description : returns a struct map list that contains exports
1334 * which are common to all CGI functions.
1337 * 1 : csp = Current client state (buffers, headers, etc...)
1338 * 2 : caller = name of CGI who calls us and which should
1339 * be excluded from the generated menu. May be
1341 * Returns : NULL if no memory, else a new map. Caller frees.
1343 *********************************************************************/
1344 struct map *default_exports(const struct client_state *csp, const char *caller)
1348 struct map * exports;
1349 int local_help_exists = 0;
1353 exports = new_map();
1354 if (exports == NULL)
1359 err = map(exports, "version", 1, VERSION, 1);
1360 if (!err) err = map(exports, "my-ip-address", 1, csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown", 1);
1361 if (!err) err = map(exports, "my-hostname", 1, csp->my_hostname ? csp->my_hostname : "unknown", 1);
1362 if (!err) err = map(exports, "homepage", 1, HOME_PAGE_URL, 1);
1363 if (!err) err = map(exports, "default-cgi", 1, HOME_PAGE_URL "/config", 1);
1364 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
1365 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
1366 if (!err) err = map_conditional(exports, "enabled-display", g_bToggleIJB);
1368 snprintf(buf, 20, "%d", csp->config->hport);
1369 if (!err) err = map(exports, "my-port", 1, buf, 1);
1371 if(!strcmp(CODE_STATUS, "stable"))
1373 if (!err) err = map_block_killer(exports, "unstable");
1376 if (csp->config->admin_address != NULL)
1378 if (!err) err = map(exports, "admin-address", 1, csp->config->admin_address, 1);
1379 local_help_exists = 1;
1383 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
1386 if (csp->config->proxy_info_url != NULL)
1388 if (!err) err = map(exports, "proxy-info-url", 1, csp->config->proxy_info_url, 1);
1389 local_help_exists = 1;
1393 if (!err) err = map_block_killer(exports, "have-proxy-info");
1396 if (local_help_exists == 0)
1398 if (!err) err = map_block_killer(exports, "have-help-info");
1411 /*********************************************************************
1413 * Function : map_block_killer
1415 * Description : Convenience function.
1416 * Adds a "killer" for the conditional HTML-template
1417 * block <name>, i.e. a substitution of the regex
1418 * "if-<name>-start.*if-<name>-end" to the given
1422 * 1 : exports = map to extend
1423 * 2 : name = name of conditional block
1425 * Returns : JB_ERR_OK on success
1426 * JB_ERR_MEMORY on out-of-memory error.
1428 *********************************************************************/
1429 jb_err map_block_killer(struct map *exports, const char *name)
1431 char buf[1000]; /* Will do, since the names are hardwired */
1435 assert(strlen(name) < 490);
1437 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1438 return map(exports, buf, 1, "", 1);
1442 /*********************************************************************
1444 * Function : map_conditional
1446 * Description : Convenience function.
1447 * Adds an "if-then-else" for the conditional HTML-template
1448 * block <name>, i.e. a substitution of the form:
1455 * The control structure and one of the alternatives
1459 * 1 : exports = map to extend
1460 * 2 : name = name of conditional block
1461 * 3 : choose_first = nonzero for first, zero for second.
1463 * Returns : JB_ERR_OK on success
1464 * JB_ERR_MEMORY on out-of-memory error.
1466 *********************************************************************/
1467 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
1469 char buf[1000]; /* Will do, since the names are hardwired */
1474 assert(strlen(name) < 480);
1476 snprintf(buf, 1000, (choose_first
1477 ? "else-not-%s@.*@endif-%s"
1478 : "if-%s-then@.*@else-not-%s"),
1481 err = map(exports, buf, 1, "", 1);
1487 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1488 return map(exports, buf, 1, "", 1);
1492 /*********************************************************************
1494 * Function : make_menu
1496 * Description : Returns an HTML-formatted menu of the available
1497 * unhidden CGIs, excluding the one given in <self>.
1499 * Parameters : self = name of CGI to leave out, can be NULL
1501 * Returns : menu string
1503 *********************************************************************/
1504 char *make_menu(const char *self)
1506 const struct cgi_dispatcher *d;
1507 char buf[BUFFER_SIZE];
1508 char *result = NULL;
1512 self = "NO-SUCH-CGI!";
1515 /* List available unhidden CGI's and export as "other-cgis" */
1516 for (d = cgi_dispatchers; d->name; d++)
1518 if (d->description && strcmp(d->name, self))
1520 snprintf(buf, BUFFER_SIZE, "<li><a href=\"%s/config/%s\">%s</a></li>\n",
1521 HOME_PAGE_URL, d->name, d->description);
1522 result = strsav(result, buf);
1530 /*********************************************************************
1532 * Function : dump_map
1534 * Description : HTML-dump a map for debugging
1537 * 1 : the_map = map to dump
1539 * Returns : string with HTML
1541 *********************************************************************/
1542 char *dump_map(const struct map *the_map)
1544 struct map_entry *cur_entry = the_map->first;
1547 ret = strsav(ret, "<table>\n");
1551 ret = strsav(ret, "<tr><td><b>");
1552 ret = strsav(ret, cur_entry->name);
1553 ret = strsav(ret, "</b></td><td>");
1554 ret = strsav(ret, cur_entry->value);
1555 ret = strsav(ret, "</td></tr>\n");
1556 cur_entry = cur_entry->next;
1559 ret = strsav(ret, "</table>\n");