1 const char cgi_rcs[] = "$Id: cgi.c,v 1.36 2001/10/26 17:33:27 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.36 2001/10/26 17:33:27 oes
44 * Revision 1.35 2001/10/23 21:48:19 jongfoster
45 * Cleaning up error handling in CGI functions - they now send back
46 * a HTML error page and should never cause a FATAL error. (Fixes one
47 * potential source of "denial of service" attacks).
49 * CGI actions file editor that works and is actually useful.
51 * Ability to toggle JunkBuster remotely using a CGI call.
53 * You can turn off both the above features in the main configuration
54 * file, e.g. if you are running a multi-user proxy.
56 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
57 * Only show "Local support" on templates conditionally:
58 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
59 * - if not, no Local support section appears
61 * Revision 1.33 2001/10/14 22:28:41 jongfoster
64 * Revision 1.32 2001/10/14 22:20:18 jongfoster
65 * - Changes to CGI dispatching method to match CGI names exactly,
66 * rather than doing a prefix match.
67 * - No longer need to count the length of the CGI handler names by hand.
68 * - Adding new handler for 404 error when disptching a CGI, if none of
70 * - Adding new handlers for CGI actionsfile editor.
72 * Revision 1.31 2001/10/10 10:56:39 oes
73 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
75 * Revision 1.30 2001/10/02 15:30:57 oes
76 * Introduced show-request cgi
78 * Revision 1.29 2001/09/20 15:47:44 steudten
80 * Fix BUG: Modify int size to size_t size in fill_template()
81 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
83 * Revision 1.28 2001/09/19 18:00:37 oes
84 * - Deletef time() FIXME (Can't fail under Linux either, if
85 * the argument is guaranteed to be in out address space,
88 * - Pointer notation cosmetics
89 * - Fixed a minor bug in template_fill(): Failiure of
90 * pcrs_execute() now secure.
92 * Revision 1.27 2001/09/16 17:08:54 jongfoster
93 * Moving simple CGI functions from cgi.c to new file cgisimple.c
95 * Revision 1.26 2001/09/16 15:47:37 jongfoster
96 * First version of CGI-based edit interface. This is very much a
97 * work-in-progress, and you can't actually use it to edit anything
98 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
101 * Revision 1.25 2001/09/16 15:02:35 jongfoster
102 * Adding i.j.b/robots.txt.
103 * Inlining add_stats() since it's only ever called from one place.
105 * Revision 1.24 2001/09/16 11:38:01 jongfoster
106 * Splitting fill_template() into 2 functions:
107 * template_load() loads the file
108 * template_fill() performs the PCRS regexps.
109 * This is because the CGI edit interface has a "table row"
110 * template which is used many times in the page - this
111 * change means it's only loaded from disk once.
113 * Revision 1.23 2001/09/16 11:16:05 jongfoster
114 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
116 * Revision 1.22 2001/09/16 11:00:10 jongfoster
117 * New function alloc_http_response, for symmetry with free_http_response
119 * Revision 1.21 2001/09/13 23:53:03 jongfoster
120 * Support for both static and dynamically generated CGI pages.
121 * Correctly setting Last-Modified: and Expires: HTTP headers.
123 * Revision 1.20 2001/09/13 23:40:36 jongfoster
124 * (Cosmetic only) Indentation correction
126 * Revision 1.19 2001/09/13 23:31:25 jongfoster
127 * Moving image data to cgi.c rather than cgi.h.
129 * Revision 1.18 2001/08/05 16:06:20 jongfoster
130 * Modifiying "struct map" so that there are now separate header and
131 * "map_entry" structures. This means that functions which modify a
132 * map no longer need to return a pointer to the modified map.
133 * Also, it no longer reverses the order of the entries (which may be
134 * important with some advanced template substitutions).
136 * Revision 1.17 2001/08/05 15:57:38 oes
137 * Adapted finish_http_response to new list_to_text
139 * Revision 1.16 2001/08/01 21:33:18 jongfoster
140 * Changes to fill_template() that reduce memory usage without having
141 * an impact on performance. I also renamed some variables so as not
142 * to clash with the C++ keywords "new" and "template".
144 * Revision 1.15 2001/08/01 21:19:22 jongfoster
145 * Moving file version information to a separate CGI page.
147 * Revision 1.14 2001/08/01 00:19:03 jongfoster
148 * New function: map_conditional() for an if-then-else syntax.
149 * Changing to use new version of show_defines()
151 * Revision 1.13 2001/07/30 22:08:36 jongfoster
152 * Tidying up #defines:
153 * - All feature #defines are now of the form FEATURE_xxx
154 * - Permanently turned off WIN_GUI_EDIT
155 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
157 * Revision 1.12 2001/07/29 18:47:05 jongfoster
158 * Adding missing #include "loadcfg.h"
160 * Revision 1.11 2001/07/18 17:24:37 oes
161 * Changed to conform to new pcrs interface
163 * Revision 1.10 2001/07/13 13:53:13 oes
164 * Removed all #ifdef PCRS and related code
166 * Revision 1.9 2001/06/29 21:45:41 oes
167 * Indentation, CRLF->LF, Tab-> Space
169 * Revision 1.8 2001/06/29 13:21:46 oes
170 * - Cosmetics: renamed and reordered functions, variables,
171 * texts, improved comments etc
173 * - Removed ij_untrusted_url() The relevant
174 * info is now part of the "untrusted" page,
175 * which is generated by filters.c:trust_url()
177 * - Generators of content now call finish_http_response()
178 * themselves, making jcc.c:chat() a little less
181 * - Removed obsolete "Pragma: no-cache" from our headers
183 * - http_responses now know their head length
185 * - fill_template now uses the new interface to pcrs, so that
186 * - long jobs (like whole files) no longer have to be assembled
187 * in a fixed size buffer
188 * - the new T (trivial) option is used, and the replacement may
189 * contain Perl syntax backrefs without confusing pcrs
191 * - Introduced default_exports() which generates a set of exports
192 * common to all CGIs and other content generators
194 * - Introduced convenience function map_block_killer()
196 * - Introduced convenience function make_menu()
198 * - Introduced CGI-like function error_response() which generates
199 * the "No such domain" and "Connect failed" messages using the
202 * - cgi_show_url_info:
203 * - adapted to new CGI features
204 * - form and answers now generated from same template
205 * - http:// prefix in URL now OK
208 * - adapted to new CGI features
209 * - no longer uses csp->init_proxy_args
212 * - moved menu generation to make_menu()
214 * - add_stats now writes single export map entries instead
217 * - Moved redirect_url() to filters.c
219 * - Fixed mem leak in free_http_response(), map_block_killer(),
221 * - Removed logentry from cancelled commit
223 * Revision 1.7 2001/06/09 10:51:58 jongfoster
224 * Changing "show URL info" handler to new style.
225 * Changing BUFSIZ ==> BUFFER_SIZE
227 * Revision 1.6 2001/06/07 23:05:19 jongfoster
228 * Removing code related to old forward and ACL files.
230 * Revision 1.5 2001/06/05 19:59:16 jongfoster
231 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
233 * Revision 1.4 2001/06/04 10:41:52 swa
234 * show version string of cgi.h and cgi.c
236 * Revision 1.3 2001/06/03 19:12:16 oes
237 * introduced new cgi handling
239 * No revisions before 1.3
241 **********************************************************************/
247 #include <sys/types.h>
254 #define snprintf _snprintf
255 #endif /* def _WIN32 */
263 #include "miscutil.h"
264 #include "cgisimple.h"
265 #ifdef FEATURE_CGI_EDIT_ACTIONS
267 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
269 /* loadcfg.h is for g_bToggleIJB only */
271 const char cgi_h_rcs[] = CGI_H_VERSION;
273 static const struct cgi_dispatcher cgi_dispatchers[] = {
276 "Junkbuster main page" },
279 "Show information about the current configuration" },
282 "Show the source code version numbers" },
285 "Show the client's request headers." },
288 "Show which actions apply to a URL and why" },
291 "Toggle JunkBuster on or off" },
292 #ifdef FEATURE_CGI_EDIT_ACTIONS
295 "Edit the actions list" },
296 { "edit-actions-for-url",
297 cgi_edit_actions_for_url,
298 NULL /* Edit the actions for (a) specified URL(s) */ },
299 { "edit-actions-list",
300 cgi_edit_actions_list,
301 NULL /* Edit the actions list */ },
302 { "edit-actions-submit",
303 cgi_edit_actions_submit,
304 NULL /* Change the actions for (a) specified URL(s) */ },
305 { "edit-actions-url",
306 cgi_edit_actions_url,
307 NULL /* Change a URL pattern in the actionsfile */ },
308 { "edit-actions-add-url",
309 cgi_edit_actions_add_url,
310 NULL /* Add a URL pattern to the actionsfile */ },
311 { "edit-actions-remove-url",
312 cgi_edit_actions_remove_url,
313 NULL /* Add a URL pattern to the actionsfile */ },
314 { "edit-actions-section-remove",
315 cgi_edit_actions_section_remove,
316 NULL /* Remove a section from the actionsfile */ },
317 { "edit-actions-section-add",
318 cgi_edit_actions_section_add,
319 NULL /* Remove a section from the actionsfile */ },
320 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
323 NULL /* Sends a robots.txt file to tell robots to go away. */ },
326 NULL /* Send the transparent or \"Junkbuster\" gif */ },
327 { NULL, /* NULL Indicates end of list and default page */
329 NULL /* Unknown CGI page */ }
336 * Hint: You can encode your own GIFs like this:
337 * perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o,", unpack("C", $c)); }'
340 const char image_junkbuster_gif_data[] =
341 "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
342 "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
343 "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
344 "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
345 "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
346 "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
347 "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
350 const int image_junkbuster_gif_length = sizeof(image_junkbuster_gif_data) - 1;
353 const char image_blank_gif_data[] =
354 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
355 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
356 "\000\001\000\000\002\002D\001\000;";
358 const int image_blank_gif_length = sizeof(image_blank_gif_data) - 1;
361 static struct http_response cgi_error_memory_response[1];
364 static struct http_response *dispatch_known_cgi(struct client_state * csp,
368 /*********************************************************************
370 * Function : dispatch_cgi
372 * Description : Checks if a request URL has either the magical hostname
373 * i.j.b or matches HOME_PAGE_URL/config/. If so, it passes
374 * the (rest of the) path onto dispatch_known_cgi, which
375 * calls the relevant CGI handler function.
378 * 1 : csp = Current client state (buffers, headers, etc...)
380 * Returns : http_response if match, NULL if nonmatch or handler fail
382 *********************************************************************/
383 struct http_response *dispatch_cgi(struct client_state *csp)
385 const char *host = csp->http->host;
386 const char *path = csp->http->path;
389 * Should we intercept ?
392 /* Either the host matches CGI_PREFIX_HOST ..*/
393 if ( (0 == strcmpic(host, CGI_PREFIX_HOST))
394 && (path[0] == '/') )
396 /* ..then the path will all be for us. Remove leading '/' */
399 /* Or it's the host part HOME_PAGE_URL, and the path /config/ */
400 else if ( (0 == strcmpic(host, HOME_PAGE_URL + 7 ))
401 && (0 == strncmpic(path,"/config", 7)) )
403 /* take everything following "/config" */
407 /* skip the forward slash after "/config" */
410 else if (*path != '\0')
412 /* wierdness: URL is /configXXX, where XXX is some string */
423 * This is a CGI call.
426 return dispatch_known_cgi(csp, path);
430 /*********************************************************************
432 * Function : dispatch_known_cgi
434 * Description : Processes a CGI once dispatch_cgi has determined that
435 * it matches one of the magic prefixes. Parses the path
436 * as a cgi name plus query string, prepares a map that
437 * maps CGI parameter names to their values, initializes
438 * the http_response struct, and calls the relevant CGI
442 * 1 : csp = Current client state (buffers, headers, etc...)
443 * 2 : path = Path of CGI, with the CGI prefix removed.
444 * Should not have a leading "/".
446 * Returns : http_response, or NULL on handler failure or out of
449 *********************************************************************/
450 static struct http_response *dispatch_known_cgi(struct client_state * csp,
453 const struct cgi_dispatcher *d;
454 struct map *param_list;
455 struct http_response *rsp;
456 char *query_args_start;
460 if (NULL == (path_copy = strdup(path)))
462 return cgi_error_memory();
465 query_args_start = path_copy;
466 while (*query_args_start && *query_args_start != '?')
470 if (*query_args_start == '?')
472 *query_args_start++ = '\0';
475 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
478 return cgi_error_memory();
484 * path_copy = CGI call name
485 * param_list = CGI params, as map
488 /* Get mem for response or fail*/
489 if (NULL == (rsp = alloc_http_response()))
492 free_map(param_list);
493 return cgi_error_memory();
496 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
497 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
498 csp->ip_addr_str, csp->http->cmd);
500 /* Find and start the right CGI function*/
501 for (d = cgi_dispatchers; FOREVER; d++)
503 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
505 err = (d->handler)(csp, rsp, param_list);
507 free_map(param_list);
508 if (err == JB_ERR_CGI_PARAMS)
510 err = cgi_error_bad_param(csp, rsp);
515 return finish_http_response(rsp);
519 /* Error in handler, probably out-of-memory */
520 free_http_response(rsp);
521 return cgi_error_memory();
528 /*********************************************************************
530 * Function : parse_cgi_parameters
532 * Description : Parse a URL-encoded argument string into name/value
533 * pairs and store them in a struct map list.
536 * 1 : string = string to be parsed. Will be trashed.
538 * Returns : pointer to param list, or NULL if out of memory.
540 *********************************************************************/
541 static struct map *parse_cgi_parameters(char *argstring)
544 char *vector[BUFFER_SIZE];
546 struct map *cgi_params;
548 if (NULL == (cgi_params = new_map()))
553 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
555 for (i = 0; i < pairs; i++)
557 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
560 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
562 free_map(cgi_params);
573 /*********************************************************************
575 * Function : error_response
577 * Description : returns an http_response that explains the reason
578 * why a request failed.
581 * 1 : csp = Current client state (buffers, headers, etc...)
582 * 2 : templatename = Which template should be used for the answer
583 * 3 : sys_err = system error number
585 * Returns : A http_response. If we run out of memory, this
586 * will be cgi_error_memory().
588 *********************************************************************/
589 struct http_response *error_response(struct client_state *csp,
590 const char *templatename,
594 struct http_response *rsp;
595 struct map * exports = default_exports(csp, NULL);
598 return cgi_error_memory();
601 if (NULL == (rsp = alloc_http_response()))
604 return cgi_error_memory();
607 err = map(exports, "host-html", 1, html_encode(csp->http->host), 0)
608 || map(exports, "hostport", 1, csp->http->hostport, 1)
609 || map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0)
610 || map(exports, "path", 1, csp->http->path, 1)
611 || map(exports, "path-html", 1, html_encode(csp->http->path), 0)
612 || map(exports, "error", 1, safe_strerror(sys_err), 0)
613 || map(exports, "host-ip", 1, csp->http->host_ip_addr_str, 1);
618 free_http_response(rsp);
619 return cgi_error_memory();
622 if (!strcmp(templatename, "no-such-domain"))
624 rsp->status = strdup("404 No such domain");
625 if (rsp->status == NULL)
628 free_http_response(rsp);
629 return cgi_error_memory();
632 else if (!strcmp(templatename, "connect-failed"))
634 rsp->status = strdup("503 Connect failed");
635 if (rsp->status == NULL)
638 free_http_response(rsp);
639 return cgi_error_memory();
643 err = template_fill_for_cgi(csp, templatename, exports, rsp);
646 free_http_response(rsp);
647 return cgi_error_memory();
650 return finish_http_response(rsp);
654 /*********************************************************************
656 * Function : cgi_init_error_messages
658 * Description : Call at the start of the program to initialize
659 * the error message used by cgi_error_memory().
665 *********************************************************************/
666 void cgi_init_error_messages(void)
668 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
669 cgi_error_memory_response->head =
670 "HTTP/1.0 500 Internal JunkBuster Proxy Error\r\n"
671 "Content-Type: text/html\r\n"
673 cgi_error_memory_response->body =
675 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
677 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
678 "<p>JunkBuster <b>ran out of memory</b> whilst processing your request.</p>\r\n"
679 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
683 cgi_error_memory_response->head_length =
684 strlen(cgi_error_memory_response->head);
685 cgi_error_memory_response->content_length =
686 strlen(cgi_error_memory_response->body);
690 /*********************************************************************
692 * Function : cgi_error_memory
694 * Description : Called if a CGI function runs out of memory.
695 * Returns a statically-allocated error response.
698 * 1 : csp = Current client state (buffers, headers, etc...)
699 * 2 : rsp = http_response data structure for output
700 * 3 : template_name = Name of template that could not
703 * Returns : JB_ERR_OK on success
704 * JB_ERR_MEMORY on out-of-memory error.
706 *********************************************************************/
707 struct http_response *cgi_error_memory(void)
709 /* assert that it's been initialized. */
710 assert(cgi_error_memory_response->head);
712 return cgi_error_memory_response;
716 /*********************************************************************
718 * Function : cgi_error_no_template
720 * Description : Almost-CGI function that is called if a templae
721 * cannot be loaded. Note this is not a true CGI,
722 * it takes a template name rather than a map of
726 * 1 : csp = Current client state (buffers, headers, etc...)
727 * 2 : rsp = http_response data structure for output
728 * 3 : template_name = Name of template that could not
731 * Returns : JB_ERR_OK on success
732 * JB_ERR_MEMORY on out-of-memory error.
734 *********************************************************************/
735 jb_err cgi_error_no_template(struct client_state *csp,
736 struct http_response *rsp,
737 const char *template_name)
739 static const char status[] =
740 "500 Internal JunkBuster Proxy Error";
741 static const char body_prefix[] =
743 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
745 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
746 "<p>JunkBuster encountered an error whilst processing your request:</p>\r\n"
747 "<p><b>Could not load template file <code>";
748 static const char body_suffix[] =
749 "</code></b></p>\r\n"
750 "<p>Please contact your proxy administrator.</p>\r\n"
751 "<p>If you are the proxy administrator, please put the required file "
752 "in the <code><i>(confdir)</i>/templates</code> directory. The "
753 "location of the <code><i>(confdir)</i></code> directory "
754 "is specified in the main JunkBuster <code>config</code> "
755 "file. (It's typically the JunkBuster install directory"
757 ", or <code>/etc/junkbuster/</code>"
758 #endif /* ndef _WIN32 */
765 assert(template_name);
767 /* Reset rsp, if needed */
771 rsp->content_length = 0;
772 rsp->head_length = 0;
775 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
776 if (rsp->body == NULL)
778 return JB_ERR_MEMORY;
780 strcpy(rsp->body, body_prefix);
781 strcat(rsp->body, template_name);
782 strcat(rsp->body, body_suffix);
784 rsp->status = strdup(status);
785 if (rsp->body == NULL)
787 return JB_ERR_MEMORY;
794 /*********************************************************************
796 * Function : cgi_error_bad_param
798 * Description : CGI function that is called if the parameters
799 * (query string) for a CGI were wrong.
802 * 1 : csp = Current client state (buffers, headers, etc...)
803 * 2 : rsp = http_response data structure for output
805 * CGI Parameters : none
807 * Returns : JB_ERR_OK on success
808 * JB_ERR_MEMORY on out-of-memory error.
810 *********************************************************************/
811 jb_err cgi_error_bad_param(struct client_state *csp,
812 struct http_response *rsp)
819 if (NULL == (exports = default_exports(csp, NULL)))
821 return JB_ERR_MEMORY;
824 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
828 /*********************************************************************
830 * Function : get_http_time
832 * Description : Get the time in a format suitable for use in a
833 * HTTP header - e.g.:
834 * "Sun, 06 Nov 1994 08:49:37 GMT"
837 * 1 : time_offset = Time returned will be current time
838 * plus this number of seconds.
839 * 2 : buf = Destination for result. Must be long enough
840 * to hold 29 characters plus a trailing zero.
844 *********************************************************************/
845 void get_http_time(int time_offset, char *buf)
847 static const char day_names[7][4] =
848 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
849 static const char month_names[12][4] =
850 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
851 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
858 time(¤t_time); /* get current time */
860 current_time += time_offset;
862 /* get and save the gmt */
863 t = gmtime(¤t_time);
865 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
867 "%s, %02d %s %4d %02d:%02d:%02d GMT",
868 day_names[t->tm_wday],
870 month_names[t->tm_mon],
880 /*********************************************************************
882 * Function : finish_http_response
884 * Description : Fill in the missing headers in an http response,
885 * and flatten the headers to an http head.
888 * 1 : rsp = pointer to http_response to be processed
890 * Returns : A http_response, usually the rsp parameter.
891 * On error, free()s rsp and returns cgi_error_memory()
893 *********************************************************************/
894 struct http_response *finish_http_response(struct http_response *rsp)
896 char buf[BUFFER_SIZE];
899 /* Special case - do NOT change this statically allocated response,
900 * which is ready for output anyway.
902 if (rsp == cgi_error_memory_response)
908 * Fill in the HTTP Status
910 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
911 err = enlist_first(rsp->headers, buf);
914 * Set the Content-Length
916 if (rsp->content_length == 0)
918 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
920 sprintf(buf, "Content-Length: %d", rsp->content_length);
921 err = err || enlist(rsp->headers, buf);
924 * Fill in the default headers:
926 * Content-Type: default to text/html if not already specified.
927 * Date: set to current date/time.
928 * Last-Modified: set to date/time the page was last changed.
929 * Expires: set to date/time page next needs reloading.
930 * Cache-Control: set to "no-cache" if applicable.
932 * See http://www.w3.org/Protocols/rfc2068/rfc2068
934 err = err || enlist_unique(rsp->headers, "Content-Type: text/html", 13);
939 * Set Expires to about 10 min into the future so it'll get reloaded
940 * occasionally, e.g. if IJB gets upgraded.
943 get_http_time(0, buf);
944 err = err || enlist_unique_header(rsp->headers, "Date", buf);
946 /* Some date in the past. */
947 err = err || enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
949 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
950 err = err || enlist_unique_header(rsp->headers, "Expires", buf);
955 * Compliant browsers should not cache this due to the "Cache-Control"
956 * setting. However, to be certain, we also set both "Last-Modified"
957 * and "Expires" to the current time.
959 err = err || enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
960 get_http_time(0, buf);
961 err = err || enlist_unique_header(rsp->headers, "Date", buf);
962 err = err || enlist_unique_header(rsp->headers, "Last-Modified", buf);
963 err = err || enlist_unique_header(rsp->headers, "Expires", buf);
970 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
972 free_http_response(rsp);
973 return cgi_error_memory();
975 rsp->head_length = strlen(rsp->head);
982 /*********************************************************************
984 * Function : alloc_http_response
986 * Description : Allocates a new http_response structure.
990 * Returns : pointer to a new http_response, or NULL.
992 *********************************************************************/
993 struct http_response *alloc_http_response(void)
995 return (struct http_response *) zalloc(sizeof(struct http_response));
1000 /*********************************************************************
1002 * Function : free_http_response
1004 * Description : Free the memory occupied by an http_response
1005 * and its depandant structures.
1008 * 1 : rsp = pointer to http_response to be freed
1012 *********************************************************************/
1013 void free_http_response(struct http_response *rsp)
1016 * Must special case cgi_error_memory_response, which is never freed.
1018 if (rsp && (rsp != cgi_error_memory_response))
1023 destroy_list(rsp->headers);
1030 /*********************************************************************
1032 * Function : template_load
1034 * Description : CGI support function that loads a given HTML
1035 * template from the confdir, ignoring comment
1039 * 1 : csp = Current client state (buffers, headers, etc...)
1040 * 2 : template_ptr = Destination for pointer to loaded
1042 * 3 : template = name of the HTML template to be used
1044 * Returns : JB_ERR_OK on success
1045 * JB_ERR_MEMORY on out-of-memory error.
1046 * JB_ERR_FILE if the template file cannot be read
1048 *********************************************************************/
1049 jb_err template_load(struct client_state *csp, char ** template_ptr,
1050 const char *templatename)
1052 char *templates_dir_path;
1056 char buf[BUFFER_SIZE];
1059 assert(template_ptr);
1060 assert(templatename);
1062 *template_ptr = NULL;
1065 * Open template file or fail
1068 templates_dir_path = make_path(csp->config->confdir, "templates");
1069 if (templates_dir_path == NULL)
1071 return JB_ERR_MEMORY;
1074 full_path = make_path(templates_dir_path, templatename);
1075 free(templates_dir_path);
1076 if (full_path == NULL)
1078 return JB_ERR_MEMORY;
1081 file_buffer = strdup("");
1082 if (file_buffer == NULL)
1085 return JB_ERR_MEMORY;
1088 if (NULL == (fp = fopen(full_path, "r")))
1090 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1098 * Read the file, ignoring comments.
1100 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1101 * This is unlikely in practise.
1103 while (fgets(buf, BUFFER_SIZE, fp))
1105 /* skip lines starting with '#' */
1111 if (string_append(&file_buffer, buf))
1114 return JB_ERR_MEMORY;
1119 *template_ptr = file_buffer;
1125 /*********************************************************************
1127 * Function : template_fill
1129 * Description : CGI support function that fills in a pre-loaded
1130 * HTML template by replacing @name@ with value using
1131 * pcrs, for each item in the output map.
1133 * Note that a leading '$' charachter in the export map's
1134 * values will be stripped and toggle on backreference
1138 * 1 : template_ptr = IN: Template to be filled out.
1140 * OUT: Filled out template.
1141 * Caller must free().
1142 * 2 : exports = map with fill in symbol -> name pairs
1144 * Returns : JB_ERR_OK on success
1145 * JB_ERR_MEMORY on out-of-memory error
1147 *********************************************************************/
1148 jb_err template_fill(char **template_ptr, const struct map *exports)
1150 struct map_entry *m;
1152 char buf[BUFFER_SIZE];
1153 char *tmp_out_buffer;
1159 assert(template_ptr);
1160 assert(*template_ptr);
1163 file_buffer = *template_ptr;
1164 size = strlen(file_buffer) + 1;
1167 * Assemble pcrs joblist from exports map
1169 for (m = exports->first; m != NULL; m = m->next)
1171 if (*m->name == '$')
1174 * First character of name is '$', so remove this flag
1175 * character and allow backreferences ($1 etc) in the
1176 * "replace with" text.
1178 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1184 * Treat the "replace with" text as a literal string -
1185 * no quoting needed, no backreferences allowed.
1186 * ("Trivial" ['T'] flag).
1190 /* Enclose name in @@ */
1191 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1195 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1197 /* Make and run job. */
1198 job = pcrs_compile(buf, m->value, flags, &error);
1201 if (error == PCRS_ERR_NOMEM)
1204 *template_ptr = NULL;
1205 return JB_ERR_MEMORY;
1209 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1210 /* Hope it wasn't important and silently ignore the invalid job */
1215 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1218 if (NULL == tmp_out_buffer)
1220 *template_ptr = NULL;
1221 return JB_ERR_MEMORY;
1223 file_buffer = tmp_out_buffer;
1230 *template_ptr = file_buffer;
1235 /*********************************************************************
1237 * Function : template_fill_for_cgi
1239 * Description : CGI support function that loads a HTML template
1240 * and fills it in. Handles file-not-found errors
1241 * by sending a HTML error message. For convenience,
1242 * this function also frees the passed "exports" map.
1245 * 1 : csp = Client state
1246 * 2 : templatename = name of the HTML template to be used
1247 * 3 : exports = map with fill in symbol -> name pairs.
1248 * Will be freed by this function.
1250 * Returns : JB_ERR_OK on success
1251 * JB_ERR_MEMORY on out-of-memory error
1253 *********************************************************************/
1254 jb_err template_fill_for_cgi(struct client_state *csp,
1255 const char *templatename,
1256 struct map *exports,
1257 struct http_response *rsp)
1262 assert(templatename);
1266 err = template_load(csp, &rsp->body, templatename);
1267 if (err == JB_ERR_FILE)
1270 return cgi_error_no_template(csp, rsp, templatename);
1275 return err; /* JB_ERR_MEMORY */
1277 err = template_fill(&rsp->body, exports);
1283 /*********************************************************************
1285 * Function : default_exports
1287 * Description : returns a struct map list that contains exports
1288 * which are common to all CGI functions.
1291 * 1 : csp = Current client state (buffers, headers, etc...)
1292 * 2 : caller = name of CGI who calls us and which should
1293 * be excluded from the generated menu. May be
1295 * Returns : NULL if no memory, else a new map. Caller frees.
1297 *********************************************************************/
1298 struct map *default_exports(const struct client_state *csp, const char *caller)
1302 struct map * exports;
1303 int local_help_exists = 0;
1307 exports = new_map();
1308 if (exports == NULL)
1313 err = map(exports, "version", 1, VERSION, 1)
1314 || map(exports, "my-ip-address", 1, csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown", 1)
1315 || map(exports, "my-hostname", 1, csp->my_hostname ? csp->my_hostname : "unknown", 1)
1316 || map(exports, "homepage", 1, HOME_PAGE_URL, 1)
1317 || map(exports, "default-cgi", 1, HOME_PAGE_URL "/config", 1)
1318 || map(exports, "menu", 1, make_menu(caller), 0)
1319 || map(exports, "code-status", 1, CODE_STATUS, 1);
1321 err = err || map_conditional(exports, "enabled-display", g_bToggleIJB);
1323 snprintf(buf, 20, "%d", csp->config->hport);
1324 err = err || map(exports, "my-port", 1, buf, 1);
1326 if(!strcmp(CODE_STATUS, "stable"))
1328 err = err || map_block_killer(exports, "unstable");
1331 if(csp->config->admin_address != NULL)
1333 err = err || map(exports, "admin-address", 1, csp->config->admin_address, 1);
1334 local_help_exists = 1;
1338 err = err || map_block_killer(exports, "have-adminaddr-info");
1341 if(csp->config->proxy_info_url != NULL)
1343 err = err || map(exports, "proxy-info-url", 1, csp->config->proxy_info_url, 1);
1344 local_help_exists = 1;
1348 err = err || map_block_killer(exports, "have-proxy-info");
1351 if (local_help_exists == 0)
1353 err = err || map_block_killer(exports, "have-help-info");
1366 /*********************************************************************
1368 * Function : map_block_killer
1370 * Description : Convenience function.
1371 * Adds a "killer" for the conditional HTML-template
1372 * block <name>, i.e. a substitution of the regex
1373 * "if-<name>-start.*if-<name>-end" to the given
1377 * 1 : exports = map to extend
1378 * 2 : name = name of conditional block
1380 * Returns : JB_ERR_OK on success
1381 * JB_ERR_MEMORY on out-of-memory error.
1383 *********************************************************************/
1384 jb_err map_block_killer(struct map *exports, const char *name)
1386 char buf[1000]; /* Will do, since the names are hardwired */
1390 assert(strlen(name) < 490);
1392 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1393 return map(exports, buf, 1, "", 1);
1397 /*********************************************************************
1399 * Function : map_conditional
1401 * Description : Convenience function.
1402 * Adds an "if-then-else" for the conditional HTML-template
1403 * block <name>, i.e. a substitution of the form:
1410 * The control structure and one of the alternatives
1414 * 1 : exports = map to extend
1415 * 2 : name = name of conditional block
1416 * 3 : choose_first = nonzero for first, zero for second.
1418 * Returns : JB_ERR_OK on success
1419 * JB_ERR_MEMORY on out-of-memory error.
1421 *********************************************************************/
1422 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
1424 char buf[1000]; /* Will do, since the names are hardwired */
1429 assert(strlen(name) < 480);
1431 snprintf(buf, 1000, (choose_first
1432 ? "else-not-%s@.*@endif-%s"
1433 : "if-%s-then@.*@else-not-%s"),
1436 err = map(exports, buf, 1, "", 1);
1442 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1443 return map(exports, buf, 1, "", 1);
1447 /*********************************************************************
1449 * Function : make_menu
1451 * Description : Returns an HTML-formatted menu of the available
1452 * unhidden CGIs, excluding the one given in <self>.
1454 * Parameters : self = name of CGI to leave out, can be NULL
1456 * Returns : menu string
1458 *********************************************************************/
1459 char *make_menu(const char *self)
1461 const struct cgi_dispatcher *d;
1462 char buf[BUFFER_SIZE];
1463 char *result = NULL;
1467 self = "NO-SUCH-CGI!";
1470 /* List available unhidden CGI's and export as "other-cgis" */
1471 for (d = cgi_dispatchers; d->name; d++)
1473 if (d->description && strcmp(d->name, self))
1475 snprintf(buf, BUFFER_SIZE, "<li><a href=%s/config/%s>%s</a></li>\n",
1476 HOME_PAGE_URL, d->name, d->description);
1477 result = strsav(result, buf);
1485 /*********************************************************************
1487 * Function : dump_map
1489 * Description : HTML-dump a map for debugging
1492 * 1 : the_map = map to dump
1494 * Returns : string with HTML
1496 *********************************************************************/
1497 char *dump_map(const struct map *the_map)
1499 struct map_entry *cur_entry = the_map->first;
1502 ret = strsav(ret, "<table>\n");
1506 ret = strsav(ret, "<tr><td><b>");
1507 ret = strsav(ret, cur_entry->name);
1508 ret = strsav(ret, "</b></td><td>");
1509 ret = strsav(ret, cur_entry->value);
1510 ret = strsav(ret, "</td></tr>\n");
1511 cur_entry = cur_entry->next;
1514 ret = strsav(ret, "</table>\n");