1 const char cgi_rcs[] = "$Id: cgi.c,v 1.40 2002/01/09 14:26:46 oes 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.40 2002/01/09 14:26:46 oes
42 * Added support for thread-safe gmtime_r call.
44 * Revision 1.39 2001/11/16 00:48:13 jongfoster
45 * Fixing a compiler warning
47 * Revision 1.38 2001/11/13 00:31:21 jongfoster
48 * - Adding new CGIs for use by non-JavaScript browsers:
49 * edit-actions-url-form
50 * edit-actions-add-url-form
51 * edit-actions-remove-url-form
52 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
55 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
56 * Show enablement/disablement status in almost all templates.
57 * There is a little trickiness here: apparent recursive resolution of
58 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
59 * the actual enablement status. So a similar construct,
60 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
63 * Revision 1.36 2001/10/26 17:33:27 oes
66 * Revision 1.35 2001/10/23 21:48:19 jongfoster
67 * Cleaning up error handling in CGI functions - they now send back
68 * a HTML error page and should never cause a FATAL error. (Fixes one
69 * potential source of "denial of service" attacks).
71 * CGI actions file editor that works and is actually useful.
73 * Ability to toggle JunkBuster remotely using a CGI call.
75 * You can turn off both the above features in the main configuration
76 * file, e.g. if you are running a multi-user proxy.
78 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
79 * Only show "Local support" on templates conditionally:
80 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
81 * - if not, no Local support section appears
83 * Revision 1.33 2001/10/14 22:28:41 jongfoster
86 * Revision 1.32 2001/10/14 22:20:18 jongfoster
87 * - Changes to CGI dispatching method to match CGI names exactly,
88 * rather than doing a prefix match.
89 * - No longer need to count the length of the CGI handler names by hand.
90 * - Adding new handler for 404 error when disptching a CGI, if none of
92 * - Adding new handlers for CGI actionsfile editor.
94 * Revision 1.31 2001/10/10 10:56:39 oes
95 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
97 * Revision 1.30 2001/10/02 15:30:57 oes
98 * Introduced show-request cgi
100 * Revision 1.29 2001/09/20 15:47:44 steudten
102 * Fix BUG: Modify int size to size_t size in fill_template()
103 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
105 * Revision 1.28 2001/09/19 18:00:37 oes
106 * - Deletef time() FIXME (Can't fail under Linux either, if
107 * the argument is guaranteed to be in out address space,
110 * - Pointer notation cosmetics
111 * - Fixed a minor bug in template_fill(): Failiure of
112 * pcrs_execute() now secure.
114 * Revision 1.27 2001/09/16 17:08:54 jongfoster
115 * Moving simple CGI functions from cgi.c to new file cgisimple.c
117 * Revision 1.26 2001/09/16 15:47:37 jongfoster
118 * First version of CGI-based edit interface. This is very much a
119 * work-in-progress, and you can't actually use it to edit anything
120 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
121 * to have any effect.
123 * Revision 1.25 2001/09/16 15:02:35 jongfoster
124 * Adding i.j.b/robots.txt.
125 * Inlining add_stats() since it's only ever called from one place.
127 * Revision 1.24 2001/09/16 11:38:01 jongfoster
128 * Splitting fill_template() into 2 functions:
129 * template_load() loads the file
130 * template_fill() performs the PCRS regexps.
131 * This is because the CGI edit interface has a "table row"
132 * template which is used many times in the page - this
133 * change means it's only loaded from disk once.
135 * Revision 1.23 2001/09/16 11:16:05 jongfoster
136 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
138 * Revision 1.22 2001/09/16 11:00:10 jongfoster
139 * New function alloc_http_response, for symmetry with free_http_response
141 * Revision 1.21 2001/09/13 23:53:03 jongfoster
142 * Support for both static and dynamically generated CGI pages.
143 * Correctly setting Last-Modified: and Expires: HTTP headers.
145 * Revision 1.20 2001/09/13 23:40:36 jongfoster
146 * (Cosmetic only) Indentation correction
148 * Revision 1.19 2001/09/13 23:31:25 jongfoster
149 * Moving image data to cgi.c rather than cgi.h.
151 * Revision 1.18 2001/08/05 16:06:20 jongfoster
152 * Modifiying "struct map" so that there are now separate header and
153 * "map_entry" structures. This means that functions which modify a
154 * map no longer need to return a pointer to the modified map.
155 * Also, it no longer reverses the order of the entries (which may be
156 * important with some advanced template substitutions).
158 * Revision 1.17 2001/08/05 15:57:38 oes
159 * Adapted finish_http_response to new list_to_text
161 * Revision 1.16 2001/08/01 21:33:18 jongfoster
162 * Changes to fill_template() that reduce memory usage without having
163 * an impact on performance. I also renamed some variables so as not
164 * to clash with the C++ keywords "new" and "template".
166 * Revision 1.15 2001/08/01 21:19:22 jongfoster
167 * Moving file version information to a separate CGI page.
169 * Revision 1.14 2001/08/01 00:19:03 jongfoster
170 * New function: map_conditional() for an if-then-else syntax.
171 * Changing to use new version of show_defines()
173 * Revision 1.13 2001/07/30 22:08:36 jongfoster
174 * Tidying up #defines:
175 * - All feature #defines are now of the form FEATURE_xxx
176 * - Permanently turned off WIN_GUI_EDIT
177 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
179 * Revision 1.12 2001/07/29 18:47:05 jongfoster
180 * Adding missing #include "loadcfg.h"
182 * Revision 1.11 2001/07/18 17:24:37 oes
183 * Changed to conform to new pcrs interface
185 * Revision 1.10 2001/07/13 13:53:13 oes
186 * Removed all #ifdef PCRS and related code
188 * Revision 1.9 2001/06/29 21:45:41 oes
189 * Indentation, CRLF->LF, Tab-> Space
191 * Revision 1.8 2001/06/29 13:21:46 oes
192 * - Cosmetics: renamed and reordered functions, variables,
193 * texts, improved comments etc
195 * - Removed ij_untrusted_url() The relevant
196 * info is now part of the "untrusted" page,
197 * which is generated by filters.c:trust_url()
199 * - Generators of content now call finish_http_response()
200 * themselves, making jcc.c:chat() a little less
203 * - Removed obsolete "Pragma: no-cache" from our headers
205 * - http_responses now know their head length
207 * - fill_template now uses the new interface to pcrs, so that
208 * - long jobs (like whole files) no longer have to be assembled
209 * in a fixed size buffer
210 * - the new T (trivial) option is used, and the replacement may
211 * contain Perl syntax backrefs without confusing pcrs
213 * - Introduced default_exports() which generates a set of exports
214 * common to all CGIs and other content generators
216 * - Introduced convenience function map_block_killer()
218 * - Introduced convenience function make_menu()
220 * - Introduced CGI-like function error_response() which generates
221 * the "No such domain" and "Connect failed" messages using the
224 * - cgi_show_url_info:
225 * - adapted to new CGI features
226 * - form and answers now generated from same template
227 * - http:// prefix in URL now OK
230 * - adapted to new CGI features
231 * - no longer uses csp->init_proxy_args
234 * - moved menu generation to make_menu()
236 * - add_stats now writes single export map entries instead
239 * - Moved redirect_url() to filters.c
241 * - Fixed mem leak in free_http_response(), map_block_killer(),
243 * - Removed logentry from cancelled commit
245 * Revision 1.7 2001/06/09 10:51:58 jongfoster
246 * Changing "show URL info" handler to new style.
247 * Changing BUFSIZ ==> BUFFER_SIZE
249 * Revision 1.6 2001/06/07 23:05:19 jongfoster
250 * Removing code related to old forward and ACL files.
252 * Revision 1.5 2001/06/05 19:59:16 jongfoster
253 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
255 * Revision 1.4 2001/06/04 10:41:52 swa
256 * show version string of cgi.h and cgi.c
258 * Revision 1.3 2001/06/03 19:12:16 oes
259 * introduced new cgi handling
261 * No revisions before 1.3
263 **********************************************************************/
269 #include <sys/types.h>
276 #define snprintf _snprintf
277 #endif /* def _WIN32 */
285 #include "miscutil.h"
286 #include "cgisimple.h"
287 #ifdef FEATURE_CGI_EDIT_ACTIONS
289 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
291 /* loadcfg.h is for g_bToggleIJB only */
293 const char cgi_h_rcs[] = CGI_H_VERSION;
295 static const struct cgi_dispatcher cgi_dispatchers[] = {
298 "Junkbuster main page" },
301 "Show information about the current configuration" },
304 "Show the source code version numbers" },
307 "Show the client's request headers." },
310 "Show which actions apply to a URL and why" },
313 "Toggle JunkBuster on or off" },
314 #ifdef FEATURE_CGI_EDIT_ACTIONS
317 "Edit the actions list" },
318 { "edit-actions-for-url",
319 cgi_edit_actions_for_url,
320 NULL /* Edit the actions for (a) specified URL(s) */ },
321 { "edit-actions-list",
322 cgi_edit_actions_list,
323 NULL /* Edit the actions list */ },
324 { "edit-actions-submit",
325 cgi_edit_actions_submit,
326 NULL /* Change the actions for (a) specified URL(s) */ },
327 { "edit-actions-url",
328 cgi_edit_actions_url,
329 NULL /* Change a URL pattern in the actionsfile */ },
330 { "edit-actions-url-form",
331 cgi_edit_actions_url_form,
332 NULL /* Form to change a URL pattern in the actionsfile */ },
333 { "edit-actions-add-url",
334 cgi_edit_actions_add_url,
335 NULL /* Add a URL pattern to the actionsfile */ },
336 { "edit-actions-add-url-form",
337 cgi_edit_actions_add_url_form,
338 NULL /* Form to add a URL pattern to the actionsfile */ },
339 { "edit-actions-remove-url",
340 cgi_edit_actions_remove_url,
341 NULL /* Remove a URL pattern from the actionsfile */ },
342 { "edit-actions-remove-url-form",
343 cgi_edit_actions_remove_url_form,
344 NULL /* Form to remove a URL pattern from the actionsfile */ },
345 { "edit-actions-section-remove",
346 cgi_edit_actions_section_remove,
347 NULL /* Remove a section from the actionsfile */ },
348 { "edit-actions-section-add",
349 cgi_edit_actions_section_add,
350 NULL /* Remove a section from the actionsfile */ },
351 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
354 NULL /* Sends a robots.txt file to tell robots to go away. */ },
357 NULL /* Send the transparent or \"Junkbuster\" gif */ },
358 { NULL, /* NULL Indicates end of list and default page */
360 NULL /* Unknown CGI page */ }
367 * Hint: You can encode your own GIFs like this:
368 * perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o,", unpack("C", $c)); }'
371 const char image_junkbuster_gif_data[] =
372 "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
373 "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
374 "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
375 "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
376 "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
377 "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
378 "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
381 const int image_junkbuster_gif_length = sizeof(image_junkbuster_gif_data) - 1;
384 const char image_blank_gif_data[] =
385 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
386 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
387 "\000\001\000\000\002\002D\001\000;";
389 const int image_blank_gif_length = sizeof(image_blank_gif_data) - 1;
392 static struct http_response cgi_error_memory_response[1];
395 static struct http_response *dispatch_known_cgi(struct client_state * csp,
397 static struct map *parse_cgi_parameters(char *argstring);
400 /*********************************************************************
402 * Function : dispatch_cgi
404 * Description : Checks if a request URL has either the magical
405 * hostname CGI_SITE_1_HOST (usully http://i.j.b/) or
406 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
407 * http://ijbswa.sourceforge.net/config). If so, it passes
408 * the (rest of the) path onto dispatch_known_cgi, which
409 * calls the relevant CGI handler function.
412 * 1 : csp = Current client state (buffers, headers, etc...)
414 * Returns : http_response if match, NULL if nonmatch or handler fail
416 *********************************************************************/
417 struct http_response *dispatch_cgi(struct client_state *csp)
419 const char *host = csp->http->host;
420 const char *path = csp->http->path;
423 * Should we intercept ?
426 /* Note: "example.com" and "example.com." are equivalent hostnames. */
428 /* Either the host matches CGI_SITE_1_HOST ..*/
429 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
430 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
431 && (path[0] == '/') )
433 /* ..then the path will all be for us. Remove leading '/' */
436 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
437 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
438 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
439 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
441 /* take everything following CGI_SITE_2_PATH */
442 path += strlen(CGI_SITE_2_PATH);
445 /* skip the forward slash after CGI_SITE_2_PATH */
448 else if (*path != '\0')
451 * wierdness: URL is /configXXX, where XXX is some string
452 * Do *NOT* intercept.
464 * This is a CGI call.
467 return dispatch_known_cgi(csp, path);
471 /*********************************************************************
473 * Function : dispatch_known_cgi
475 * Description : Processes a CGI once dispatch_cgi has determined that
476 * it matches one of the magic prefixes. Parses the path
477 * as a cgi name plus query string, prepares a map that
478 * maps CGI parameter names to their values, initializes
479 * the http_response struct, and calls the relevant CGI
483 * 1 : csp = Current client state (buffers, headers, etc...)
484 * 2 : path = Path of CGI, with the CGI prefix removed.
485 * Should not have a leading "/".
487 * Returns : http_response, or NULL on handler failure or out of
490 *********************************************************************/
491 static struct http_response *dispatch_known_cgi(struct client_state * csp,
494 const struct cgi_dispatcher *d;
495 struct map *param_list;
496 struct http_response *rsp;
497 char *query_args_start;
501 if (NULL == (path_copy = strdup(path)))
503 return cgi_error_memory();
506 query_args_start = path_copy;
507 while (*query_args_start && *query_args_start != '?')
511 if (*query_args_start == '?')
513 *query_args_start++ = '\0';
516 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
519 return cgi_error_memory();
525 * path_copy = CGI call name
526 * param_list = CGI params, as map
529 /* Get mem for response or fail*/
530 if (NULL == (rsp = alloc_http_response()))
533 free_map(param_list);
534 return cgi_error_memory();
537 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
538 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
539 csp->ip_addr_str, csp->http->cmd);
541 /* Find and start the right CGI function*/
542 for (d = cgi_dispatchers; FOREVER; d++)
544 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
546 err = (d->handler)(csp, rsp, param_list);
548 free_map(param_list);
549 if (err == JB_ERR_CGI_PARAMS)
551 err = cgi_error_bad_param(csp, rsp);
556 return finish_http_response(rsp);
560 /* Error in handler, probably out-of-memory */
561 free_http_response(rsp);
562 return cgi_error_memory();
569 /*********************************************************************
571 * Function : parse_cgi_parameters
573 * Description : Parse a URL-encoded argument string into name/value
574 * pairs and store them in a struct map list.
577 * 1 : string = string to be parsed. Will be trashed.
579 * Returns : pointer to param list, or NULL if out of memory.
581 *********************************************************************/
582 static struct map *parse_cgi_parameters(char *argstring)
585 char *vector[BUFFER_SIZE];
587 struct map *cgi_params;
589 if (NULL == (cgi_params = new_map()))
594 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
596 for (i = 0; i < pairs; i++)
598 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
601 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
603 free_map(cgi_params);
614 /*********************************************************************
616 * Function : error_response
618 * Description : returns an http_response that explains the reason
619 * why a request failed.
622 * 1 : csp = Current client state (buffers, headers, etc...)
623 * 2 : templatename = Which template should be used for the answer
624 * 3 : sys_err = system error number
626 * Returns : A http_response. If we run out of memory, this
627 * will be cgi_error_memory().
629 *********************************************************************/
630 struct http_response *error_response(struct client_state *csp,
631 const char *templatename,
635 struct http_response *rsp;
636 struct map * exports = default_exports(csp, NULL);
639 return cgi_error_memory();
642 if (NULL == (rsp = alloc_http_response()))
645 return cgi_error_memory();
648 err = map(exports, "host-html", 1, html_encode(csp->http->host), 0);
649 if (!err) err = map(exports, "hostport", 1, csp->http->hostport, 1);
650 if (!err) err = map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
651 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
652 if (!err) err = map(exports, "path-html", 1, html_encode(csp->http->path), 0);
653 if (!err) err = map(exports, "error", 1, safe_strerror(sys_err), 0);
654 if (!err) err = map(exports, "host-ip", 1, csp->http->host_ip_addr_str, 1);
659 free_http_response(rsp);
660 return cgi_error_memory();
663 if (!strcmp(templatename, "no-such-domain"))
665 rsp->status = strdup("404 No such domain");
666 if (rsp->status == NULL)
669 free_http_response(rsp);
670 return cgi_error_memory();
673 else if (!strcmp(templatename, "connect-failed"))
675 rsp->status = strdup("503 Connect failed");
676 if (rsp->status == NULL)
679 free_http_response(rsp);
680 return cgi_error_memory();
684 err = template_fill_for_cgi(csp, templatename, exports, rsp);
687 free_http_response(rsp);
688 return cgi_error_memory();
691 return finish_http_response(rsp);
695 /*********************************************************************
697 * Function : cgi_init_error_messages
699 * Description : Call at the start of the program to initialize
700 * the error message used by cgi_error_memory().
706 *********************************************************************/
707 void cgi_init_error_messages(void)
709 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
710 cgi_error_memory_response->head =
711 "HTTP/1.0 500 Internal JunkBuster Proxy Error\r\n"
712 "Content-Type: text/html\r\n"
714 cgi_error_memory_response->body =
716 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
718 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
719 "<p>JunkBuster <b>ran out of memory</b> whilst processing your request.</p>\r\n"
720 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
724 cgi_error_memory_response->head_length =
725 strlen(cgi_error_memory_response->head);
726 cgi_error_memory_response->content_length =
727 strlen(cgi_error_memory_response->body);
731 /*********************************************************************
733 * Function : cgi_error_memory
735 * Description : Called if a CGI function runs out of memory.
736 * Returns a statically-allocated error response.
739 * 1 : csp = Current client state (buffers, headers, etc...)
740 * 2 : rsp = http_response data structure for output
741 * 3 : template_name = Name of template that could not
744 * Returns : JB_ERR_OK on success
745 * JB_ERR_MEMORY on out-of-memory error.
747 *********************************************************************/
748 struct http_response *cgi_error_memory(void)
750 /* assert that it's been initialized. */
751 assert(cgi_error_memory_response->head);
753 return cgi_error_memory_response;
757 /*********************************************************************
759 * Function : cgi_error_no_template
761 * Description : Almost-CGI function that is called if a templae
762 * cannot be loaded. Note this is not a true CGI,
763 * it takes a template name rather than a map of
767 * 1 : csp = Current client state (buffers, headers, etc...)
768 * 2 : rsp = http_response data structure for output
769 * 3 : template_name = Name of template that could not
772 * Returns : JB_ERR_OK on success
773 * JB_ERR_MEMORY on out-of-memory error.
775 *********************************************************************/
776 jb_err cgi_error_no_template(struct client_state *csp,
777 struct http_response *rsp,
778 const char *template_name)
780 static const char status[] =
781 "500 Internal JunkBuster Proxy Error";
782 static const char body_prefix[] =
784 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
786 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
787 "<p>JunkBuster encountered an error whilst processing your request:</p>\r\n"
788 "<p><b>Could not load template file <code>";
789 static const char body_suffix[] =
790 "</code></b></p>\r\n"
791 "<p>Please contact your proxy administrator.</p>\r\n"
792 "<p>If you are the proxy administrator, please put the required file "
793 "in the <code><i>(confdir)</i>/templates</code> directory. The "
794 "location of the <code><i>(confdir)</i></code> directory "
795 "is specified in the main JunkBuster <code>config</code> "
796 "file. (It's typically the JunkBuster install directory"
798 ", or <code>/etc/junkbuster/</code>"
799 #endif /* ndef _WIN32 */
806 assert(template_name);
808 /* Reset rsp, if needed */
812 rsp->content_length = 0;
813 rsp->head_length = 0;
816 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
817 if (rsp->body == NULL)
819 return JB_ERR_MEMORY;
821 strcpy(rsp->body, body_prefix);
822 strcat(rsp->body, template_name);
823 strcat(rsp->body, body_suffix);
825 rsp->status = strdup(status);
826 if (rsp->body == NULL)
828 return JB_ERR_MEMORY;
835 /*********************************************************************
837 * Function : cgi_error_bad_param
839 * Description : CGI function that is called if the parameters
840 * (query string) for a CGI were wrong.
843 * 1 : csp = Current client state (buffers, headers, etc...)
844 * 2 : rsp = http_response data structure for output
846 * CGI Parameters : none
848 * Returns : JB_ERR_OK on success
849 * JB_ERR_MEMORY on out-of-memory error.
851 *********************************************************************/
852 jb_err cgi_error_bad_param(struct client_state *csp,
853 struct http_response *rsp)
860 if (NULL == (exports = default_exports(csp, NULL)))
862 return JB_ERR_MEMORY;
865 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
869 /*********************************************************************
871 * Function : get_http_time
873 * Description : Get the time in a format suitable for use in a
874 * HTTP header - e.g.:
875 * "Sun, 06 Nov 1994 08:49:37 GMT"
878 * 1 : time_offset = Time returned will be current time
879 * plus this number of seconds.
880 * 2 : buf = Destination for result. Must be long enough
881 * to hold 29 characters plus a trailing zero.
885 *********************************************************************/
886 void get_http_time(int time_offset, char *buf)
888 static const char day_names[7][4] =
889 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
890 static const char month_names[12][4] =
891 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
892 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
899 time(¤t_time); /* get current time */
901 current_time += time_offset;
903 /* get and save the gmt */
907 t = gmtime_r(¤t_time, &dummy);
909 t = gmtime(¤t_time);
913 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
915 "%s, %02d %s %4d %02d:%02d:%02d GMT",
916 day_names[t->tm_wday],
918 month_names[t->tm_mon],
928 /*********************************************************************
930 * Function : finish_http_response
932 * Description : Fill in the missing headers in an http response,
933 * and flatten the headers to an http head.
936 * 1 : rsp = pointer to http_response to be processed
938 * Returns : A http_response, usually the rsp parameter.
939 * On error, free()s rsp and returns cgi_error_memory()
941 *********************************************************************/
942 struct http_response *finish_http_response(struct http_response *rsp)
944 char buf[BUFFER_SIZE];
947 /* Special case - do NOT change this statically allocated response,
948 * which is ready for output anyway.
950 if (rsp == cgi_error_memory_response)
956 * Fill in the HTTP Status
958 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
959 err = enlist_first(rsp->headers, buf);
962 * Set the Content-Length
964 if (rsp->content_length == 0)
966 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
970 sprintf(buf, "Content-Length: %d", rsp->content_length);
971 err = enlist(rsp->headers, buf);
975 * Fill in the default headers:
977 * Content-Type: default to text/html if not already specified.
978 * Date: set to current date/time.
979 * Last-Modified: set to date/time the page was last changed.
980 * Expires: set to date/time page next needs reloading.
981 * Cache-Control: set to "no-cache" if applicable.
983 * See http://www.w3.org/Protocols/rfc2068/rfc2068
985 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
990 * Set Expires to about 10 min into the future so it'll get reloaded
991 * occasionally, e.g. if IJB gets upgraded.
996 get_http_time(0, buf);
997 err = enlist_unique_header(rsp->headers, "Date", buf);
1000 /* Some date in the past. */
1001 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1005 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1006 err = enlist_unique_header(rsp->headers, "Expires", buf);
1012 * Compliant browsers should not cache this due to the "Cache-Control"
1013 * setting. However, to be certain, we also set both "Last-Modified"
1014 * and "Expires" to the current time.
1016 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1018 get_http_time(0, buf);
1019 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1020 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1021 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1028 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1030 free_http_response(rsp);
1031 return cgi_error_memory();
1033 rsp->head_length = strlen(rsp->head);
1040 /*********************************************************************
1042 * Function : alloc_http_response
1044 * Description : Allocates a new http_response structure.
1048 * Returns : pointer to a new http_response, or NULL.
1050 *********************************************************************/
1051 struct http_response *alloc_http_response(void)
1053 return (struct http_response *) zalloc(sizeof(struct http_response));
1058 /*********************************************************************
1060 * Function : free_http_response
1062 * Description : Free the memory occupied by an http_response
1063 * and its depandant structures.
1066 * 1 : rsp = pointer to http_response to be freed
1070 *********************************************************************/
1071 void free_http_response(struct http_response *rsp)
1074 * Must special case cgi_error_memory_response, which is never freed.
1076 if (rsp && (rsp != cgi_error_memory_response))
1081 destroy_list(rsp->headers);
1088 /*********************************************************************
1090 * Function : template_load
1092 * Description : CGI support function that loads a given HTML
1093 * template from the confdir, ignoring comment
1097 * 1 : csp = Current client state (buffers, headers, etc...)
1098 * 2 : template_ptr = Destination for pointer to loaded
1100 * 3 : template = name of the HTML template to be used
1102 * Returns : JB_ERR_OK on success
1103 * JB_ERR_MEMORY on out-of-memory error.
1104 * JB_ERR_FILE if the template file cannot be read
1106 *********************************************************************/
1107 jb_err template_load(struct client_state *csp, char ** template_ptr,
1108 const char *templatename)
1110 char *templates_dir_path;
1114 char buf[BUFFER_SIZE];
1117 assert(template_ptr);
1118 assert(templatename);
1120 *template_ptr = NULL;
1123 * Open template file or fail
1126 templates_dir_path = make_path(csp->config->confdir, "templates");
1127 if (templates_dir_path == NULL)
1129 return JB_ERR_MEMORY;
1132 full_path = make_path(templates_dir_path, templatename);
1133 free(templates_dir_path);
1134 if (full_path == NULL)
1136 return JB_ERR_MEMORY;
1139 file_buffer = strdup("");
1140 if (file_buffer == NULL)
1143 return JB_ERR_MEMORY;
1146 if (NULL == (fp = fopen(full_path, "r")))
1148 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1156 * Read the file, ignoring comments.
1158 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1159 * This is unlikely in practise.
1161 while (fgets(buf, BUFFER_SIZE, fp))
1163 /* skip lines starting with '#' */
1169 if (string_append(&file_buffer, buf))
1172 return JB_ERR_MEMORY;
1177 *template_ptr = file_buffer;
1183 /*********************************************************************
1185 * Function : template_fill
1187 * Description : CGI support function that fills in a pre-loaded
1188 * HTML template by replacing @name@ with value using
1189 * pcrs, for each item in the output map.
1191 * Note that a leading '$' charachter in the export map's
1192 * values will be stripped and toggle on backreference
1196 * 1 : template_ptr = IN: Template to be filled out.
1198 * OUT: Filled out template.
1199 * Caller must free().
1200 * 2 : exports = map with fill in symbol -> name pairs
1202 * Returns : JB_ERR_OK on success
1203 * JB_ERR_MEMORY on out-of-memory error
1205 *********************************************************************/
1206 jb_err template_fill(char **template_ptr, const struct map *exports)
1208 struct map_entry *m;
1210 char buf[BUFFER_SIZE];
1211 char *tmp_out_buffer;
1217 assert(template_ptr);
1218 assert(*template_ptr);
1221 file_buffer = *template_ptr;
1222 size = strlen(file_buffer) + 1;
1225 * Assemble pcrs joblist from exports map
1227 for (m = exports->first; m != NULL; m = m->next)
1229 if (*m->name == '$')
1232 * First character of name is '$', so remove this flag
1233 * character and allow backreferences ($1 etc) in the
1234 * "replace with" text.
1236 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1242 * Treat the "replace with" text as a literal string -
1243 * no quoting needed, no backreferences allowed.
1244 * ("Trivial" ['T'] flag).
1248 /* Enclose name in @@ */
1249 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1253 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1255 /* Make and run job. */
1256 job = pcrs_compile(buf, m->value, flags, &error);
1259 if (error == PCRS_ERR_NOMEM)
1262 *template_ptr = NULL;
1263 return JB_ERR_MEMORY;
1267 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1268 /* Hope it wasn't important and silently ignore the invalid job */
1273 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1276 if (NULL == tmp_out_buffer)
1278 *template_ptr = NULL;
1279 return JB_ERR_MEMORY;
1281 file_buffer = tmp_out_buffer;
1288 *template_ptr = file_buffer;
1293 /*********************************************************************
1295 * Function : template_fill_for_cgi
1297 * Description : CGI support function that loads a HTML template
1298 * and fills it in. Handles file-not-found errors
1299 * by sending a HTML error message. For convenience,
1300 * this function also frees the passed "exports" map.
1303 * 1 : csp = Client state
1304 * 2 : templatename = name of the HTML template to be used
1305 * 3 : exports = map with fill in symbol -> name pairs.
1306 * Will be freed by this function.
1308 * Returns : JB_ERR_OK on success
1309 * JB_ERR_MEMORY on out-of-memory error
1311 *********************************************************************/
1312 jb_err template_fill_for_cgi(struct client_state *csp,
1313 const char *templatename,
1314 struct map *exports,
1315 struct http_response *rsp)
1320 assert(templatename);
1324 err = template_load(csp, &rsp->body, templatename);
1325 if (err == JB_ERR_FILE)
1328 return cgi_error_no_template(csp, rsp, templatename);
1333 return err; /* JB_ERR_MEMORY */
1335 err = template_fill(&rsp->body, exports);
1341 /*********************************************************************
1343 * Function : default_exports
1345 * Description : returns a struct map list that contains exports
1346 * which are common to all CGI functions.
1349 * 1 : csp = Current client state (buffers, headers, etc...)
1350 * 2 : caller = name of CGI who calls us and which should
1351 * be excluded from the generated menu. May be
1353 * Returns : NULL if no memory, else a new map. Caller frees.
1355 *********************************************************************/
1356 struct map *default_exports(const struct client_state *csp, const char *caller)
1360 struct map * exports;
1361 int local_help_exists = 0;
1365 exports = new_map();
1366 if (exports == NULL)
1371 err = map(exports, "version", 1, VERSION, 1);
1372 if (!err) err = map(exports, "my-ip-address", 1, csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown", 1);
1373 if (!err) err = map(exports, "my-hostname", 1, csp->my_hostname ? csp->my_hostname : "unknown", 1);
1374 if (!err) err = map(exports, "homepage", 1, HOME_PAGE_URL, 1);
1375 if (!err) err = map(exports, "default-cgi", 1, CGI_PREFIX, 1);
1376 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
1377 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
1378 if (!err) err = map_conditional(exports, "enabled-display", g_bToggleIJB);
1380 snprintf(buf, 20, "%d", csp->config->hport);
1381 if (!err) err = map(exports, "my-port", 1, buf, 1);
1383 if(!strcmp(CODE_STATUS, "stable"))
1385 if (!err) err = map_block_killer(exports, "unstable");
1388 if (csp->config->admin_address != NULL)
1390 if (!err) err = map(exports, "admin-address", 1, csp->config->admin_address, 1);
1391 local_help_exists = 1;
1395 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
1398 if (csp->config->proxy_info_url != NULL)
1400 if (!err) err = map(exports, "proxy-info-url", 1, csp->config->proxy_info_url, 1);
1401 local_help_exists = 1;
1405 if (!err) err = map_block_killer(exports, "have-proxy-info");
1408 if (local_help_exists == 0)
1410 if (!err) err = map_block_killer(exports, "have-help-info");
1423 /*********************************************************************
1425 * Function : map_block_killer
1427 * Description : Convenience function.
1428 * Adds a "killer" for the conditional HTML-template
1429 * block <name>, i.e. a substitution of the regex
1430 * "if-<name>-start.*if-<name>-end" to the given
1434 * 1 : exports = map to extend
1435 * 2 : name = name of conditional block
1437 * Returns : JB_ERR_OK on success
1438 * JB_ERR_MEMORY on out-of-memory error.
1440 *********************************************************************/
1441 jb_err map_block_killer(struct map *exports, const char *name)
1443 char buf[1000]; /* Will do, since the names are hardwired */
1447 assert(strlen(name) < 490);
1449 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1450 return map(exports, buf, 1, "", 1);
1454 /*********************************************************************
1456 * Function : map_conditional
1458 * Description : Convenience function.
1459 * Adds an "if-then-else" for the conditional HTML-template
1460 * block <name>, i.e. a substitution of the form:
1467 * The control structure and one of the alternatives
1471 * 1 : exports = map to extend
1472 * 2 : name = name of conditional block
1473 * 3 : choose_first = nonzero for first, zero for second.
1475 * Returns : JB_ERR_OK on success
1476 * JB_ERR_MEMORY on out-of-memory error.
1478 *********************************************************************/
1479 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
1481 char buf[1000]; /* Will do, since the names are hardwired */
1486 assert(strlen(name) < 480);
1488 snprintf(buf, 1000, (choose_first
1489 ? "else-not-%s@.*@endif-%s"
1490 : "if-%s-then@.*@else-not-%s"),
1493 err = map(exports, buf, 1, "", 1);
1499 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1500 return map(exports, buf, 1, "", 1);
1504 /*********************************************************************
1506 * Function : make_menu
1508 * Description : Returns an HTML-formatted menu of the available
1509 * unhidden CGIs, excluding the one given in <self>.
1511 * Parameters : self = name of CGI to leave out, can be NULL
1513 * Returns : menu string
1515 *********************************************************************/
1516 char *make_menu(const char *self)
1518 const struct cgi_dispatcher *d;
1519 char buf[BUFFER_SIZE];
1520 char *result = NULL;
1524 self = "NO-SUCH-CGI!";
1527 /* List available unhidden CGI's and export as "other-cgis" */
1528 for (d = cgi_dispatchers; d->name; d++)
1530 if (d->description && strcmp(d->name, self))
1532 snprintf(buf, BUFFER_SIZE, "<li><a href=\"%s%s\">%s</a></li>\n",
1533 CGI_PREFIX, d->name, d->description);
1534 result = strsav(result, buf);
1542 /*********************************************************************
1544 * Function : dump_map
1546 * Description : HTML-dump a map for debugging
1549 * 1 : the_map = map to dump
1551 * Returns : string with HTML
1553 *********************************************************************/
1554 char *dump_map(const struct map *the_map)
1556 struct map_entry *cur_entry = the_map->first;
1559 ret = strsav(ret, "<table>\n");
1563 ret = strsav(ret, "<tr><td><b>");
1564 ret = strsav(ret, cur_entry->name);
1565 ret = strsav(ret, "</b></td><td>");
1566 ret = strsav(ret, cur_entry->value);
1567 ret = strsav(ret, "</td></tr>\n");
1568 cur_entry = cur_entry->next;
1571 ret = strsav(ret, "</table>\n");