1 const char cgi_rcs[] = "$Id: cgi.c,v 1.34 2001/10/18 22:22:09 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.34 2001/10/18 22:22:09 david__schmidt
42 * Only show "Local support" on templates conditionally:
43 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
44 * - if not, no Local support section appears are removed automatically
46 * Revision 1.33 2001/10/14 22:28:41 jongfoster
49 * Revision 1.32 2001/10/14 22:20:18 jongfoster
50 * - Changes to CGI dispatching method to match CGI names exactly,
51 * rather than doing a prefix match.
52 * - No longer need to count the length of the CGI handler names by hand.
53 * - Adding new handler for 404 error when disptching a CGI, if none of
55 * - Adding new handlers for CGI actionsfile editor.
57 * Revision 1.31 2001/10/10 10:56:39 oes
58 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
60 * Revision 1.30 2001/10/02 15:30:57 oes
61 * Introduced show-request cgi
63 * Revision 1.29 2001/09/20 15:47:44 steudten
65 * Fix BUG: Modify int size to size_t size in fill_template()
66 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
68 * Revision 1.28 2001/09/19 18:00:37 oes
69 * - Deletef time() FIXME (Can't fail under Linux either, if
70 * the argument is guaranteed to be in out address space,
73 * - Pointer notation cosmetics
74 * - Fixed a minor bug in template_fill(): Failiure of
75 * pcrs_execute() now secure.
77 * Revision 1.27 2001/09/16 17:08:54 jongfoster
78 * Moving simple CGI functions from cgi.c to new file cgisimple.c
80 * Revision 1.26 2001/09/16 15:47:37 jongfoster
81 * First version of CGI-based edit interface. This is very much a
82 * work-in-progress, and you can't actually use it to edit anything
83 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
86 * Revision 1.25 2001/09/16 15:02:35 jongfoster
87 * Adding i.j.b/robots.txt.
88 * Inlining add_stats() since it's only ever called from one place.
90 * Revision 1.24 2001/09/16 11:38:01 jongfoster
91 * Splitting fill_template() into 2 functions:
92 * template_load() loads the file
93 * template_fill() performs the PCRS regexps.
94 * This is because the CGI edit interface has a "table row"
95 * template which is used many times in the page - this
96 * change means it's only loaded from disk once.
98 * Revision 1.23 2001/09/16 11:16:05 jongfoster
99 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
101 * Revision 1.22 2001/09/16 11:00:10 jongfoster
102 * New function alloc_http_response, for symmetry with free_http_response
104 * Revision 1.21 2001/09/13 23:53:03 jongfoster
105 * Support for both static and dynamically generated CGI pages.
106 * Correctly setting Last-Modified: and Expires: HTTP headers.
108 * Revision 1.20 2001/09/13 23:40:36 jongfoster
109 * (Cosmetic only) Indentation correction
111 * Revision 1.19 2001/09/13 23:31:25 jongfoster
112 * Moving image data to cgi.c rather than cgi.h.
114 * Revision 1.18 2001/08/05 16:06:20 jongfoster
115 * Modifiying "struct map" so that there are now separate header and
116 * "map_entry" structures. This means that functions which modify a
117 * map no longer need to return a pointer to the modified map.
118 * Also, it no longer reverses the order of the entries (which may be
119 * important with some advanced template substitutions).
121 * Revision 1.17 2001/08/05 15:57:38 oes
122 * Adapted finish_http_response to new list_to_text
124 * Revision 1.16 2001/08/01 21:33:18 jongfoster
125 * Changes to fill_template() that reduce memory usage without having
126 * an impact on performance. I also renamed some variables so as not
127 * to clash with the C++ keywords "new" and "template".
129 * Revision 1.15 2001/08/01 21:19:22 jongfoster
130 * Moving file version information to a separate CGI page.
132 * Revision 1.14 2001/08/01 00:19:03 jongfoster
133 * New function: map_conditional() for an if-then-else syntax.
134 * Changing to use new version of show_defines()
136 * Revision 1.13 2001/07/30 22:08:36 jongfoster
137 * Tidying up #defines:
138 * - All feature #defines are now of the form FEATURE_xxx
139 * - Permanently turned off WIN_GUI_EDIT
140 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
142 * Revision 1.12 2001/07/29 18:47:05 jongfoster
143 * Adding missing #include "loadcfg.h"
145 * Revision 1.11 2001/07/18 17:24:37 oes
146 * Changed to conform to new pcrs interface
148 * Revision 1.10 2001/07/13 13:53:13 oes
149 * Removed all #ifdef PCRS and related code
151 * Revision 1.9 2001/06/29 21:45:41 oes
152 * Indentation, CRLF->LF, Tab-> Space
154 * Revision 1.8 2001/06/29 13:21:46 oes
155 * - Cosmetics: renamed and reordered functions, variables,
156 * texts, improved comments etc
158 * - Removed ij_untrusted_url() The relevant
159 * info is now part of the "untrusted" page,
160 * which is generated by filters.c:trust_url()
162 * - Generators of content now call finish_http_response()
163 * themselves, making jcc.c:chat() a little less
166 * - Removed obsolete "Pragma: no-cache" from our headers
168 * - http_responses now know their head length
170 * - fill_template now uses the new interface to pcrs, so that
171 * - long jobs (like whole files) no longer have to be assembled
172 * in a fixed size buffer
173 * - the new T (trivial) option is used, and the replacement may
174 * contain Perl syntax backrefs without confusing pcrs
176 * - Introduced default_exports() which generates a set of exports
177 * common to all CGIs and other content generators
179 * - Introduced convenience function map_block_killer()
181 * - Introduced convenience function make_menu()
183 * - Introduced CGI-like function error_response() which generates
184 * the "No such domain" and "Connect failed" messages using the
187 * - cgi_show_url_info:
188 * - adapted to new CGI features
189 * - form and answers now generated from same template
190 * - http:// prefix in URL now OK
193 * - adapted to new CGI features
194 * - no longer uses csp->init_proxy_args
197 * - moved menu generation to make_menu()
199 * - add_stats now writes single export map entries instead
202 * - Moved redirect_url() to filters.c
204 * - Fixed mem leak in free_http_response(), map_block_killer(),
206 * - Removed logentry from cancelled commit
208 * Revision 1.7 2001/06/09 10:51:58 jongfoster
209 * Changing "show URL info" handler to new style.
210 * Changing BUFSIZ ==> BUFFER_SIZE
212 * Revision 1.6 2001/06/07 23:05:19 jongfoster
213 * Removing code related to old forward and ACL files.
215 * Revision 1.5 2001/06/05 19:59:16 jongfoster
216 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
218 * Revision 1.4 2001/06/04 10:41:52 swa
219 * show version string of cgi.h and cgi.c
221 * Revision 1.3 2001/06/03 19:12:16 oes
222 * introduced new cgi handling
224 * No revisions before 1.3
226 **********************************************************************/
232 #include <sys/types.h>
239 #define snprintf _snprintf
240 #endif /* def _WIN32 */
248 #include "miscutil.h"
249 #include "cgisimple.h"
250 #ifdef FEATURE_CGI_EDIT_ACTIONS
252 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
254 const char cgi_h_rcs[] = CGI_H_VERSION;
256 static const struct cgi_dispatcher cgi_dispatchers[] = {
259 "Junkbuster main page" },
262 "Show information about the current configuration" },
265 "Show the source code version numbers" },
268 "Show the client's request headers." },
271 "Show which actions apply to a URL and why" },
272 #ifdef FEATURE_CGI_EDIT_ACTIONS
275 "Toggle JunkBuster on or off" },
278 "Edit the actions list" },
279 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
281 #ifdef FEATURE_CGI_EDIT_ACTIONS
282 { "edit-actions-for-url",
283 cgi_edit_actions_for_url,
284 NULL /* Edit the actions for (a) specified URL(s) */ },
285 { "edit-actions-list",
286 cgi_edit_actions_list,
287 NULL /* Edit the actions list */ },
288 { "edit-actions-submit",
289 cgi_edit_actions_submit,
290 NULL /* Change the actions for (a) specified URL(s) */ },
291 { "edit-actions-url",
292 cgi_edit_actions_url,
293 NULL /* Change a URL pattern in the actionsfile */ },
294 { "edit-actions-add-url",
295 cgi_edit_actions_add_url,
296 NULL /* Add a URL pattern to the actionsfile */ },
297 { "edit-actions-remove-url",
298 cgi_edit_actions_remove_url,
299 NULL /* Add a URL pattern to the actionsfile */ },
300 { "edit-actions-section-remove",
301 cgi_edit_actions_section_remove,
302 NULL /* Remove a section from the actionsfile */ },
303 { "edit-actions-section-add",
304 cgi_edit_actions_section_add,
305 NULL /* Remove a section from the actionsfile */ },
306 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
309 NULL /* Sends a robots.txt file to tell robots to go away. */ },
312 NULL /* Send the transparent or \"Junkbuster\" gif */ },
313 { NULL, /* NULL Indicates end of list and default page */
315 NULL /* Unknown CGI page */ }
322 * Hint: You can encode your own GIFs like this:
323 * perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o,", unpack("C", $c)); }'
326 const char image_junkbuster_gif_data[] =
327 "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
328 "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
329 "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
330 "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
331 "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
332 "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
333 "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
336 const int image_junkbuster_gif_length = sizeof(image_junkbuster_gif_data) - 1;
339 const char image_blank_gif_data[] =
340 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
341 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
342 "\000\001\000\000\002\002D\001\000;";
344 const int image_blank_gif_length = sizeof(image_blank_gif_data) - 1;
347 static struct http_response cgi_error_memory_response[1];
350 static struct http_response *dispatch_known_cgi(struct client_state * csp,
354 /*********************************************************************
356 * Function : dispatch_cgi
358 * Description : Checks if a request URL has either the magical hostname
359 * i.j.b or matches HOME_PAGE_URL/config/. If so, it passes
360 * the (rest of the) path onto dispatch_known_cgi, which
361 * calls the relevant CGI handler function.
364 * 1 : csp = Current client state (buffers, headers, etc...)
366 * Returns : http_response if match, NULL if nonmatch or handler fail
368 *********************************************************************/
369 struct http_response *dispatch_cgi(struct client_state *csp)
371 const char *host = csp->http->host;
372 const char *path = csp->http->path;
375 * Should we intercept ?
378 /* Either the host matches CGI_PREFIX_HOST ..*/
379 if ( (0 == strcmpic(host, CGI_PREFIX_HOST))
380 && (path[0] == '/') )
382 /* ..then the path will all be for us. Remove leading '/' */
385 /* Or it's the host part HOME_PAGE_URL, and the path /config/ */
386 else if ( (0 == strcmpic(host, HOME_PAGE_URL + 7 ))
387 && (0 == strncmpic(path,"/config", 7)) )
389 /* take everything following "/config" */
393 /* skip the forward slash after "/config" */
396 else if (*path != '\0')
398 /* wierdness: URL is /configXXX, where XXX is some string */
409 * This is a CGI call.
412 return dispatch_known_cgi(csp, path);
416 /*********************************************************************
418 * Function : dispatch_known_cgi
420 * Description : Processes a CGI once dispatch_cgi has determined that
421 * it matches one of the magic prefixes. Parses the path
422 * as a cgi name plus query string, prepares a map that
423 * maps CGI parameter names to their values, initializes
424 * the http_response struct, and calls the relevant CGI
428 * 1 : csp = Current client state (buffers, headers, etc...)
429 * 2 : path = Path of CGI, with the CGI prefix removed.
430 * Should not have a leading "/".
432 * Returns : http_response, or NULL on handler failure or out of
435 *********************************************************************/
436 static struct http_response *dispatch_known_cgi(struct client_state * csp,
439 const struct cgi_dispatcher *d;
440 struct map *param_list;
441 struct http_response *rsp;
442 char *query_args_start;
446 if (NULL == (path_copy = strdup(path)))
448 return cgi_error_memory();
451 query_args_start = path_copy;
452 while (*query_args_start && *query_args_start != '?')
456 if (*query_args_start == '?')
458 *query_args_start++ = '\0';
461 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
464 return cgi_error_memory();
470 * path_copy = CGI call name
471 * param_list = CGI params, as map
474 /* Get mem for response or fail*/
475 if (NULL == (rsp = alloc_http_response()))
478 free_map(param_list);
479 return cgi_error_memory();
482 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
483 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
484 csp->ip_addr_str, csp->http->cmd);
486 /* Find and start the right CGI function*/
487 for (d = cgi_dispatchers; FOREVER; d++)
489 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
491 err = (d->handler)(csp, rsp, param_list);
493 free_map(param_list);
494 if (err == JB_ERR_CGI_PARAMS)
496 err = cgi_error_bad_param(csp, rsp);
501 return finish_http_response(rsp);
505 /* Error in handler, probably out-of-memory */
506 free_http_response(rsp);
507 return cgi_error_memory();
514 /*********************************************************************
516 * Function : parse_cgi_parameters
518 * Description : Parse a URL-encoded argument string into name/value
519 * pairs and store them in a struct map list.
522 * 1 : string = string to be parsed. Will be trashed.
524 * Returns : pointer to param list, or NULL if out of memory.
526 *********************************************************************/
527 static struct map *parse_cgi_parameters(char *argstring)
530 char *vector[BUFFER_SIZE];
532 struct map *cgi_params;
534 if (NULL == (cgi_params = new_map()))
539 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
541 for (i = 0; i < pairs; i++)
543 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
546 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
548 free_map(cgi_params);
559 /*********************************************************************
561 * Function : error_response
563 * Description : returns an http_response that explains the reason
564 * why a request failed.
567 * 1 : csp = Current client state (buffers, headers, etc...)
568 * 2 : templatename = Which template should be used for the answer
569 * 3 : sys_err = system error number
571 * Returns : A http_response. If we run out of memory, this
572 * will be cgi_error_memory().
574 *********************************************************************/
575 struct http_response *error_response(struct client_state *csp,
576 const char *templatename,
580 struct http_response *rsp;
581 struct map * exports = default_exports(csp, NULL);
584 return cgi_error_memory();
587 if (NULL == (rsp = alloc_http_response()))
590 return cgi_error_memory();
593 err = map(exports, "host-html", 1, html_encode(csp->http->host), 0)
594 || map(exports, "hostport", 1, csp->http->hostport, 1)
595 || map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0)
596 || map(exports, "path", 1, csp->http->path, 1)
597 || map(exports, "path-html", 1, html_encode(csp->http->path), 0)
598 || map(exports, "error", 1, safe_strerror(sys_err), 0)
599 || map(exports, "host-ip", 1, csp->http->host_ip_addr_str, 1);
604 free_http_response(rsp);
605 return cgi_error_memory();
608 if (!strcmp(templatename, "no-such-domain"))
610 rsp->status = strdup("404 No such domain");
611 if (rsp->status == NULL)
614 free_http_response(rsp);
615 return cgi_error_memory();
618 else if (!strcmp(templatename, "connect-failed"))
620 rsp->status = strdup("503 Connect failed");
621 if (rsp->status == NULL)
624 free_http_response(rsp);
625 return cgi_error_memory();
629 err = template_fill_for_cgi(csp, templatename, exports, rsp);
632 free_http_response(rsp);
633 return cgi_error_memory();
636 return finish_http_response(rsp);
640 /*********************************************************************
642 * Function : cgi_init_error_messages
644 * Description : Call at the start of the program to initialize
645 * the error message used by cgi_error_memory().
651 *********************************************************************/
652 void cgi_init_error_messages(void)
654 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
655 cgi_error_memory_response->head =
656 "HTTP/1.0 500 Internal JunkBuster Proxy Error\r\n"
657 "Content-Type: text/html\r\n"
659 cgi_error_memory_response->body =
661 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
663 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
664 "<p>JunkBuster <b>ran out of memory</b> whilst processing your request.</p>\r\n"
665 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
669 cgi_error_memory_response->head_length =
670 strlen(cgi_error_memory_response->head);
671 cgi_error_memory_response->content_length =
672 strlen(cgi_error_memory_response->body);
676 /*********************************************************************
678 * Function : cgi_error_memory
680 * Description : Called if a CGI function runs out of memory.
681 * Returns a statically-allocated error response.
684 * 1 : csp = Current client state (buffers, headers, etc...)
685 * 2 : rsp = http_response data structure for output
686 * 3 : template_name = Name of template that could not
689 * Returns : JB_ERR_OK on success
690 * JB_ERR_MEMORY on out-of-memory error.
692 *********************************************************************/
693 struct http_response *cgi_error_memory(void)
695 /* assert that it's been initialized. */
696 assert(cgi_error_memory_response->head);
698 return cgi_error_memory_response;
702 /*********************************************************************
704 * Function : cgi_error_no_template
706 * Description : Almost-CGI function that is called if a templae
707 * cannot be loaded. Note this is not a true CGI,
708 * it takes a template name rather than a map of
712 * 1 : csp = Current client state (buffers, headers, etc...)
713 * 2 : rsp = http_response data structure for output
714 * 3 : template_name = Name of template that could not
717 * Returns : JB_ERR_OK on success
718 * JB_ERR_MEMORY on out-of-memory error.
720 *********************************************************************/
721 jb_err cgi_error_no_template(struct client_state *csp,
722 struct http_response *rsp,
723 const char *template_name)
725 static const char status[] =
726 "500 Internal JunkBuster Proxy Error";
727 static const char body_prefix[] =
729 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
731 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
732 "<p>JunkBuster encountered an error whilst processing your request:</p>\r\n"
733 "<p><b>Could not load template file <code>";
734 static const char body_suffix[] =
735 "</code></b></p>\r\n"
736 "<p>Please contact your proxy administrator.</p>\r\n"
737 "<p>If you are the proxy administrator, please put the required file "
738 "in the <code><i>(confdir)</i>/templates</code> directory. The "
739 "location of the <code><i>(confdir)</i></code> directory "
740 "is specified in the main JunkBuster <code>config</code> "
741 "file. (It's typically the JunkBuster install directory"
743 ", or <code>/etc/junkbuster/</code>"
744 #endif /* ndef _WIN32 */
751 assert(template_name);
753 /* Reset rsp, if needed */
757 rsp->content_length = 0;
758 rsp->head_length = 0;
761 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
762 if (rsp->body == NULL)
764 return JB_ERR_MEMORY;
766 strcpy(rsp->body, body_prefix);
767 strcat(rsp->body, template_name);
768 strcat(rsp->body, body_suffix);
770 rsp->status = strdup(status);
771 if (rsp->body == NULL)
773 return JB_ERR_MEMORY;
780 /*********************************************************************
782 * Function : cgi_error_bad_param
784 * Description : CGI function that is called if the parameters
785 * (query string) for a CGI were wrong.
788 * 1 : csp = Current client state (buffers, headers, etc...)
789 * 2 : rsp = http_response data structure for output
791 * CGI Parameters : none
793 * Returns : JB_ERR_OK on success
794 * JB_ERR_MEMORY on out-of-memory error.
796 *********************************************************************/
797 jb_err cgi_error_bad_param(struct client_state *csp,
798 struct http_response *rsp)
805 if (NULL == (exports = default_exports(csp, NULL)))
807 return JB_ERR_MEMORY;
810 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
814 /*********************************************************************
816 * Function : get_http_time
818 * Description : Get the time in a format suitable for use in a
819 * HTTP header - e.g.:
820 * "Sun, 06 Nov 1994 08:49:37 GMT"
823 * 1 : time_offset = Time returned will be current time
824 * plus this number of seconds.
825 * 2 : buf = Destination for result. Must be long enough
826 * to hold 29 characters plus a trailing zero.
830 *********************************************************************/
831 void get_http_time(int time_offset, char *buf)
833 static const char day_names[7][4] =
834 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
835 static const char month_names[12][4] =
836 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
837 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
844 time(¤t_time); /* get current time */
846 current_time += time_offset;
848 /* get and save the gmt */
849 t = gmtime(¤t_time);
851 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
853 "%s, %02d %s %4d %02d:%02d:%02d GMT",
854 day_names[t->tm_wday],
856 month_names[t->tm_mon],
866 /*********************************************************************
868 * Function : finish_http_response
870 * Description : Fill in the missing headers in an http response,
871 * and flatten the headers to an http head.
874 * 1 : rsp = pointer to http_response to be processed
876 * Returns : A http_response, usually the rsp parameter.
877 * On error, free()s rsp and returns cgi_error_memory()
879 *********************************************************************/
880 struct http_response *finish_http_response(struct http_response *rsp)
882 char buf[BUFFER_SIZE];
885 /* Special case - do NOT change this statically allocated response,
886 * which is ready for output anyway.
888 if (rsp == cgi_error_memory_response)
894 * Fill in the HTTP Status
896 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
897 err = enlist_first(rsp->headers, buf);
900 * Set the Content-Length
902 if (rsp->content_length == 0)
904 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
906 sprintf(buf, "Content-Length: %d", rsp->content_length);
907 err = err || enlist(rsp->headers, buf);
910 * Fill in the default headers:
912 * Content-Type: default to text/html if not already specified.
913 * Date: set to current date/time.
914 * Last-Modified: set to date/time the page was last changed.
915 * Expires: set to date/time page next needs reloading.
916 * Cache-Control: set to "no-cache" if applicable.
918 * See http://www.w3.org/Protocols/rfc2068/rfc2068
920 err = err || enlist_unique(rsp->headers, "Content-Type: text/html", 13);
925 * Set Expires to about 10 min into the future so it'll get reloaded
926 * occasionally, e.g. if IJB gets upgraded.
929 get_http_time(0, buf);
930 err = err || enlist_unique_header(rsp->headers, "Date", buf);
932 /* Some date in the past. */
933 err = err || enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
935 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
936 err = err || enlist_unique_header(rsp->headers, "Expires", buf);
941 * Compliant browsers should not cache this due to the "Cache-Control"
942 * setting. However, to be certain, we also set both "Last-Modified"
943 * and "Expires" to the current time.
945 err = err || enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
946 get_http_time(0, buf);
947 err = err || enlist_unique_header(rsp->headers, "Date", buf);
948 err = err || enlist_unique_header(rsp->headers, "Last-Modified", buf);
949 err = err || enlist_unique_header(rsp->headers, "Expires", buf);
956 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
958 free_http_response(rsp);
959 return cgi_error_memory();
961 rsp->head_length = strlen(rsp->head);
968 /*********************************************************************
970 * Function : alloc_http_response
972 * Description : Allocates a new http_response structure.
976 * Returns : pointer to a new http_response, or NULL.
978 *********************************************************************/
979 struct http_response *alloc_http_response(void)
981 return (struct http_response *) zalloc(sizeof(struct http_response));
986 /*********************************************************************
988 * Function : free_http_response
990 * Description : Free the memory occupied by an http_response
991 * and its depandant structures.
994 * 1 : rsp = pointer to http_response to be freed
998 *********************************************************************/
999 void free_http_response(struct http_response *rsp)
1002 * Must special case cgi_error_memory_response, which is never freed.
1004 if (rsp && (rsp != cgi_error_memory_response))
1009 destroy_list(rsp->headers);
1016 /*********************************************************************
1018 * Function : fill_template
1020 * Description : CGI support function that loads a given HTML
1021 * template from the confdir, ignoring comment
1025 * 1 : csp = Current client state (buffers, headers, etc...)
1026 * 2 : template_ptr = Destination for pointer to loaded
1028 * 3 : template = name of the HTML template to be used
1030 * Returns : JB_ERR_OK on success
1031 * JB_ERR_MEMORY on out-of-memory error.
1032 * JB_ERR_FILE if the template file cannot be read
1034 *********************************************************************/
1035 jb_err template_load(struct client_state *csp, char ** template_ptr,
1036 const char *templatename)
1038 char *templates_dir_path;
1042 char buf[BUFFER_SIZE];
1045 assert(template_ptr);
1046 assert(templatename);
1048 *template_ptr = NULL;
1051 * Open template file or fail
1054 templates_dir_path = make_path(csp->config->confdir, "templates");
1055 if (templates_dir_path == NULL)
1057 return JB_ERR_MEMORY;
1060 full_path = make_path(templates_dir_path, templatename);
1061 free(templates_dir_path);
1062 if (full_path == NULL)
1064 return JB_ERR_MEMORY;
1067 file_buffer = strdup("");
1068 if (file_buffer == NULL)
1071 return JB_ERR_MEMORY;
1074 if (NULL == (fp = fopen(full_path, "r")))
1076 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1084 * Read the file, ignoring comments.
1086 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1087 * This is unlikely in practise.
1089 while (fgets(buf, BUFFER_SIZE, fp))
1091 /* skip lines starting with '#' */
1097 if (string_append(&file_buffer, buf))
1100 return JB_ERR_MEMORY;
1105 *template_ptr = file_buffer;
1111 /*********************************************************************
1113 * Function : template_fill
1115 * Description : CGI support function that fills in a pre-loaded
1116 * HTML template by replacing @name@ with value using
1117 * pcrs, for each item in the output map.
1119 * Note that a leading '$' charachter in the export map's
1120 * values will be stripped and toggle on backreference
1124 * 1 : template_ptr = IN: Template to be filled out.
1126 * OUT: Filled out template.
1127 * Caller must free().
1128 * 2 : exports = map with fill in symbol -> name pairs
1130 * Returns : JB_ERR_OK on success
1131 * JB_ERR_MEMORY on out-of-memory error
1133 *********************************************************************/
1134 jb_err template_fill(char **template_ptr, const struct map *exports)
1136 struct map_entry *m;
1138 char buf[BUFFER_SIZE];
1139 char *tmp_out_buffer;
1145 assert(template_ptr);
1146 assert(*template_ptr);
1149 file_buffer = *template_ptr;
1150 size = strlen(file_buffer) + 1;
1153 * Assemble pcrs joblist from exports map
1155 for (m = exports->first; m != NULL; m = m->next)
1157 if (*m->name == '$')
1160 * First character of name is '$', so remove this flag
1161 * character and allow backreferences ($1 etc) in the
1162 * "replace with" text.
1164 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1170 * Treat the "replace with" text as a literal string -
1171 * no quoting needed, no backreferences allowed.
1172 * ("Trivial" ['T'] flag).
1176 /* Enclose name in @@ */
1177 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1181 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1183 /* Make and run job. */
1184 job = pcrs_compile(buf, m->value, flags, &error);
1187 if (error == PCRS_ERR_NOMEM)
1190 *template_ptr = NULL;
1191 return JB_ERR_MEMORY;
1195 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1196 /* Hope it wasn't important and silently ignore the invalid job */
1201 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1204 if (NULL == tmp_out_buffer)
1206 *template_ptr = NULL;
1207 return JB_ERR_MEMORY;
1209 file_buffer = tmp_out_buffer;
1216 *template_ptr = file_buffer;
1221 /*********************************************************************
1223 * Function : template_fill_for_cgi
1225 * Description : CGI support function that loads a HTML template
1226 * and fills it in. Handles file-not-found errors
1227 * by sending a HTML error message. For convenience,
1228 * this function also frees the passed "exports" map.
1231 * 1 : csp = Client state
1232 * 2 : templatename = name of the HTML template to be used
1233 * 3 : exports = map with fill in symbol -> name pairs.
1234 * Will be freed by this function.
1236 * Returns : JB_ERR_OK on success
1237 * JB_ERR_MEMORY on out-of-memory error
1239 *********************************************************************/
1240 jb_err template_fill_for_cgi(struct client_state *csp,
1241 const char *templatename,
1242 struct map *exports,
1243 struct http_response *rsp)
1248 assert(templatename);
1252 err = template_load(csp, &rsp->body, templatename);
1253 if (err == JB_ERR_FILE)
1256 return cgi_error_no_template(csp, rsp, templatename);
1261 return err; /* JB_ERR_MEMORY */
1263 err = template_fill(&rsp->body, exports);
1268 /*********************************************************************
1270 * Function : default_exports
1272 * Description : returns a struct map list that contains exports
1273 * which are common to all CGI functions.
1276 * 1 : csp = Current client state (buffers, headers, etc...)
1277 * 2 : caller = name of CGI who calls us and which should
1278 * be excluded from the generated menu. May be
1280 * Returns : NULL if no memory, else a new map. Caller frees.
1282 *********************************************************************/
1283 struct map *default_exports(const struct client_state *csp, const char *caller)
1287 struct map * exports;
1288 int local_help_exists = 0;
1292 exports = new_map();
1293 if (exports == NULL)
1299 err = map(exports, "version", 1, VERSION, 1)
1300 || map(exports, "my-ip-address", 1, csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown", 1)
1301 || map(exports, "my-hostname", 1, csp->my_hostname ? csp->my_hostname : "unknown", 1)
1302 || map(exports, "homepage", 1, HOME_PAGE_URL, 1)
1303 || map(exports, "default-cgi", 1, HOME_PAGE_URL "/config", 1)
1304 || map(exports, "menu", 1, make_menu(caller), 0)
1305 || map(exports, "code-status", 1, CODE_STATUS, 1);
1307 snprintf(buf, 20, "%d", csp->config->hport);
1308 err = err || map(exports, "my-port", 1, buf, 1);
1310 if(!strcmp(CODE_STATUS, "stable"))
1312 err = err || map_block_killer(exports, "unstable");
1315 if(csp->config->admin_address != NULL)
1317 err = err || map(exports, "admin-address", 1, csp->config->admin_address, 1);
1318 local_help_exists = 1;
1322 err = err || map_block_killer(exports, "have-adminaddr-info");
1325 if(csp->config->proxy_info_url != NULL)
1327 err = err || map(exports, "proxy-info-url", 1, csp->config->proxy_info_url, 1);
1328 local_help_exists = 1;
1332 err = err || map_block_killer(exports, "have-proxy-info");
1335 if (local_help_exists == 0)
1337 err = err || map_block_killer(exports, "have-help-info");
1350 /*********************************************************************
1352 * Function : map_block_killer
1354 * Description : Convenience function.
1355 * Adds a "killer" for the conditional HTML-template
1356 * block <name>, i.e. a substitution of the regex
1357 * "if-<name>-start.*if-<name>-end" to the given
1361 * 1 : exports = map to extend
1362 * 2 : name = name of conditional block
1364 * Returns : JB_ERR_OK on success
1365 * JB_ERR_MEMORY on out-of-memory error.
1367 *********************************************************************/
1368 jb_err map_block_killer(struct map *exports, const char *name)
1370 char buf[1000]; /* Will do, since the names are hardwired */
1374 assert(strlen(name) < 490);
1376 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1377 return map(exports, buf, 1, "", 1);
1381 /*********************************************************************
1383 * Function : map_conditional
1385 * Description : Convenience function.
1386 * Adds an "if-then-else" for the conditional HTML-template
1387 * block <name>, i.e. a substitution of the form:
1394 * The control structure and one of the alternatives
1398 * 1 : exports = map to extend
1399 * 2 : name = name of conditional block
1400 * 3 : choose_first = nonzero for first, zero for second.
1402 * Returns : JB_ERR_OK on success
1403 * JB_ERR_MEMORY on out-of-memory error.
1405 *********************************************************************/
1406 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
1408 char buf[1000]; /* Will do, since the names are hardwired */
1413 assert(strlen(name) < 480);
1415 snprintf(buf, 1000, (choose_first
1416 ? "else-not-%s@.*@endif-%s"
1417 : "if-%s-then@.*@else-not-%s"),
1420 err = map(exports, buf, 1, "", 1);
1426 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1427 return map(exports, buf, 1, "", 1);
1431 /*********************************************************************
1433 * Function : make_menu
1435 * Description : Returns an HTML-formatted menu of the available
1436 * unhidden CGIs, excluding the one given in <self>.
1438 * Parameters : self = name of CGI to leave out, can be NULL
1440 * Returns : menu string
1442 *********************************************************************/
1443 char *make_menu(const char *self)
1445 const struct cgi_dispatcher *d;
1446 char buf[BUFFER_SIZE];
1447 char *result = NULL;
1451 self = "NO-SUCH-CGI!";
1454 /* List available unhidden CGI's and export as "other-cgis" */
1455 for (d = cgi_dispatchers; d->name; d++)
1457 if (d->description && strcmp(d->name, self))
1459 snprintf(buf, BUFFER_SIZE, "<li><a href=%s/config/%s>%s</a></li>\n",
1460 HOME_PAGE_URL, d->name, d->description);
1461 result = strsav(result, buf);
1469 /*********************************************************************
1471 * Function : dump_map
1473 * Description : HTML-dump a map for debugging
1476 * 1 : the_map = map to dump
1478 * Returns : string with HTML
1480 *********************************************************************/
1481 char *dump_map(const struct map *the_map)
1483 struct map_entry *cur_entry = the_map->first;
1486 ret = strsav(ret, "<table>\n");
1490 ret = strsav(ret, "<tr><td><b>");
1491 ret = strsav(ret, cur_entry->name);
1492 ret = strsav(ret, "</b></td><td>");
1493 ret = strsav(ret, cur_entry->value);
1494 ret = strsav(ret, "</td></tr>\n");
1495 cur_entry = cur_entry->next;
1498 ret = strsav(ret, "</table>\n");