1 const char cgi_rcs[] = "$Id: cgi.c,v 1.24 2001/09/16 11:38:01 jongfoster Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/cgi.c,v $
6 * Purpose : Declares functions to intercept request, generate
7 * html or gif answers, and to compose HTTP resonses.
9 * Functions declared include:
12 * Copyright : Written by and Copyright (C) 2001 the SourceForge
13 * IJBSWA team. http://ijbswa.sourceforge.net
15 * Based on the Internet Junkbuster originally written
16 * by and Copyright (C) 1997 Anonymous Coders and
17 * Junkbusters Corporation. http://www.junkbusters.com
19 * This program is free software; you can redistribute it
20 * and/or modify it under the terms of the GNU General
21 * Public License as published by the Free Software
22 * Foundation; either version 2 of the License, or (at
23 * your option) any later version.
25 * This program is distributed in the hope that it will
26 * be useful, but WITHOUT ANY WARRANTY; without even the
27 * implied warranty of MERCHANTABILITY or FITNESS FOR A
28 * PARTICULAR PURPOSE. See the GNU General Public
29 * License for more details.
31 * The GNU General Public License should be included with
32 * this file. If not, you can view it at
33 * http://www.gnu.org/copyleft/gpl.html
34 * or write to the Free Software Foundation, Inc., 59
35 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
39 * Revision 1.24 2001/09/16 11:38:01 jongfoster
40 * Splitting fill_template() into 2 functions:
41 * template_load() loads the file
42 * template_fill() performs the PCRS regexps.
43 * This is because the CGI edit interface has a "table row"
44 * template which is used many times in the page - this
45 * change means it's only loaded from disk once.
47 * Revision 1.23 2001/09/16 11:16:05 jongfoster
48 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
50 * Revision 1.22 2001/09/16 11:00:10 jongfoster
51 * New function alloc_http_response, for symmetry with free_http_response
53 * Revision 1.21 2001/09/13 23:53:03 jongfoster
54 * Support for both static and dynamically generated CGI pages.
55 * Correctly setting Last-Modified: and Expires: HTTP headers.
57 * Revision 1.20 2001/09/13 23:40:36 jongfoster
58 * (Cosmetic only) Indentation correction
60 * Revision 1.19 2001/09/13 23:31:25 jongfoster
61 * Moving image data to cgi.c rather than cgi.h.
63 * Revision 1.18 2001/08/05 16:06:20 jongfoster
64 * Modifiying "struct map" so that there are now separate header and
65 * "map_entry" structures. This means that functions which modify a
66 * map no longer need to return a pointer to the modified map.
67 * Also, it no longer reverses the order of the entries (which may be
68 * important with some advanced template substitutions).
70 * Revision 1.17 2001/08/05 15:57:38 oes
71 * Adapted finish_http_response to new list_to_text
73 * Revision 1.16 2001/08/01 21:33:18 jongfoster
74 * Changes to fill_template() that reduce memory usage without having
75 * an impact on performance. I also renamed some variables so as not
76 * to clash with the C++ keywords "new" and "template".
78 * Revision 1.15 2001/08/01 21:19:22 jongfoster
79 * Moving file version information to a separate CGI page.
81 * Revision 1.14 2001/08/01 00:19:03 jongfoster
82 * New function: map_conditional() for an if-then-else syntax.
83 * Changing to use new version of show_defines()
85 * Revision 1.13 2001/07/30 22:08:36 jongfoster
86 * Tidying up #defines:
87 * - All feature #defines are now of the form FEATURE_xxx
88 * - Permanently turned off WIN_GUI_EDIT
89 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
91 * Revision 1.12 2001/07/29 18:47:05 jongfoster
92 * Adding missing #include "loadcfg.h"
94 * Revision 1.11 2001/07/18 17:24:37 oes
95 * Changed to conform to new pcrs interface
97 * Revision 1.10 2001/07/13 13:53:13 oes
98 * Removed all #ifdef PCRS and related code
100 * Revision 1.9 2001/06/29 21:45:41 oes
101 * Indentation, CRLF->LF, Tab-> Space
103 * Revision 1.8 2001/06/29 13:21:46 oes
104 * - Cosmetics: renamed and reordered functions, variables,
105 * texts, improved comments etc
107 * - Removed ij_untrusted_url() The relevant
108 * info is now part of the "untrusted" page,
109 * which is generated by filters.c:trust_url()
111 * - Generators of content now call finish_http_response()
112 * themselves, making jcc.c:chat() a little less
115 * - Removed obsolete "Pragma: no-cache" from our headers
117 * - http_responses now know their head length
119 * - fill_template now uses the new interface to pcrs, so that
120 * - long jobs (like whole files) no longer have to be assembled
121 * in a fixed size buffer
122 * - the new T (trivial) option is used, and the replacement may
123 * contain Perl syntax backrefs without confusing pcrs
125 * - Introduced default_exports() which generates a set of exports
126 * common to all CGIs and other content generators
128 * - Introduced convenience function map_block_killer()
130 * - Introduced convenience function make_menu()
132 * - Introduced CGI-like function error_response() which generates
133 * the "No such domain" and "Connect failed" messages using the
136 * - cgi_show_url_info:
137 * - adapted to new CGI features
138 * - form and answers now generated from same template
139 * - http:// prefix in URL now OK
142 * - adapted to new CGI features
143 * - no longer uses csp->init_proxy_args
146 * - moved menu generation to make_menu()
148 * - add_stats now writes single export map entries instead
151 * - Moved redirect_url() to filters.c
153 * - Fixed mem leak in free_http_response(), map_block_killer(),
155 * - Removed logentry from cancelled commit
157 * Revision 1.7 2001/06/09 10:51:58 jongfoster
158 * Changing "show URL info" handler to new style.
159 * Changing BUFSIZ ==> BUFFER_SIZE
161 * Revision 1.6 2001/06/07 23:05:19 jongfoster
162 * Removing code related to old forward and ACL files.
164 * Revision 1.5 2001/06/05 19:59:16 jongfoster
165 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
167 * Revision 1.4 2001/06/04 10:41:52 swa
168 * show version string of cgi.h and cgi.c
170 * Revision 1.3 2001/06/03 19:12:16 oes
171 * introduced new cgi handling
173 * No revisions before 1.3
175 **********************************************************************/
181 #include <sys/types.h>
188 #define snprintf _snprintf
189 #endif /* def _WIN32 */
200 #include "miscutil.h"
201 #include "showargs.h"
204 const char cgi_h_rcs[] = CGI_H_VERSION;
206 const struct cgi_dispatcher cgi_dispatcher[] = {
209 "HIDE Sends a robots.txt file to tell robots to go away." },
212 "Show information about the current configuration" },
214 13, cgi_show_url_info,
215 "Show which actions apply to a URL and why" },
217 12, cgi_show_version,
218 "Show the source code version numbers" },
221 "HIDE Send the transparent or \"Junkbuster\" gif" },
224 "Junkbuster main page" },
225 { NULL, 0, NULL, NULL }
232 * Hint: You can encode your own GIFs like that:
233 * perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o,", unpack("C", $c)); }'
236 const char image_junkbuster_gif_data[] =
237 "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
238 "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
239 "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
240 "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
241 "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
242 "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
243 "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
246 const int image_junkbuster_gif_length = sizeof(image_junkbuster_gif_data) - 1;
249 const char image_blank_gif_data[] =
250 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
251 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
252 "\000\001\000\000\002\002D\001\000;";
254 const int image_blank_gif_length = sizeof(image_blank_gif_data) - 1;
257 /*********************************************************************
259 * Function : dispatch_cgi
261 * Description : Checks if a request URL has either the magical hostname
262 * i.j.b or matches HOME_PAGE_URL/config/. If so, it parses
263 * the (rest of the) path as a cgi name plus query string,
264 * prepares a map that maps CGI parameter names to their values,
265 * initializes the http_response struct, and calls the
266 * relevant CGI handler function.
269 * 1 : csp = Current client state (buffers, headers, etc...)
271 * Returns : http_response if match, NULL if nonmatch or handler fail
273 *********************************************************************/
274 struct http_response *dispatch_cgi(struct client_state *csp)
276 char *argstring = NULL;
277 const struct cgi_dispatcher *d;
278 struct map *param_list;
279 struct http_response *rsp;
282 * Should we intercept ?
285 /* Either the host matches CGI_PREFIX_HOST ..*/
286 if (0 == strcmpic(csp->http->host, CGI_PREFIX_HOST))
288 /* ..then the path will all be for us */
289 argstring = csp->http->path;
291 /* Or it's the host part HOME_PAGE_URL, and the path /config ? */
292 else if ( (0 == strcmpic(csp->http->host, HOME_PAGE_URL + 7 ))
293 && (0 == strncmpic(csp->http->path,"/config", 7))
294 && ((csp->http->path[7] == '/') || (csp->http->path[7] == '\0')))
296 /* then it's everything following "/config" */
297 argstring = csp->http->path + 7;
305 * This is a CGI call.
308 /* Get mem for response or fail*/
309 if (NULL == (rsp = alloc_http_response()))
314 /* Remove leading slash */
315 if (*argstring == '/')
320 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
321 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
322 csp->ip_addr_str, csp->http->cmd);
324 /* Find and start the right CGI function*/
325 for (d = cgi_dispatcher; d->handler; d++)
327 if (strncmp(argstring, d->name, d->name_length) == 0)
329 if (NULL == (param_list =
330 parse_cgi_parameters(argstring + d->name_length)))
332 free_map(param_list);
333 free_http_response(rsp);
336 if ((d->handler)(csp, rsp, param_list))
338 free_map(param_list);
339 free_http_response(rsp);
343 free_map(param_list);
344 return(finish_http_response(rsp));
348 /* Can't get here, since cgi_default will match all requests */
349 free_http_response(rsp);
354 /*********************************************************************
356 * Function : parse_cgi_parameters
358 * Description : Parse a URL-encoded argument string into name/value
359 * pairs and store them in a struct map list.
362 * 1 : string = string to be parsed
364 * Returns : pointer to param list, or NULL if out of memory.
366 *********************************************************************/
367 struct map *parse_cgi_parameters(char *argstring)
370 char *vector[BUFFER_SIZE];
372 struct map *cgi_params;
374 if (NULL == (cgi_params = new_map()))
379 if(*argstring == '?')
383 if (NULL == (tmp = strdup(argstring)))
385 free_map(cgi_params);
389 pairs = ssplit(tmp, "&", vector, SZ(vector), 1, 1);
391 for (i = 0; i < pairs; i++)
393 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
396 map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0);
406 /*********************************************************************
408 * Function : cgi_default
410 * Description : CGI function that is called if no action was given.
411 * Lists menu of available unhidden CGIs.
414 * 1 : csp = Current client state (buffers, headers, etc...)
415 * 2 : rsp = http_response data structure for output
416 * 3 : parameters = map of cgi parameters
420 *********************************************************************/
421 int cgi_default(struct client_state *csp, struct http_response *rsp,
422 struct map *parameters)
426 struct map * exports = default_exports(csp, "");
428 /* If there were other parameters, export a dump as "cgi-parameters" */
431 p = dump_map(parameters);
432 tmp = strsav(tmp, "<p>What made you think this cgi takes parameters?\n"
433 "Anyway, here they are, in case you're interested:</p>\n");
434 tmp = strsav(tmp, p);
435 map(exports, "cgi-parameters", 1, tmp, 0);
440 map(exports, "cgi-parameters", 1, "", 1);
443 rsp->body = template_load(csp, "default");
444 template_fill(&rsp->body, exports);
451 /*********************************************************************
453 * Function : cgi_send_banner
455 * Description : CGI function that returns a banner.
458 * 1 : csp = Current client state (buffers, headers, etc...)
459 * 2 : rsp = http_response data structure for output
460 * 3 : parameters = map of cgi parameters
463 * type : Selects the type of banner between "trans" and "jb".
464 * Defaults to "jb" if absent or != "trans".
468 *********************************************************************/
469 int cgi_send_banner(struct client_state *csp, struct http_response *rsp,
470 struct map *parameters)
472 if(strcmp(lookup(parameters, "type"), "trans"))
474 rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
475 rsp->content_length = image_junkbuster_gif_length;
479 rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
480 rsp->content_length = image_blank_gif_length;
483 enlist(rsp->headers, "Content-Type: image/gif");
491 /*********************************************************************
493 * Function : cgi_show_version
495 * Description : CGI function that returns a a web page describing the
496 * file versions of IJB.
499 * 1 : csp = Current client state (buffers, headers, etc...)
500 * 2 : rsp = http_response data structure for output
501 * 3 : parameters = map of cgi parameters
504 * type : Selects the type of banner between "trans" and "jb".
505 * Defaults to "jb" if absent or != "trans".
509 *********************************************************************/
510 int cgi_show_version(struct client_state *csp, struct http_response *rsp,
511 struct map *parameters)
513 struct map * exports = default_exports(csp, "show-version");
515 map(exports, "sourceversions", 1, show_rcs(), 0);
517 rsp->body = template_load(csp, "show-version");
518 template_fill(&rsp->body, exports);
525 /*********************************************************************
527 * Function : cgi_show_status
529 * Description : CGI function that returns a a web page describing the
530 * current status of IJB.
533 * 1 : csp = Current client state (buffers, headers, etc...)
534 * 2 : rsp = http_response data structure for output
535 * 3 : parameters = map of cgi parameters
538 * type : Selects the type of banner between "trans" and "jb".
539 * Defaults to "jb" if absent or != "trans".
543 *********************************************************************/
544 int cgi_show_status(struct client_state *csp, struct http_response *rsp,
545 struct map *parameters)
551 char buf[BUFFER_SIZE];
553 const char * filename = NULL;
554 char * file_description = NULL;
555 #ifdef FEATURE_STATISTICS
556 float perc_rej; /* Percentage of http requests rejected */
558 int local_urls_rejected;
559 #endif /* ndef FEATURE_STATISTICS */
561 struct map * exports = default_exports(csp, "show-status");
563 switch (*(lookup(parameters, "file")))
566 if (csp->actions_list)
568 filename = csp->actions_list->filename;
569 file_description = "Actions List";
576 filename = csp->rlist->filename;
577 file_description = "Regex Filter List";
585 filename = csp->tlist->filename;
586 file_description = "Trust List";
589 #endif /* def FEATURE_TRUST */
592 if (NULL != filename)
594 map(exports, "file-description", 1, file_description, 1);
595 map(exports, "filepath", 1, html_encode(filename), 0);
597 if ((fp = fopen(filename, "r")) == NULL)
599 map(exports, "content", 1, "<h1>ERROR OPENING FILE!</h1>", 1);
603 while (fgets(buf, sizeof(buf), fp))
605 p = html_encode(buf);
610 s = strsav(s, "<br>");
614 map(exports, "contents", 1, s, 0);
616 rsp->body = template_load(csp, "show-status-file");
617 template_fill(&rsp->body, exports);
623 map(exports, "redirect-url", 1, REDIRECT_URL, 1);
626 for (i=0; i < Argc; i++)
628 s = strsav(s, Argv[i]);
631 map(exports, "invocation", 1, s, 0);
633 map(exports, "options", 1, csp->config->proxy_args, 1);
634 show_defines(exports);
636 #ifdef FEATURE_STATISTICS
637 local_urls_read = urls_read;
638 local_urls_rejected = urls_rejected;
641 * Need to alter the stats not to include the fetch of this
644 * Can't do following thread safely! doh!
647 * urls_rejected--; * This will be incremented subsequently *
650 if (local_urls_read == 0)
652 map_block_killer(exports, "have-stats");
656 map_block_killer(exports, "have-no-stats");
658 perc_rej = (float)local_urls_rejected * 100.0F /
659 (float)local_urls_read;
661 sprintf(buf, "%d", local_urls_read);
662 map(exports, "requests-received", 1, buf, 1);
664 sprintf(buf, "%d", local_urls_rejected);
665 map(exports, "requests-blocked", 1, buf, 1);
667 sprintf(buf, "%6.2f", perc_rej);
668 map(exports, "percent-blocked", 1, buf, 1);
671 #else /* ndef FEATURE_STATISTICS */
672 map_block_killer(exports, "statistics");
673 #endif /* ndef FEATURE_STATISTICS */
675 if (csp->actions_list)
677 map(exports, "actions-filename", 1, csp->actions_list->filename, 1);
681 map(exports, "actions-filename", 1, "None specified", 1);
686 map(exports, "re-filter-filename", 1, csp->rlist->filename, 1);
690 map(exports, "re-filter-filename", 1, "None specified", 1);
696 map(exports, "trust-filename", 1, csp->tlist->filename, 1);
700 map(exports, "trust-filename", 1, "None specified", 1);
703 map_block_killer(exports, "trust-support");
704 #endif /* ndef FEATURE_TRUST */
706 rsp->body = template_load(csp, "show-status");
707 template_fill(&rsp->body, exports);
714 /*********************************************************************
716 * Function : cgi_show_url_info
718 * Description : CGI function that determines and shows which actions
719 * junkbuster will perform for a given url, and which
720 * matches starting from the defaults have lead to that.
723 * 1 : csp = Current client state (buffers, headers, etc...)
724 * 2 : rsp = http_response data structure for output
725 * 3 : parameters = map of cgi parameters
728 * url : The url whose actions are to be determined.
729 * If url is unset, the url-given conditional will be
730 * set, so that all but the form can be suppressed in
735 *********************************************************************/
736 int cgi_show_url_info(struct client_state *csp, struct http_response *rsp,
737 struct map *parameters)
741 struct map * exports = default_exports(csp, "show-url-info");
743 if (NULL == (url_param = strdup(lookup(parameters, "url"))) || *url_param == '\0')
745 map_block_killer(exports, "url-given");
746 map(exports, "url", 1, "", 1);
750 char *matches = NULL;
755 struct file_list *fl;
756 struct url_actions *b;
757 struct url_spec url[1];
758 struct current_action_spec action[1];
761 host += (strncmp(url_param, "http://", 7)) ? 0 : 7;
763 map(exports, "url", 1, host, 1);
764 map(exports, "url-html", 1, html_encode(host), 0);
766 init_current_action(action);
768 s = current_action_to_text(action);
769 map(exports, "default", 1, s , 0);
771 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
773 map(exports, "matches", 1, "none" , 1);
774 map(exports, "final", 1, lookup(exports, "default"), 1);
777 free_current_action(action);
779 rsp->body = template_load(csp, "show-url-info");
780 template_fill(&rsp->body, exports);
786 s = strchr(host, '/');
796 s = strchr(host, ':');
806 /* if splitting the domain fails, punt */
807 if (url->dbuf == NULL)
809 map(exports, "matches", 1, "none" , 1);
810 map(exports, "final", 1, lookup(exports, "default"), 1);
814 free_current_action(action);
816 rsp->body = template_load(csp, "show-url-info");
817 template_fill(&rsp->body, exports);
823 for (b = b->next; NULL != b; b = b->next)
825 if ((b->url->port == 0) || (b->url->port == port))
827 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
829 if ((b->url->path == NULL) ||
831 (regexec(b->url->preg, path, 0, NULL, 0) == 0)
833 (strncmp(b->url->path, path, b->url->pathlen) == 0)
837 s = actions_to_text(b->action);
838 matches = strsav(matches, "<b>{");
839 matches = strsav(matches, s);
840 matches = strsav(matches, " }</b><br>\n<code>");
841 matches = strsav(matches, b->url->spec);
842 matches = strsav(matches, "</code><br>\n<br>\n");
845 merge_current_action(action, b->action);
854 map(exports, "matches", 1, matches , 0);
858 map(exports, "matches", 1, "none", 1);
868 s = current_action_to_text(action);
869 map(exports, "final", 1, s, 0);
872 free_current_action(action);
875 rsp->body = template_load(csp, "show-url-info");
876 template_fill(&rsp->body, exports);
883 /*********************************************************************
885 * Function : error_response
887 * Description : returns an http_response that explains the reason
888 * why a request failed.
891 * 1 : csp = Current client state (buffers, headers, etc...)
892 * 2 : templatename = Which template should be used for the answer
893 * 3 : errno = system error number
895 * Returns : NULL if no memory, else http_response
897 *********************************************************************/
898 struct http_response *error_response(struct client_state *csp, const char *templatename, int err)
900 struct http_response *rsp;
901 struct map * exports = default_exports(csp, NULL);
903 if (NULL == (rsp = alloc_http_response()))
908 map(exports, "host-html", 1, html_encode(csp->http->host), 0);
909 map(exports, "hostport", 1, csp->http->hostport, 1);
910 map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
911 map(exports, "path", 1, csp->http->path, 1);
912 map(exports, "path-html", 1, html_encode(csp->http->path), 0);
913 map(exports, "error", 1, safe_strerror(err), 0);
914 map(exports, "host-ip", 1, csp->http->host_ip_addr_str, 1);
916 rsp->body = template_load(csp, templatename);
917 template_fill(&rsp->body, exports);
920 if (!strcmp(templatename, "no-such-domain"))
922 rsp->status = strdup("404 No such domain");
924 else if (!strcmp(templatename, "connect-failed"))
926 rsp->status = strdup("503 Connect failed");
929 return(finish_http_response(rsp));
933 /*********************************************************************
935 * Function : get_http_time
937 * Description : Get the time in a format suitable for use in a
938 * HTTP header - e.g.:
939 * "Sun, 06 Nov 1994 08:49:37 GMT"
942 * 1 : time_offset = Time returned will be current time
943 * plus this number of seconds.
944 * 2 : buf = Destination for result. Must be long enough
945 * to hold 29 characters plus a trailing zero.
949 *********************************************************************/
950 static void get_http_time(int time_offset, char * buf)
952 static const char day_names[7][4] =
953 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
954 static const char month_names[12][4] =
955 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
956 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
963 time(¤t_time); /* get current time */
965 /* FIXME: is this needed? time() can't fail on Win32. What about Linux?
966 if(current_time <= 0)
972 current_time += time_offset;
974 /* get and save the gmt */
975 t = gmtime(¤t_time);
977 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
979 "%s, %02d %s %4d %02d:%02d:%02d GMT",
980 day_names[t->tm_wday],
982 month_names[t->tm_mon],
992 /*********************************************************************
994 * Function : finish_http_response
996 * Description : Fill in the missing headers in an http response,
997 * and flatten the headers to an http head.
1000 * 1 : rsp = pointer to http_response to be processed
1002 * Returns : http_response, or NULL on failiure
1004 *********************************************************************/
1005 struct http_response *finish_http_response(struct http_response *rsp)
1007 char buf[BUFFER_SIZE];
1010 * Fill in the HTTP Status
1012 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1013 enlist_first(rsp->headers, buf);
1016 * Set the Content-Length
1018 if (rsp->content_length == 0)
1020 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1022 sprintf(buf, "Content-Length: %d", rsp->content_length);
1023 enlist(rsp->headers, buf);
1026 * Fill in the default headers:
1028 * Content-Type: default to text/html if not already specified.
1029 * Date: set to current date/time.
1030 * Last-Modified: set to date/time the page was last changed.
1031 * Expires: set to date/time page next needs reloading.
1032 * Cache-Control: set to "no-cache" if applicable.
1034 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1036 enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1041 * Set Expires to about 10 min into the future so it'll get reloaded
1042 * occasionally, e.g. if IJB gets upgraded.
1045 get_http_time(0, buf);
1046 enlist_unique_header(rsp->headers, "Date", buf);
1048 /* Some date in the past. */
1049 enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1051 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1052 enlist_unique_header(rsp->headers, "Expires", buf);
1057 * Compliant browsers should not cache this due to the "Cache-Control"
1058 * setting. However, to be certain, we also set both "Last-Modified"
1059 * and "Expires" to the current time.
1061 enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1062 get_http_time(0, buf);
1063 enlist_unique_header(rsp->headers, "Date", buf);
1064 enlist_unique_header(rsp->headers, "Last-Modified", buf);
1065 enlist_unique_header(rsp->headers, "Expires", buf);
1072 if (NULL == (rsp->head = list_to_text(rsp->headers)))
1074 free_http_response(rsp);
1077 rsp->head_length = strlen(rsp->head);
1084 /*********************************************************************
1086 * Function : alloc_http_response
1088 * Description : Allocates a new http_response structure.
1092 * Returns : pointer to a new http_response, or NULL.
1094 *********************************************************************/
1095 struct http_response * alloc_http_response(void)
1097 return (struct http_response *) zalloc(sizeof(struct http_response));
1101 /*********************************************************************
1103 * Function : free_http_response
1105 * Description : Free the memory occupied by an http_response
1106 * and its depandant structures.
1109 * 1 : rsp = pointer to http_response to be freed
1113 *********************************************************************/
1114 void free_http_response(struct http_response *rsp)
1121 destroy_list(rsp->headers);
1128 /*********************************************************************
1130 * Function : fill_template
1132 * Description : CGI support function that loads a given HTML
1133 * template from the confdir, and fills it in
1134 * by replacing @name@ with value using pcrs,
1135 * for each item in the output map.
1138 * 1 : csp = Current client state (buffers, headers, etc...)
1139 * 3 : template = name of the HTML template to be used
1141 * Returns : char * with loaded template, or NULL if failure
1143 *********************************************************************/
1144 char *template_load(struct client_state *csp, const char *templatename)
1146 char buf[BUFFER_SIZE];
1147 char *file_buffer = NULL;
1151 * Open template file or fail
1153 snprintf(buf, BUFFER_SIZE, "%s/templates/%s", csp->config->confdir, templatename);
1155 if(NULL == (fp = fopen(buf, "r")))
1157 log_error(LOG_LEVEL_ERROR, "error loading template %s: %E", buf);
1163 * Read the file, ignoring comments
1165 while (fgets(buf, BUFFER_SIZE, fp))
1167 /* skip lines starting with '#' */
1173 file_buffer = strsav(file_buffer, buf);
1177 return(file_buffer);
1181 /*********************************************************************
1183 * Function : fill_template
1185 * Description : CGI support function that loads a given HTML
1186 * template from the confdir, and fills it in
1187 * by replacing @name@ with value using pcrs,
1188 * for each item in the output map.
1191 * 1 : template_ptr = IN: Template to be filled out.
1193 * OUT: Filled out template.
1194 * Caller must free().
1195 * 2 : exports = map with fill in symbol -> name pairs
1199 *********************************************************************/
1200 void template_fill(char ** template_ptr, struct map *exports)
1202 struct map_entry *m;
1204 char buf[BUFFER_SIZE];
1205 char *tmp_out_buffer;
1211 assert(template_ptr);
1212 assert(*template_ptr);
1215 file_buffer = *template_ptr;
1216 size = strlen(file_buffer) + 1;
1219 * Assemble pcrs joblist from exports map
1221 for (m = exports->first; m != NULL; m = m->next)
1223 if (*m->name == '$')
1226 * First character of name is '$', so remove this flag
1227 * character and allow backreferences ($1 etc) in the
1228 * "replace with" text.
1230 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1236 * Treat the "replace with" text as a literal string -
1237 * no quoting needed, no backreferences allowed.
1238 * ("Trivial" ['T'] flag).
1242 /* Enclose name in @@ */
1243 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1247 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1249 /* Make and run job. */
1250 job = pcrs_compile(buf, m->value, flags, &error);
1253 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1257 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1258 if (file_buffer != tmp_out_buffer)
1261 file_buffer = tmp_out_buffer;
1270 *template_ptr = file_buffer;
1274 /*********************************************************************
1276 * Function : default_exports
1278 * Description : returns a struct map list that contains exports
1279 * which are common to all CGI functions.
1282 * 1 : exports = Structure to write output to. This
1283 * structure should be newly allocated and will be
1285 * 1 : csp = Current client state (buffers, headers, etc...)
1286 * 2 : caller = name of CGI who calls us and which should
1287 * be excluded from the generated menu.
1288 * Returns : NULL if no memory, else map
1290 *********************************************************************/
1291 struct map * default_exports(const struct client_state *csp, const char *caller)
1294 struct map * exports = new_map();
1296 map(exports, "version", 1, VERSION, 1);
1297 map(exports, "my-ip-address", 1, csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown", 1);
1298 map(exports, "my-hostname", 1, csp->my_hostname ? csp->my_hostname : "unknown", 1);
1299 map(exports, "admin-address", 1, csp->config->admin_address ? csp->config->admin_address : "fill@me.in.please", 1);
1300 map(exports, "homepage", 1, HOME_PAGE_URL, 1);
1301 map(exports, "default-cgi", 1, HOME_PAGE_URL "/config", 1);
1302 map(exports, "menu", 1, make_menu(caller), 0);
1303 map(exports, "code-status", 1, CODE_STATUS, 1);
1305 snprintf(buf, 20, "%d", csp->config->hport);
1306 map(exports, "my-port", 1, buf, 1);
1308 if(!strcmp(CODE_STATUS, "stable"))
1310 map_block_killer(exports, "unstable");
1313 if(csp->config->proxy_info_url != NULL)
1315 map(exports, "proxy-info-url", 1, csp->config->proxy_info_url, 1);
1319 map_block_killer(exports, "have-proxy-info");
1326 /*********************************************************************
1328 * Function : map_block_killer
1330 * Description : Convenience function.
1331 * Adds a "killer" for the conditional HTML-template
1332 * block <name>, i.e. a substitution of the regex
1333 * "if-<name>-start.*if-<name>-end" to the given
1337 * 1 : exports = map to extend
1338 * 2 : name = name of conditional block
1340 * Returns : extended map
1342 *********************************************************************/
1343 void map_block_killer(struct map *exports, const char *name)
1345 char buf[1000]; /* Will do, since the names are hardwired */
1347 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1348 map(exports, buf, 1, "", 1);
1352 /*********************************************************************
1354 * Function : map_conditional
1356 * Description : Convenience function.
1357 * Adds an "if-then-else" for the conditional HTML-template
1358 * block <name>, i.e. a substitution of the form:
1365 * The control structure and one of the alternatives
1369 * 1 : exports = map to extend
1370 * 2 : name = name of conditional block
1371 * 3 : choose_first = nonzero for first, zero for second.
1373 * Returns : extended map
1375 *********************************************************************/
1376 void map_conditional(struct map *exports, const char *name, int choose_first)
1378 char buf[1000]; /* Will do, since the names are hardwired */
1380 snprintf(buf, 1000, (choose_first
1381 ? "else-not-%s@.*@endif-%s"
1382 : "if-%s-then@.*@else-not-%s"),
1384 map(exports, buf, 1, "", 1);
1386 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1387 map(exports, buf, 1, "", 1);
1391 /*********************************************************************
1393 * Function : make_menu
1395 * Description : Returns an HTML-formatted menu of the available
1396 * unhidden CGIs, excluding the one given in <self>.
1398 * Parameters : self = name of CGI to leave out, can be NULL
1400 * Returns : menu string
1402 *********************************************************************/
1403 char *make_menu(const char *self)
1405 const struct cgi_dispatcher *d;
1406 char buf[BUFFER_SIZE];
1407 char *result = NULL;
1411 self = "NO-SUCH-CGI!";
1414 /* List available unhidden CGI's and export as "other-cgis" */
1415 for (d = cgi_dispatcher; d->handler; d++)
1417 if (strncmp(d->description, "HIDE", 4) && strcmp(d->name, self))
1419 snprintf(buf, BUFFER_SIZE, "<li><a href=%s/config/%s>%s</a></li>\n",
1420 HOME_PAGE_URL, d->name, d->description);
1421 result = strsav(result, buf);
1429 /*********************************************************************
1431 * Function : dump_map
1433 * Description : HTML-dump a map for debugging
1436 * 1 : the_map = map to dump
1438 * Returns : string with HTML
1440 *********************************************************************/
1441 char *dump_map(const struct map *the_map)
1443 struct map_entry *cur_entry = the_map->first;
1446 ret = strsav(ret, "<table>\n");
1450 ret = strsav(ret, "<tr><td><b>");
1451 ret = strsav(ret, cur_entry->name);
1452 ret = strsav(ret, "</b></td><td>");
1453 ret = strsav(ret, cur_entry->value);
1454 ret = strsav(ret, "</td></tr>\n");
1455 cur_entry = cur_entry->next;
1458 ret = strsav(ret, "</table>\n");
1464 /*********************************************************************
1466 * Function : cgi_robots_txt
1468 * Description : CGI function to return "/robots.txt".
1471 * 1 : csp = Current client state (buffers, headers, etc...)
1472 * 2 : rsp = http_response data structure for output
1473 * 3 : parameters = map of cgi parameters
1475 * CGI Parameters : None
1479 *********************************************************************/
1480 int cgi_robots_txt(struct client_state *csp, struct http_response *rsp,
1481 struct map *parameters)
1486 "# This is the Internet Junkbuster control interface.\n"
1487 "# It isn't very useful to index it, and you're likely to break stuff.\n"
1494 enlist_unique(rsp->headers, "Content-Type: text/plain", 13);
1498 get_http_time(7 * 24 * 60 * 60, buf); /* 7 days into future */
1499 enlist_unique_header(rsp->headers, "Expires", buf);