1 const char cgi_rcs[] = "$Id: cgi.c,v 1.37 2001/11/01 14:28:47 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.37 2001/11/01 14:28:47 david__schmidt
42 * Show enablement/disablement status in almost all templates.
43 * There is a little trickiness here: apparent recursive resolution of
44 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
45 * the actual enablement status. So a similar construct,
46 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
49 * Revision 1.36 2001/10/26 17:33:27 oes
52 * Revision 1.35 2001/10/23 21:48:19 jongfoster
53 * Cleaning up error handling in CGI functions - they now send back
54 * a HTML error page and should never cause a FATAL error. (Fixes one
55 * potential source of "denial of service" attacks).
57 * CGI actions file editor that works and is actually useful.
59 * Ability to toggle JunkBuster remotely using a CGI call.
61 * You can turn off both the above features in the main configuration
62 * file, e.g. if you are running a multi-user proxy.
64 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
65 * Only show "Local support" on templates conditionally:
66 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
67 * - if not, no Local support section appears
69 * Revision 1.33 2001/10/14 22:28:41 jongfoster
72 * Revision 1.32 2001/10/14 22:20:18 jongfoster
73 * - Changes to CGI dispatching method to match CGI names exactly,
74 * rather than doing a prefix match.
75 * - No longer need to count the length of the CGI handler names by hand.
76 * - Adding new handler for 404 error when disptching a CGI, if none of
78 * - Adding new handlers for CGI actionsfile editor.
80 * Revision 1.31 2001/10/10 10:56:39 oes
81 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
83 * Revision 1.30 2001/10/02 15:30:57 oes
84 * Introduced show-request cgi
86 * Revision 1.29 2001/09/20 15:47:44 steudten
88 * Fix BUG: Modify int size to size_t size in fill_template()
89 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
91 * Revision 1.28 2001/09/19 18:00:37 oes
92 * - Deletef time() FIXME (Can't fail under Linux either, if
93 * the argument is guaranteed to be in out address space,
96 * - Pointer notation cosmetics
97 * - Fixed a minor bug in template_fill(): Failiure of
98 * pcrs_execute() now secure.
100 * Revision 1.27 2001/09/16 17:08:54 jongfoster
101 * Moving simple CGI functions from cgi.c to new file cgisimple.c
103 * Revision 1.26 2001/09/16 15:47:37 jongfoster
104 * First version of CGI-based edit interface. This is very much a
105 * work-in-progress, and you can't actually use it to edit anything
106 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
107 * to have any effect.
109 * Revision 1.25 2001/09/16 15:02:35 jongfoster
110 * Adding i.j.b/robots.txt.
111 * Inlining add_stats() since it's only ever called from one place.
113 * Revision 1.24 2001/09/16 11:38:01 jongfoster
114 * Splitting fill_template() into 2 functions:
115 * template_load() loads the file
116 * template_fill() performs the PCRS regexps.
117 * This is because the CGI edit interface has a "table row"
118 * template which is used many times in the page - this
119 * change means it's only loaded from disk once.
121 * Revision 1.23 2001/09/16 11:16:05 jongfoster
122 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
124 * Revision 1.22 2001/09/16 11:00:10 jongfoster
125 * New function alloc_http_response, for symmetry with free_http_response
127 * Revision 1.21 2001/09/13 23:53:03 jongfoster
128 * Support for both static and dynamically generated CGI pages.
129 * Correctly setting Last-Modified: and Expires: HTTP headers.
131 * Revision 1.20 2001/09/13 23:40:36 jongfoster
132 * (Cosmetic only) Indentation correction
134 * Revision 1.19 2001/09/13 23:31:25 jongfoster
135 * Moving image data to cgi.c rather than cgi.h.
137 * Revision 1.18 2001/08/05 16:06:20 jongfoster
138 * Modifiying "struct map" so that there are now separate header and
139 * "map_entry" structures. This means that functions which modify a
140 * map no longer need to return a pointer to the modified map.
141 * Also, it no longer reverses the order of the entries (which may be
142 * important with some advanced template substitutions).
144 * Revision 1.17 2001/08/05 15:57:38 oes
145 * Adapted finish_http_response to new list_to_text
147 * Revision 1.16 2001/08/01 21:33:18 jongfoster
148 * Changes to fill_template() that reduce memory usage without having
149 * an impact on performance. I also renamed some variables so as not
150 * to clash with the C++ keywords "new" and "template".
152 * Revision 1.15 2001/08/01 21:19:22 jongfoster
153 * Moving file version information to a separate CGI page.
155 * Revision 1.14 2001/08/01 00:19:03 jongfoster
156 * New function: map_conditional() for an if-then-else syntax.
157 * Changing to use new version of show_defines()
159 * Revision 1.13 2001/07/30 22:08:36 jongfoster
160 * Tidying up #defines:
161 * - All feature #defines are now of the form FEATURE_xxx
162 * - Permanently turned off WIN_GUI_EDIT
163 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
165 * Revision 1.12 2001/07/29 18:47:05 jongfoster
166 * Adding missing #include "loadcfg.h"
168 * Revision 1.11 2001/07/18 17:24:37 oes
169 * Changed to conform to new pcrs interface
171 * Revision 1.10 2001/07/13 13:53:13 oes
172 * Removed all #ifdef PCRS and related code
174 * Revision 1.9 2001/06/29 21:45:41 oes
175 * Indentation, CRLF->LF, Tab-> Space
177 * Revision 1.8 2001/06/29 13:21:46 oes
178 * - Cosmetics: renamed and reordered functions, variables,
179 * texts, improved comments etc
181 * - Removed ij_untrusted_url() The relevant
182 * info is now part of the "untrusted" page,
183 * which is generated by filters.c:trust_url()
185 * - Generators of content now call finish_http_response()
186 * themselves, making jcc.c:chat() a little less
189 * - Removed obsolete "Pragma: no-cache" from our headers
191 * - http_responses now know their head length
193 * - fill_template now uses the new interface to pcrs, so that
194 * - long jobs (like whole files) no longer have to be assembled
195 * in a fixed size buffer
196 * - the new T (trivial) option is used, and the replacement may
197 * contain Perl syntax backrefs without confusing pcrs
199 * - Introduced default_exports() which generates a set of exports
200 * common to all CGIs and other content generators
202 * - Introduced convenience function map_block_killer()
204 * - Introduced convenience function make_menu()
206 * - Introduced CGI-like function error_response() which generates
207 * the "No such domain" and "Connect failed" messages using the
210 * - cgi_show_url_info:
211 * - adapted to new CGI features
212 * - form and answers now generated from same template
213 * - http:// prefix in URL now OK
216 * - adapted to new CGI features
217 * - no longer uses csp->init_proxy_args
220 * - moved menu generation to make_menu()
222 * - add_stats now writes single export map entries instead
225 * - Moved redirect_url() to filters.c
227 * - Fixed mem leak in free_http_response(), map_block_killer(),
229 * - Removed logentry from cancelled commit
231 * Revision 1.7 2001/06/09 10:51:58 jongfoster
232 * Changing "show URL info" handler to new style.
233 * Changing BUFSIZ ==> BUFFER_SIZE
235 * Revision 1.6 2001/06/07 23:05:19 jongfoster
236 * Removing code related to old forward and ACL files.
238 * Revision 1.5 2001/06/05 19:59:16 jongfoster
239 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
241 * Revision 1.4 2001/06/04 10:41:52 swa
242 * show version string of cgi.h and cgi.c
244 * Revision 1.3 2001/06/03 19:12:16 oes
245 * introduced new cgi handling
247 * No revisions before 1.3
249 **********************************************************************/
255 #include <sys/types.h>
262 #define snprintf _snprintf
263 #endif /* def _WIN32 */
271 #include "miscutil.h"
272 #include "cgisimple.h"
273 #ifdef FEATURE_CGI_EDIT_ACTIONS
275 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
277 /* loadcfg.h is for g_bToggleIJB only */
279 const char cgi_h_rcs[] = CGI_H_VERSION;
281 static const struct cgi_dispatcher cgi_dispatchers[] = {
284 "Junkbuster main page" },
287 "Show information about the current configuration" },
290 "Show the source code version numbers" },
293 "Show the client's request headers." },
296 "Show which actions apply to a URL and why" },
299 "Toggle JunkBuster on or off" },
300 #ifdef FEATURE_CGI_EDIT_ACTIONS
303 "Edit the actions list" },
304 { "edit-actions-for-url",
305 cgi_edit_actions_for_url,
306 NULL /* Edit the actions for (a) specified URL(s) */ },
307 { "edit-actions-list",
308 cgi_edit_actions_list,
309 NULL /* Edit the actions list */ },
310 { "edit-actions-submit",
311 cgi_edit_actions_submit,
312 NULL /* Change the actions for (a) specified URL(s) */ },
313 { "edit-actions-url",
314 cgi_edit_actions_url,
315 NULL /* Change a URL pattern in the actionsfile */ },
316 { "edit-actions-url-form",
317 cgi_edit_actions_url_form,
318 NULL /* Form to change a URL pattern in the actionsfile */ },
319 { "edit-actions-add-url",
320 cgi_edit_actions_add_url,
321 NULL /* Add a URL pattern to the actionsfile */ },
322 { "edit-actions-add-url-form",
323 cgi_edit_actions_add_url_form,
324 NULL /* Form to add a URL pattern to the actionsfile */ },
325 { "edit-actions-remove-url",
326 cgi_edit_actions_remove_url,
327 NULL /* Remove a URL pattern from the actionsfile */ },
328 { "edit-actions-remove-url-form",
329 cgi_edit_actions_remove_url_form,
330 NULL /* Form to remove a URL pattern from the actionsfile */ },
331 { "edit-actions-section-remove",
332 cgi_edit_actions_section_remove,
333 NULL /* Remove a section from the actionsfile */ },
334 { "edit-actions-section-add",
335 cgi_edit_actions_section_add,
336 NULL /* Remove a section from the actionsfile */ },
337 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
340 NULL /* Sends a robots.txt file to tell robots to go away. */ },
343 NULL /* Send the transparent or \"Junkbuster\" gif */ },
344 { NULL, /* NULL Indicates end of list and default page */
346 NULL /* Unknown CGI page */ }
353 * Hint: You can encode your own GIFs like this:
354 * perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o,", unpack("C", $c)); }'
357 const char image_junkbuster_gif_data[] =
358 "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
359 "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
360 "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
361 "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
362 "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
363 "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
364 "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
367 const int image_junkbuster_gif_length = sizeof(image_junkbuster_gif_data) - 1;
370 const char image_blank_gif_data[] =
371 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
372 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
373 "\000\001\000\000\002\002D\001\000;";
375 const int image_blank_gif_length = sizeof(image_blank_gif_data) - 1;
378 static struct http_response cgi_error_memory_response[1];
381 static struct http_response *dispatch_known_cgi(struct client_state * csp,
385 /*********************************************************************
387 * Function : dispatch_cgi
389 * Description : Checks if a request URL has either the magical hostname
390 * i.j.b or matches HOME_PAGE_URL/config/. If so, it passes
391 * the (rest of the) path onto dispatch_known_cgi, which
392 * calls the relevant CGI handler function.
395 * 1 : csp = Current client state (buffers, headers, etc...)
397 * Returns : http_response if match, NULL if nonmatch or handler fail
399 *********************************************************************/
400 struct http_response *dispatch_cgi(struct client_state *csp)
402 const char *host = csp->http->host;
403 const char *path = csp->http->path;
406 * Should we intercept ?
409 /* Either the host matches CGI_PREFIX_HOST ..*/
410 if ( (0 == strcmpic(host, CGI_PREFIX_HOST))
411 && (path[0] == '/') )
413 /* ..then the path will all be for us. Remove leading '/' */
416 /* Or it's the host part HOME_PAGE_URL, and the path /config/ */
417 else if ( (0 == strcmpic(host, HOME_PAGE_URL + 7 ))
418 && (0 == strncmpic(path,"/config", 7)) )
420 /* take everything following "/config" */
424 /* skip the forward slash after "/config" */
427 else if (*path != '\0')
429 /* wierdness: URL is /configXXX, where XXX is some string */
440 * This is a CGI call.
443 return dispatch_known_cgi(csp, path);
447 /*********************************************************************
449 * Function : dispatch_known_cgi
451 * Description : Processes a CGI once dispatch_cgi has determined that
452 * it matches one of the magic prefixes. Parses the path
453 * as a cgi name plus query string, prepares a map that
454 * maps CGI parameter names to their values, initializes
455 * the http_response struct, and calls the relevant CGI
459 * 1 : csp = Current client state (buffers, headers, etc...)
460 * 2 : path = Path of CGI, with the CGI prefix removed.
461 * Should not have a leading "/".
463 * Returns : http_response, or NULL on handler failure or out of
466 *********************************************************************/
467 static struct http_response *dispatch_known_cgi(struct client_state * csp,
470 const struct cgi_dispatcher *d;
471 struct map *param_list;
472 struct http_response *rsp;
473 char *query_args_start;
477 if (NULL == (path_copy = strdup(path)))
479 return cgi_error_memory();
482 query_args_start = path_copy;
483 while (*query_args_start && *query_args_start != '?')
487 if (*query_args_start == '?')
489 *query_args_start++ = '\0';
492 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
495 return cgi_error_memory();
501 * path_copy = CGI call name
502 * param_list = CGI params, as map
505 /* Get mem for response or fail*/
506 if (NULL == (rsp = alloc_http_response()))
509 free_map(param_list);
510 return cgi_error_memory();
513 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
514 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
515 csp->ip_addr_str, csp->http->cmd);
517 /* Find and start the right CGI function*/
518 for (d = cgi_dispatchers; FOREVER; d++)
520 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
522 err = (d->handler)(csp, rsp, param_list);
524 free_map(param_list);
525 if (err == JB_ERR_CGI_PARAMS)
527 err = cgi_error_bad_param(csp, rsp);
532 return finish_http_response(rsp);
536 /* Error in handler, probably out-of-memory */
537 free_http_response(rsp);
538 return cgi_error_memory();
545 /*********************************************************************
547 * Function : parse_cgi_parameters
549 * Description : Parse a URL-encoded argument string into name/value
550 * pairs and store them in a struct map list.
553 * 1 : string = string to be parsed. Will be trashed.
555 * Returns : pointer to param list, or NULL if out of memory.
557 *********************************************************************/
558 static struct map *parse_cgi_parameters(char *argstring)
561 char *vector[BUFFER_SIZE];
563 struct map *cgi_params;
565 if (NULL == (cgi_params = new_map()))
570 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
572 for (i = 0; i < pairs; i++)
574 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
577 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
579 free_map(cgi_params);
590 /*********************************************************************
592 * Function : error_response
594 * Description : returns an http_response that explains the reason
595 * why a request failed.
598 * 1 : csp = Current client state (buffers, headers, etc...)
599 * 2 : templatename = Which template should be used for the answer
600 * 3 : sys_err = system error number
602 * Returns : A http_response. If we run out of memory, this
603 * will be cgi_error_memory().
605 *********************************************************************/
606 struct http_response *error_response(struct client_state *csp,
607 const char *templatename,
611 struct http_response *rsp;
612 struct map * exports = default_exports(csp, NULL);
615 return cgi_error_memory();
618 if (NULL == (rsp = alloc_http_response()))
621 return cgi_error_memory();
624 err = map(exports, "host-html", 1, html_encode(csp->http->host), 0);
625 if (!err) err = map(exports, "hostport", 1, csp->http->hostport, 1);
626 if (!err) err = map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
627 if (!err) err = map(exports, "path", 1, csp->http->path, 1);
628 if (!err) err = map(exports, "path-html", 1, html_encode(csp->http->path), 0);
629 if (!err) err = map(exports, "error", 1, safe_strerror(sys_err), 0);
630 if (!err) err = map(exports, "host-ip", 1, csp->http->host_ip_addr_str, 1);
635 free_http_response(rsp);
636 return cgi_error_memory();
639 if (!strcmp(templatename, "no-such-domain"))
641 rsp->status = strdup("404 No such domain");
642 if (rsp->status == NULL)
645 free_http_response(rsp);
646 return cgi_error_memory();
649 else if (!strcmp(templatename, "connect-failed"))
651 rsp->status = strdup("503 Connect failed");
652 if (rsp->status == NULL)
655 free_http_response(rsp);
656 return cgi_error_memory();
660 err = template_fill_for_cgi(csp, templatename, exports, rsp);
663 free_http_response(rsp);
664 return cgi_error_memory();
667 return finish_http_response(rsp);
671 /*********************************************************************
673 * Function : cgi_init_error_messages
675 * Description : Call at the start of the program to initialize
676 * the error message used by cgi_error_memory().
682 *********************************************************************/
683 void cgi_init_error_messages(void)
685 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
686 cgi_error_memory_response->head =
687 "HTTP/1.0 500 Internal JunkBuster Proxy Error\r\n"
688 "Content-Type: text/html\r\n"
690 cgi_error_memory_response->body =
692 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
694 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
695 "<p>JunkBuster <b>ran out of memory</b> whilst processing your request.</p>\r\n"
696 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
700 cgi_error_memory_response->head_length =
701 strlen(cgi_error_memory_response->head);
702 cgi_error_memory_response->content_length =
703 strlen(cgi_error_memory_response->body);
707 /*********************************************************************
709 * Function : cgi_error_memory
711 * Description : Called if a CGI function runs out of memory.
712 * Returns a statically-allocated error response.
715 * 1 : csp = Current client state (buffers, headers, etc...)
716 * 2 : rsp = http_response data structure for output
717 * 3 : template_name = Name of template that could not
720 * Returns : JB_ERR_OK on success
721 * JB_ERR_MEMORY on out-of-memory error.
723 *********************************************************************/
724 struct http_response *cgi_error_memory(void)
726 /* assert that it's been initialized. */
727 assert(cgi_error_memory_response->head);
729 return cgi_error_memory_response;
733 /*********************************************************************
735 * Function : cgi_error_no_template
737 * Description : Almost-CGI function that is called if a templae
738 * cannot be loaded. Note this is not a true CGI,
739 * it takes a template name rather than a map of
743 * 1 : csp = Current client state (buffers, headers, etc...)
744 * 2 : rsp = http_response data structure for output
745 * 3 : template_name = Name of template that could not
748 * Returns : JB_ERR_OK on success
749 * JB_ERR_MEMORY on out-of-memory error.
751 *********************************************************************/
752 jb_err cgi_error_no_template(struct client_state *csp,
753 struct http_response *rsp,
754 const char *template_name)
756 static const char status[] =
757 "500 Internal JunkBuster Proxy Error";
758 static const char body_prefix[] =
760 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
762 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
763 "<p>JunkBuster encountered an error whilst processing your request:</p>\r\n"
764 "<p><b>Could not load template file <code>";
765 static const char body_suffix[] =
766 "</code></b></p>\r\n"
767 "<p>Please contact your proxy administrator.</p>\r\n"
768 "<p>If you are the proxy administrator, please put the required file "
769 "in the <code><i>(confdir)</i>/templates</code> directory. The "
770 "location of the <code><i>(confdir)</i></code> directory "
771 "is specified in the main JunkBuster <code>config</code> "
772 "file. (It's typically the JunkBuster install directory"
774 ", or <code>/etc/junkbuster/</code>"
775 #endif /* ndef _WIN32 */
782 assert(template_name);
784 /* Reset rsp, if needed */
788 rsp->content_length = 0;
789 rsp->head_length = 0;
792 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
793 if (rsp->body == NULL)
795 return JB_ERR_MEMORY;
797 strcpy(rsp->body, body_prefix);
798 strcat(rsp->body, template_name);
799 strcat(rsp->body, body_suffix);
801 rsp->status = strdup(status);
802 if (rsp->body == NULL)
804 return JB_ERR_MEMORY;
811 /*********************************************************************
813 * Function : cgi_error_bad_param
815 * Description : CGI function that is called if the parameters
816 * (query string) for a CGI were wrong.
819 * 1 : csp = Current client state (buffers, headers, etc...)
820 * 2 : rsp = http_response data structure for output
822 * CGI Parameters : none
824 * Returns : JB_ERR_OK on success
825 * JB_ERR_MEMORY on out-of-memory error.
827 *********************************************************************/
828 jb_err cgi_error_bad_param(struct client_state *csp,
829 struct http_response *rsp)
836 if (NULL == (exports = default_exports(csp, NULL)))
838 return JB_ERR_MEMORY;
841 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
845 /*********************************************************************
847 * Function : get_http_time
849 * Description : Get the time in a format suitable for use in a
850 * HTTP header - e.g.:
851 * "Sun, 06 Nov 1994 08:49:37 GMT"
854 * 1 : time_offset = Time returned will be current time
855 * plus this number of seconds.
856 * 2 : buf = Destination for result. Must be long enough
857 * to hold 29 characters plus a trailing zero.
861 *********************************************************************/
862 void get_http_time(int time_offset, char *buf)
864 static const char day_names[7][4] =
865 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
866 static const char month_names[12][4] =
867 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
868 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
875 time(¤t_time); /* get current time */
877 current_time += time_offset;
879 /* get and save the gmt */
880 t = gmtime(¤t_time);
882 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
884 "%s, %02d %s %4d %02d:%02d:%02d GMT",
885 day_names[t->tm_wday],
887 month_names[t->tm_mon],
897 /*********************************************************************
899 * Function : finish_http_response
901 * Description : Fill in the missing headers in an http response,
902 * and flatten the headers to an http head.
905 * 1 : rsp = pointer to http_response to be processed
907 * Returns : A http_response, usually the rsp parameter.
908 * On error, free()s rsp and returns cgi_error_memory()
910 *********************************************************************/
911 struct http_response *finish_http_response(struct http_response *rsp)
913 char buf[BUFFER_SIZE];
916 /* Special case - do NOT change this statically allocated response,
917 * which is ready for output anyway.
919 if (rsp == cgi_error_memory_response)
925 * Fill in the HTTP Status
927 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
928 err = enlist_first(rsp->headers, buf);
931 * Set the Content-Length
933 if (rsp->content_length == 0)
935 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
939 sprintf(buf, "Content-Length: %d", rsp->content_length);
940 err = enlist(rsp->headers, buf);
944 * Fill in the default headers:
946 * Content-Type: default to text/html if not already specified.
947 * Date: set to current date/time.
948 * Last-Modified: set to date/time the page was last changed.
949 * Expires: set to date/time page next needs reloading.
950 * Cache-Control: set to "no-cache" if applicable.
952 * See http://www.w3.org/Protocols/rfc2068/rfc2068
954 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
959 * Set Expires to about 10 min into the future so it'll get reloaded
960 * occasionally, e.g. if IJB gets upgraded.
965 get_http_time(0, buf);
966 err = enlist_unique_header(rsp->headers, "Date", buf);
969 /* Some date in the past. */
970 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
974 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
975 err = enlist_unique_header(rsp->headers, "Expires", buf);
981 * Compliant browsers should not cache this due to the "Cache-Control"
982 * setting. However, to be certain, we also set both "Last-Modified"
983 * and "Expires" to the current time.
985 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
987 get_http_time(0, buf);
988 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
989 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
990 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
997 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
999 free_http_response(rsp);
1000 return cgi_error_memory();
1002 rsp->head_length = strlen(rsp->head);
1009 /*********************************************************************
1011 * Function : alloc_http_response
1013 * Description : Allocates a new http_response structure.
1017 * Returns : pointer to a new http_response, or NULL.
1019 *********************************************************************/
1020 struct http_response *alloc_http_response(void)
1022 return (struct http_response *) zalloc(sizeof(struct http_response));
1027 /*********************************************************************
1029 * Function : free_http_response
1031 * Description : Free the memory occupied by an http_response
1032 * and its depandant structures.
1035 * 1 : rsp = pointer to http_response to be freed
1039 *********************************************************************/
1040 void free_http_response(struct http_response *rsp)
1043 * Must special case cgi_error_memory_response, which is never freed.
1045 if (rsp && (rsp != cgi_error_memory_response))
1050 destroy_list(rsp->headers);
1057 /*********************************************************************
1059 * Function : template_load
1061 * Description : CGI support function that loads a given HTML
1062 * template from the confdir, ignoring comment
1066 * 1 : csp = Current client state (buffers, headers, etc...)
1067 * 2 : template_ptr = Destination for pointer to loaded
1069 * 3 : template = name of the HTML template to be used
1071 * Returns : JB_ERR_OK on success
1072 * JB_ERR_MEMORY on out-of-memory error.
1073 * JB_ERR_FILE if the template file cannot be read
1075 *********************************************************************/
1076 jb_err template_load(struct client_state *csp, char ** template_ptr,
1077 const char *templatename)
1079 char *templates_dir_path;
1083 char buf[BUFFER_SIZE];
1086 assert(template_ptr);
1087 assert(templatename);
1089 *template_ptr = NULL;
1092 * Open template file or fail
1095 templates_dir_path = make_path(csp->config->confdir, "templates");
1096 if (templates_dir_path == NULL)
1098 return JB_ERR_MEMORY;
1101 full_path = make_path(templates_dir_path, templatename);
1102 free(templates_dir_path);
1103 if (full_path == NULL)
1105 return JB_ERR_MEMORY;
1108 file_buffer = strdup("");
1109 if (file_buffer == NULL)
1112 return JB_ERR_MEMORY;
1115 if (NULL == (fp = fopen(full_path, "r")))
1117 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1125 * Read the file, ignoring comments.
1127 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1128 * This is unlikely in practise.
1130 while (fgets(buf, BUFFER_SIZE, fp))
1132 /* skip lines starting with '#' */
1138 if (string_append(&file_buffer, buf))
1141 return JB_ERR_MEMORY;
1146 *template_ptr = file_buffer;
1152 /*********************************************************************
1154 * Function : template_fill
1156 * Description : CGI support function that fills in a pre-loaded
1157 * HTML template by replacing @name@ with value using
1158 * pcrs, for each item in the output map.
1160 * Note that a leading '$' charachter in the export map's
1161 * values will be stripped and toggle on backreference
1165 * 1 : template_ptr = IN: Template to be filled out.
1167 * OUT: Filled out template.
1168 * Caller must free().
1169 * 2 : exports = map with fill in symbol -> name pairs
1171 * Returns : JB_ERR_OK on success
1172 * JB_ERR_MEMORY on out-of-memory error
1174 *********************************************************************/
1175 jb_err template_fill(char **template_ptr, const struct map *exports)
1177 struct map_entry *m;
1179 char buf[BUFFER_SIZE];
1180 char *tmp_out_buffer;
1186 assert(template_ptr);
1187 assert(*template_ptr);
1190 file_buffer = *template_ptr;
1191 size = strlen(file_buffer) + 1;
1194 * Assemble pcrs joblist from exports map
1196 for (m = exports->first; m != NULL; m = m->next)
1198 if (*m->name == '$')
1201 * First character of name is '$', so remove this flag
1202 * character and allow backreferences ($1 etc) in the
1203 * "replace with" text.
1205 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1211 * Treat the "replace with" text as a literal string -
1212 * no quoting needed, no backreferences allowed.
1213 * ("Trivial" ['T'] flag).
1217 /* Enclose name in @@ */
1218 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1222 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1224 /* Make and run job. */
1225 job = pcrs_compile(buf, m->value, flags, &error);
1228 if (error == PCRS_ERR_NOMEM)
1231 *template_ptr = NULL;
1232 return JB_ERR_MEMORY;
1236 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1237 /* Hope it wasn't important and silently ignore the invalid job */
1242 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1245 if (NULL == tmp_out_buffer)
1247 *template_ptr = NULL;
1248 return JB_ERR_MEMORY;
1250 file_buffer = tmp_out_buffer;
1257 *template_ptr = file_buffer;
1262 /*********************************************************************
1264 * Function : template_fill_for_cgi
1266 * Description : CGI support function that loads a HTML template
1267 * and fills it in. Handles file-not-found errors
1268 * by sending a HTML error message. For convenience,
1269 * this function also frees the passed "exports" map.
1272 * 1 : csp = Client state
1273 * 2 : templatename = name of the HTML template to be used
1274 * 3 : exports = map with fill in symbol -> name pairs.
1275 * Will be freed by this function.
1277 * Returns : JB_ERR_OK on success
1278 * JB_ERR_MEMORY on out-of-memory error
1280 *********************************************************************/
1281 jb_err template_fill_for_cgi(struct client_state *csp,
1282 const char *templatename,
1283 struct map *exports,
1284 struct http_response *rsp)
1289 assert(templatename);
1293 err = template_load(csp, &rsp->body, templatename);
1294 if (err == JB_ERR_FILE)
1297 return cgi_error_no_template(csp, rsp, templatename);
1302 return err; /* JB_ERR_MEMORY */
1304 err = template_fill(&rsp->body, exports);
1310 /*********************************************************************
1312 * Function : default_exports
1314 * Description : returns a struct map list that contains exports
1315 * which are common to all CGI functions.
1318 * 1 : csp = Current client state (buffers, headers, etc...)
1319 * 2 : caller = name of CGI who calls us and which should
1320 * be excluded from the generated menu. May be
1322 * Returns : NULL if no memory, else a new map. Caller frees.
1324 *********************************************************************/
1325 struct map *default_exports(const struct client_state *csp, const char *caller)
1329 struct map * exports;
1330 int local_help_exists = 0;
1334 exports = new_map();
1335 if (exports == NULL)
1340 err = map(exports, "version", 1, VERSION, 1);
1341 if (!err) err = map(exports, "my-ip-address", 1, csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown", 1);
1342 if (!err) err = map(exports, "my-hostname", 1, csp->my_hostname ? csp->my_hostname : "unknown", 1);
1343 if (!err) err = map(exports, "homepage", 1, HOME_PAGE_URL, 1);
1344 if (!err) err = map(exports, "default-cgi", 1, HOME_PAGE_URL "/config", 1);
1345 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
1346 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
1347 if (!err) err = map_conditional(exports, "enabled-display", g_bToggleIJB);
1349 snprintf(buf, 20, "%d", csp->config->hport);
1350 if (!err) err = map(exports, "my-port", 1, buf, 1);
1352 if(!strcmp(CODE_STATUS, "stable"))
1354 if (!err) err = map_block_killer(exports, "unstable");
1357 if (csp->config->admin_address != NULL)
1359 if (!err) err = map(exports, "admin-address", 1, csp->config->admin_address, 1);
1360 local_help_exists = 1;
1364 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
1367 if (csp->config->proxy_info_url != NULL)
1369 if (!err) err = map(exports, "proxy-info-url", 1, csp->config->proxy_info_url, 1);
1370 local_help_exists = 1;
1374 if (!err) err = map_block_killer(exports, "have-proxy-info");
1377 if (local_help_exists == 0)
1379 if (!err) err = map_block_killer(exports, "have-help-info");
1392 /*********************************************************************
1394 * Function : map_block_killer
1396 * Description : Convenience function.
1397 * Adds a "killer" for the conditional HTML-template
1398 * block <name>, i.e. a substitution of the regex
1399 * "if-<name>-start.*if-<name>-end" to the given
1403 * 1 : exports = map to extend
1404 * 2 : name = name of conditional block
1406 * Returns : JB_ERR_OK on success
1407 * JB_ERR_MEMORY on out-of-memory error.
1409 *********************************************************************/
1410 jb_err map_block_killer(struct map *exports, const char *name)
1412 char buf[1000]; /* Will do, since the names are hardwired */
1416 assert(strlen(name) < 490);
1418 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1419 return map(exports, buf, 1, "", 1);
1423 /*********************************************************************
1425 * Function : map_conditional
1427 * Description : Convenience function.
1428 * Adds an "if-then-else" for the conditional HTML-template
1429 * block <name>, i.e. a substitution of the form:
1436 * The control structure and one of the alternatives
1440 * 1 : exports = map to extend
1441 * 2 : name = name of conditional block
1442 * 3 : choose_first = nonzero for first, zero for second.
1444 * Returns : JB_ERR_OK on success
1445 * JB_ERR_MEMORY on out-of-memory error.
1447 *********************************************************************/
1448 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
1450 char buf[1000]; /* Will do, since the names are hardwired */
1455 assert(strlen(name) < 480);
1457 snprintf(buf, 1000, (choose_first
1458 ? "else-not-%s@.*@endif-%s"
1459 : "if-%s-then@.*@else-not-%s"),
1462 err = map(exports, buf, 1, "", 1);
1468 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1469 return map(exports, buf, 1, "", 1);
1473 /*********************************************************************
1475 * Function : make_menu
1477 * Description : Returns an HTML-formatted menu of the available
1478 * unhidden CGIs, excluding the one given in <self>.
1480 * Parameters : self = name of CGI to leave out, can be NULL
1482 * Returns : menu string
1484 *********************************************************************/
1485 char *make_menu(const char *self)
1487 const struct cgi_dispatcher *d;
1488 char buf[BUFFER_SIZE];
1489 char *result = NULL;
1493 self = "NO-SUCH-CGI!";
1496 /* List available unhidden CGI's and export as "other-cgis" */
1497 for (d = cgi_dispatchers; d->name; d++)
1499 if (d->description && strcmp(d->name, self))
1501 snprintf(buf, BUFFER_SIZE, "<li><a href=\"%s/config/%s\">%s</a></li>\n",
1502 HOME_PAGE_URL, d->name, d->description);
1503 result = strsav(result, buf);
1511 /*********************************************************************
1513 * Function : dump_map
1515 * Description : HTML-dump a map for debugging
1518 * 1 : the_map = map to dump
1520 * Returns : string with HTML
1522 *********************************************************************/
1523 char *dump_map(const struct map *the_map)
1525 struct map_entry *cur_entry = the_map->first;
1528 ret = strsav(ret, "<table>\n");
1532 ret = strsav(ret, "<tr><td><b>");
1533 ret = strsav(ret, cur_entry->name);
1534 ret = strsav(ret, "</b></td><td>");
1535 ret = strsav(ret, cur_entry->value);
1536 ret = strsav(ret, "</td></tr>\n");
1537 cur_entry = cur_entry->next;
1540 ret = strsav(ret, "</table>\n");