1 const char cgi_rcs[] = "$Id: cgi.c,v 1.25 2001/09/16 15:02:35 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.25 2001/09/16 15:02:35 jongfoster
40 * Adding i.j.b/robots.txt.
41 * Inlining add_stats() since it's only ever called from one place.
43 * Revision 1.24 2001/09/16 11:38:01 jongfoster
44 * Splitting fill_template() into 2 functions:
45 * template_load() loads the file
46 * template_fill() performs the PCRS regexps.
47 * This is because the CGI edit interface has a "table row"
48 * template which is used many times in the page - this
49 * change means it's only loaded from disk once.
51 * Revision 1.23 2001/09/16 11:16:05 jongfoster
52 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
54 * Revision 1.22 2001/09/16 11:00:10 jongfoster
55 * New function alloc_http_response, for symmetry with free_http_response
57 * Revision 1.21 2001/09/13 23:53:03 jongfoster
58 * Support for both static and dynamically generated CGI pages.
59 * Correctly setting Last-Modified: and Expires: HTTP headers.
61 * Revision 1.20 2001/09/13 23:40:36 jongfoster
62 * (Cosmetic only) Indentation correction
64 * Revision 1.19 2001/09/13 23:31:25 jongfoster
65 * Moving image data to cgi.c rather than cgi.h.
67 * Revision 1.18 2001/08/05 16:06:20 jongfoster
68 * Modifiying "struct map" so that there are now separate header and
69 * "map_entry" structures. This means that functions which modify a
70 * map no longer need to return a pointer to the modified map.
71 * Also, it no longer reverses the order of the entries (which may be
72 * important with some advanced template substitutions).
74 * Revision 1.17 2001/08/05 15:57:38 oes
75 * Adapted finish_http_response to new list_to_text
77 * Revision 1.16 2001/08/01 21:33:18 jongfoster
78 * Changes to fill_template() that reduce memory usage without having
79 * an impact on performance. I also renamed some variables so as not
80 * to clash with the C++ keywords "new" and "template".
82 * Revision 1.15 2001/08/01 21:19:22 jongfoster
83 * Moving file version information to a separate CGI page.
85 * Revision 1.14 2001/08/01 00:19:03 jongfoster
86 * New function: map_conditional() for an if-then-else syntax.
87 * Changing to use new version of show_defines()
89 * Revision 1.13 2001/07/30 22:08:36 jongfoster
90 * Tidying up #defines:
91 * - All feature #defines are now of the form FEATURE_xxx
92 * - Permanently turned off WIN_GUI_EDIT
93 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
95 * Revision 1.12 2001/07/29 18:47:05 jongfoster
96 * Adding missing #include "loadcfg.h"
98 * Revision 1.11 2001/07/18 17:24:37 oes
99 * Changed to conform to new pcrs interface
101 * Revision 1.10 2001/07/13 13:53:13 oes
102 * Removed all #ifdef PCRS and related code
104 * Revision 1.9 2001/06/29 21:45:41 oes
105 * Indentation, CRLF->LF, Tab-> Space
107 * Revision 1.8 2001/06/29 13:21:46 oes
108 * - Cosmetics: renamed and reordered functions, variables,
109 * texts, improved comments etc
111 * - Removed ij_untrusted_url() The relevant
112 * info is now part of the "untrusted" page,
113 * which is generated by filters.c:trust_url()
115 * - Generators of content now call finish_http_response()
116 * themselves, making jcc.c:chat() a little less
119 * - Removed obsolete "Pragma: no-cache" from our headers
121 * - http_responses now know their head length
123 * - fill_template now uses the new interface to pcrs, so that
124 * - long jobs (like whole files) no longer have to be assembled
125 * in a fixed size buffer
126 * - the new T (trivial) option is used, and the replacement may
127 * contain Perl syntax backrefs without confusing pcrs
129 * - Introduced default_exports() which generates a set of exports
130 * common to all CGIs and other content generators
132 * - Introduced convenience function map_block_killer()
134 * - Introduced convenience function make_menu()
136 * - Introduced CGI-like function error_response() which generates
137 * the "No such domain" and "Connect failed" messages using the
140 * - cgi_show_url_info:
141 * - adapted to new CGI features
142 * - form and answers now generated from same template
143 * - http:// prefix in URL now OK
146 * - adapted to new CGI features
147 * - no longer uses csp->init_proxy_args
150 * - moved menu generation to make_menu()
152 * - add_stats now writes single export map entries instead
155 * - Moved redirect_url() to filters.c
157 * - Fixed mem leak in free_http_response(), map_block_killer(),
159 * - Removed logentry from cancelled commit
161 * Revision 1.7 2001/06/09 10:51:58 jongfoster
162 * Changing "show URL info" handler to new style.
163 * Changing BUFSIZ ==> BUFFER_SIZE
165 * Revision 1.6 2001/06/07 23:05:19 jongfoster
166 * Removing code related to old forward and ACL files.
168 * Revision 1.5 2001/06/05 19:59:16 jongfoster
169 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
171 * Revision 1.4 2001/06/04 10:41:52 swa
172 * show version string of cgi.h and cgi.c
174 * Revision 1.3 2001/06/03 19:12:16 oes
175 * introduced new cgi handling
177 * No revisions before 1.3
179 **********************************************************************/
185 #include <sys/types.h>
192 #define snprintf _snprintf
193 #endif /* def _WIN32 */
204 #include "miscutil.h"
205 #include "showargs.h"
207 #ifdef FEATURE_CGI_EDIT_ACTIONS
209 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
211 const char cgi_h_rcs[] = CGI_H_VERSION;
213 const struct cgi_dispatcher cgi_dispatcher[] = {
216 "HIDE Sends a robots.txt file to tell robots to go away." },
219 "Show information about the current configuration" },
221 13, cgi_show_url_info,
222 "Show which actions apply to a URL and why" },
224 12, cgi_show_version,
225 "Show the source code version numbers" },
228 "HIDE Send the transparent or \"Junkbuster\" gif" },
229 #ifdef FEATURE_CGI_EDIT_ACTIONS
230 { "edit-actions-list",
231 17, cgi_edit_actions_list,
232 "Edit the actions list" },
233 { "edit-actions-submit",
234 19, cgi_edit_actions_submit,
235 "HIDE Change the actions for (a) specified URL(s)" },
237 12, cgi_edit_actions,
238 "HIDE Edit the actions for (a) specified URL(s)" },
239 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
242 "Junkbuster main page" },
243 { NULL, 0, NULL, NULL }
250 * Hint: You can encode your own GIFs like that:
251 * perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o,", unpack("C", $c)); }'
254 const char image_junkbuster_gif_data[] =
255 "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
256 "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
257 "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
258 "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
259 "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
260 "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
261 "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
264 const int image_junkbuster_gif_length = sizeof(image_junkbuster_gif_data) - 1;
267 const char image_blank_gif_data[] =
268 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
269 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
270 "\000\001\000\000\002\002D\001\000;";
272 const int image_blank_gif_length = sizeof(image_blank_gif_data) - 1;
275 /*********************************************************************
277 * Function : dispatch_cgi
279 * Description : Checks if a request URL has either the magical hostname
280 * i.j.b or matches HOME_PAGE_URL/config/. If so, it parses
281 * the (rest of the) path as a cgi name plus query string,
282 * prepares a map that maps CGI parameter names to their values,
283 * initializes the http_response struct, and calls the
284 * relevant CGI handler function.
287 * 1 : csp = Current client state (buffers, headers, etc...)
289 * Returns : http_response if match, NULL if nonmatch or handler fail
291 *********************************************************************/
292 struct http_response *dispatch_cgi(struct client_state *csp)
294 char *argstring = NULL;
295 const struct cgi_dispatcher *d;
296 struct map *param_list;
297 struct http_response *rsp;
300 * Should we intercept ?
303 /* Either the host matches CGI_PREFIX_HOST ..*/
304 if (0 == strcmpic(csp->http->host, CGI_PREFIX_HOST))
306 /* ..then the path will all be for us */
307 argstring = csp->http->path;
309 /* Or it's the host part HOME_PAGE_URL, and the path /config ? */
310 else if ( (0 == strcmpic(csp->http->host, HOME_PAGE_URL + 7 ))
311 && (0 == strncmpic(csp->http->path,"/config", 7))
312 && ((csp->http->path[7] == '/') || (csp->http->path[7] == '\0')))
314 /* then it's everything following "/config" */
315 argstring = csp->http->path + 7;
323 * This is a CGI call.
326 /* Get mem for response or fail*/
327 if (NULL == (rsp = alloc_http_response()))
333 /* Remove leading slash */
334 if (*argstring == '/')
339 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
340 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
341 csp->ip_addr_str, csp->http->cmd);
343 /* Find and start the right CGI function*/
344 for (d = cgi_dispatcher; d->handler; d++)
346 if (strncmp(argstring, d->name, d->name_length) == 0)
348 if (NULL == (param_list =
349 parse_cgi_parameters(argstring + d->name_length)))
351 free_map(param_list);
352 free_http_response(rsp);
355 if ((d->handler)(csp, rsp, param_list))
357 free_map(param_list);
358 free_http_response(rsp);
362 free_map(param_list);
363 return(finish_http_response(rsp));
367 /* Can't get here, since cgi_default will match all requests */
368 free_http_response(rsp);
373 /*********************************************************************
375 * Function : parse_cgi_parameters
377 * Description : Parse a URL-encoded argument string into name/value
378 * pairs and store them in a struct map list.
381 * 1 : string = string to be parsed
383 * Returns : pointer to param list, or NULL if out of memory.
385 *********************************************************************/
386 struct map *parse_cgi_parameters(char *argstring)
389 char *vector[BUFFER_SIZE];
391 struct map *cgi_params;
393 if (NULL == (cgi_params = new_map()))
398 if(*argstring == '?')
402 if (NULL == (tmp = strdup(argstring)))
404 free_map(cgi_params);
408 pairs = ssplit(tmp, "&", vector, SZ(vector), 1, 1);
410 for (i = 0; i < pairs; i++)
412 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
415 map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0);
425 /*********************************************************************
427 * Function : cgi_default
429 * Description : CGI function that is called if no action was given.
430 * Lists menu of available unhidden CGIs.
433 * 1 : csp = Current client state (buffers, headers, etc...)
434 * 2 : rsp = http_response data structure for output
435 * 3 : parameters = map of cgi parameters
439 *********************************************************************/
440 int cgi_default(struct client_state *csp, struct http_response *rsp,
441 struct map *parameters)
445 struct map * exports = default_exports(csp, "");
447 /* If there were other parameters, export a dump as "cgi-parameters" */
450 p = dump_map(parameters);
451 tmp = strsav(tmp, "<p>What made you think this cgi takes parameters?\n"
452 "Anyway, here they are, in case you're interested:</p>\n");
453 tmp = strsav(tmp, p);
454 map(exports, "cgi-parameters", 1, tmp, 0);
459 map(exports, "cgi-parameters", 1, "", 1);
462 rsp->body = template_load(csp, "default");
463 template_fill(&rsp->body, exports);
470 /*********************************************************************
472 * Function : cgi_send_banner
474 * Description : CGI function that returns a banner.
477 * 1 : csp = Current client state (buffers, headers, etc...)
478 * 2 : rsp = http_response data structure for output
479 * 3 : parameters = map of cgi parameters
482 * type : Selects the type of banner between "trans" and "jb".
483 * Defaults to "jb" if absent or != "trans".
487 *********************************************************************/
488 int cgi_send_banner(struct client_state *csp, struct http_response *rsp,
489 struct map *parameters)
491 if(strcmp(lookup(parameters, "type"), "trans"))
493 rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
494 rsp->content_length = image_junkbuster_gif_length;
498 rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
499 rsp->content_length = image_blank_gif_length;
502 enlist(rsp->headers, "Content-Type: image/gif");
510 /*********************************************************************
512 * Function : cgi_show_version
514 * Description : CGI function that returns a a web page describing the
515 * file versions of IJB.
518 * 1 : csp = Current client state (buffers, headers, etc...)
519 * 2 : rsp = http_response data structure for output
520 * 3 : parameters = map of cgi parameters
523 * type : Selects the type of banner between "trans" and "jb".
524 * Defaults to "jb" if absent or != "trans".
528 *********************************************************************/
529 int cgi_show_version(struct client_state *csp, struct http_response *rsp,
530 struct map *parameters)
532 struct map * exports = default_exports(csp, "show-version");
534 map(exports, "sourceversions", 1, show_rcs(), 0);
536 rsp->body = template_load(csp, "show-version");
537 template_fill(&rsp->body, exports);
544 /*********************************************************************
546 * Function : cgi_show_status
548 * Description : CGI function that returns a a web page describing the
549 * current status of IJB.
552 * 1 : csp = Current client state (buffers, headers, etc...)
553 * 2 : rsp = http_response data structure for output
554 * 3 : parameters = map of cgi parameters
557 * type : Selects the type of banner between "trans" and "jb".
558 * Defaults to "jb" if absent or != "trans".
562 *********************************************************************/
563 int cgi_show_status(struct client_state *csp, struct http_response *rsp,
564 struct map *parameters)
570 char buf[BUFFER_SIZE];
572 const char * filename = NULL;
573 char * file_description = NULL;
574 #ifdef FEATURE_STATISTICS
575 float perc_rej; /* Percentage of http requests rejected */
577 int local_urls_rejected;
578 #endif /* ndef FEATURE_STATISTICS */
580 struct map * exports = default_exports(csp, "show-status");
582 switch (*(lookup(parameters, "file")))
585 if (csp->actions_list)
587 filename = csp->actions_list->filename;
588 file_description = "Actions List";
595 filename = csp->rlist->filename;
596 file_description = "Regex Filter List";
604 filename = csp->tlist->filename;
605 file_description = "Trust List";
608 #endif /* def FEATURE_TRUST */
611 if (NULL != filename)
613 map(exports, "file-description", 1, file_description, 1);
614 map(exports, "filepath", 1, html_encode(filename), 0);
616 if ((fp = fopen(filename, "r")) == NULL)
618 map(exports, "content", 1, "<h1>ERROR OPENING FILE!</h1>", 1);
622 while (fgets(buf, sizeof(buf), fp))
624 p = html_encode(buf);
629 s = strsav(s, "<br>");
633 map(exports, "contents", 1, s, 0);
635 rsp->body = template_load(csp, "show-status-file");
636 template_fill(&rsp->body, exports);
642 map(exports, "redirect-url", 1, REDIRECT_URL, 1);
645 for (i=0; i < Argc; i++)
647 s = strsav(s, Argv[i]);
650 map(exports, "invocation", 1, s, 0);
652 map(exports, "options", 1, csp->config->proxy_args, 1);
653 show_defines(exports);
655 #ifdef FEATURE_STATISTICS
656 local_urls_read = urls_read;
657 local_urls_rejected = urls_rejected;
660 * Need to alter the stats not to include the fetch of this
663 * Can't do following thread safely! doh!
666 * urls_rejected--; * This will be incremented subsequently *
669 if (local_urls_read == 0)
671 map_block_killer(exports, "have-stats");
675 map_block_killer(exports, "have-no-stats");
677 perc_rej = (float)local_urls_rejected * 100.0F /
678 (float)local_urls_read;
680 sprintf(buf, "%d", local_urls_read);
681 map(exports, "requests-received", 1, buf, 1);
683 sprintf(buf, "%d", local_urls_rejected);
684 map(exports, "requests-blocked", 1, buf, 1);
686 sprintf(buf, "%6.2f", perc_rej);
687 map(exports, "percent-blocked", 1, buf, 1);
690 #else /* ndef FEATURE_STATISTICS */
691 map_block_killer(exports, "statistics");
692 #endif /* ndef FEATURE_STATISTICS */
694 if (csp->actions_list)
696 map(exports, "actions-filename", 1, csp->actions_list->filename, 1);
700 map(exports, "actions-filename", 1, "None specified", 1);
705 map(exports, "re-filter-filename", 1, csp->rlist->filename, 1);
709 map(exports, "re-filter-filename", 1, "None specified", 1);
715 map(exports, "trust-filename", 1, csp->tlist->filename, 1);
719 map(exports, "trust-filename", 1, "None specified", 1);
722 map_block_killer(exports, "trust-support");
723 #endif /* ndef FEATURE_TRUST */
725 rsp->body = template_load(csp, "show-status");
726 template_fill(&rsp->body, exports);
733 /*********************************************************************
735 * Function : cgi_show_url_info
737 * Description : CGI function that determines and shows which actions
738 * junkbuster will perform for a given url, and which
739 * matches starting from the defaults have lead to that.
742 * 1 : csp = Current client state (buffers, headers, etc...)
743 * 2 : rsp = http_response data structure for output
744 * 3 : parameters = map of cgi parameters
747 * url : The url whose actions are to be determined.
748 * If url is unset, the url-given conditional will be
749 * set, so that all but the form can be suppressed in
754 *********************************************************************/
755 int cgi_show_url_info(struct client_state *csp, struct http_response *rsp,
756 struct map *parameters)
760 struct map * exports = default_exports(csp, "show-url-info");
762 if (NULL == (url_param = strdup(lookup(parameters, "url"))) || *url_param == '\0')
764 map_block_killer(exports, "url-given");
765 map(exports, "url", 1, "", 1);
769 char *matches = NULL;
774 struct file_list *fl;
775 struct url_actions *b;
776 struct url_spec url[1];
777 struct current_action_spec action[1];
780 host += (strncmp(url_param, "http://", 7)) ? 0 : 7;
782 map(exports, "url", 1, host, 1);
783 map(exports, "url-html", 1, html_encode(host), 0);
785 init_current_action(action);
787 s = current_action_to_text(action);
788 map(exports, "default", 1, s , 0);
790 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
792 map(exports, "matches", 1, "none" , 1);
793 map(exports, "final", 1, lookup(exports, "default"), 1);
796 free_current_action(action);
798 rsp->body = template_load(csp, "show-url-info");
799 template_fill(&rsp->body, exports);
805 s = strchr(host, '/');
815 s = strchr(host, ':');
825 /* if splitting the domain fails, punt */
826 if (url->dbuf == NULL)
828 map(exports, "matches", 1, "none" , 1);
829 map(exports, "final", 1, lookup(exports, "default"), 1);
833 free_current_action(action);
835 rsp->body = template_load(csp, "show-url-info");
836 template_fill(&rsp->body, exports);
842 for (b = b->next; NULL != b; b = b->next)
844 if ((b->url->port == 0) || (b->url->port == port))
846 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
848 if ((b->url->path == NULL) ||
850 (regexec(b->url->preg, path, 0, NULL, 0) == 0)
852 (strncmp(b->url->path, path, b->url->pathlen) == 0)
856 s = actions_to_text(b->action);
857 matches = strsav(matches, "<b>{");
858 matches = strsav(matches, s);
859 matches = strsav(matches, " }</b><br>\n<code>");
860 matches = strsav(matches, b->url->spec);
861 matches = strsav(matches, "</code><br>\n<br>\n");
864 merge_current_action(action, b->action);
873 map(exports, "matches", 1, matches , 0);
877 map(exports, "matches", 1, "none", 1);
887 s = current_action_to_text(action);
888 map(exports, "final", 1, s, 0);
891 free_current_action(action);
894 rsp->body = template_load(csp, "show-url-info");
895 template_fill(&rsp->body, exports);
902 /*********************************************************************
904 * Function : error_response
906 * Description : returns an http_response that explains the reason
907 * why a request failed.
910 * 1 : csp = Current client state (buffers, headers, etc...)
911 * 2 : templatename = Which template should be used for the answer
912 * 3 : errno = system error number
914 * Returns : NULL if no memory, else http_response
916 *********************************************************************/
917 struct http_response *error_response(struct client_state *csp, const char *templatename, int err)
919 struct http_response *rsp;
920 struct map * exports = default_exports(csp, NULL);
922 if (NULL == (rsp = alloc_http_response()))
927 map(exports, "host-html", 1, html_encode(csp->http->host), 0);
928 map(exports, "hostport", 1, csp->http->hostport, 1);
929 map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
930 map(exports, "path", 1, csp->http->path, 1);
931 map(exports, "path-html", 1, html_encode(csp->http->path), 0);
932 map(exports, "error", 1, safe_strerror(err), 0);
933 map(exports, "host-ip", 1, csp->http->host_ip_addr_str, 1);
935 rsp->body = template_load(csp, templatename);
936 template_fill(&rsp->body, exports);
939 if (!strcmp(templatename, "no-such-domain"))
941 rsp->status = strdup("404 No such domain");
943 else if (!strcmp(templatename, "connect-failed"))
945 rsp->status = strdup("503 Connect failed");
948 return(finish_http_response(rsp));
952 /*********************************************************************
954 * Function : get_http_time
956 * Description : Get the time in a format suitable for use in a
957 * HTTP header - e.g.:
958 * "Sun, 06 Nov 1994 08:49:37 GMT"
961 * 1 : time_offset = Time returned will be current time
962 * plus this number of seconds.
963 * 2 : buf = Destination for result. Must be long enough
964 * to hold 29 characters plus a trailing zero.
968 *********************************************************************/
969 static void get_http_time(int time_offset, char * buf)
971 static const char day_names[7][4] =
972 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
973 static const char month_names[12][4] =
974 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
975 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
982 time(¤t_time); /* get current time */
984 /* FIXME: is this needed? time() can't fail on Win32. What about Linux?
985 if(current_time <= 0)
991 current_time += time_offset;
993 /* get and save the gmt */
994 t = gmtime(¤t_time);
996 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
998 "%s, %02d %s %4d %02d:%02d:%02d GMT",
999 day_names[t->tm_wday],
1001 month_names[t->tm_mon],
1011 /*********************************************************************
1013 * Function : finish_http_response
1015 * Description : Fill in the missing headers in an http response,
1016 * and flatten the headers to an http head.
1019 * 1 : rsp = pointer to http_response to be processed
1021 * Returns : http_response, or NULL on failiure
1023 *********************************************************************/
1024 struct http_response *finish_http_response(struct http_response *rsp)
1026 char buf[BUFFER_SIZE];
1029 * Fill in the HTTP Status
1031 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1032 enlist_first(rsp->headers, buf);
1035 * Set the Content-Length
1037 if (rsp->content_length == 0)
1039 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1041 sprintf(buf, "Content-Length: %d", rsp->content_length);
1042 enlist(rsp->headers, buf);
1045 * Fill in the default headers:
1047 * Content-Type: default to text/html if not already specified.
1048 * Date: set to current date/time.
1049 * Last-Modified: set to date/time the page was last changed.
1050 * Expires: set to date/time page next needs reloading.
1051 * Cache-Control: set to "no-cache" if applicable.
1053 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1055 enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1060 * Set Expires to about 10 min into the future so it'll get reloaded
1061 * occasionally, e.g. if IJB gets upgraded.
1064 get_http_time(0, buf);
1065 enlist_unique_header(rsp->headers, "Date", buf);
1067 /* Some date in the past. */
1068 enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1070 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1071 enlist_unique_header(rsp->headers, "Expires", buf);
1076 * Compliant browsers should not cache this due to the "Cache-Control"
1077 * setting. However, to be certain, we also set both "Last-Modified"
1078 * and "Expires" to the current time.
1080 enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1081 get_http_time(0, buf);
1082 enlist_unique_header(rsp->headers, "Date", buf);
1083 enlist_unique_header(rsp->headers, "Last-Modified", buf);
1084 enlist_unique_header(rsp->headers, "Expires", buf);
1091 if (NULL == (rsp->head = list_to_text(rsp->headers)))
1093 free_http_response(rsp);
1096 rsp->head_length = strlen(rsp->head);
1103 /*********************************************************************
1105 * Function : alloc_http_response
1107 * Description : Allocates a new http_response structure.
1111 * Returns : pointer to a new http_response, or NULL.
1113 *********************************************************************/
1114 struct http_response * alloc_http_response(void)
1116 return (struct http_response *) zalloc(sizeof(struct http_response));
1120 /*********************************************************************
1122 * Function : free_http_response
1124 * Description : Free the memory occupied by an http_response
1125 * and its depandant structures.
1128 * 1 : rsp = pointer to http_response to be freed
1132 *********************************************************************/
1133 void free_http_response(struct http_response *rsp)
1140 destroy_list(rsp->headers);
1147 /*********************************************************************
1149 * Function : fill_template
1151 * Description : CGI support function that loads a given HTML
1152 * template from the confdir, and fills it in
1153 * by replacing @name@ with value using pcrs,
1154 * for each item in the output map.
1157 * 1 : csp = Current client state (buffers, headers, etc...)
1158 * 3 : template = name of the HTML template to be used
1160 * Returns : char * with loaded template, or NULL if failure
1162 *********************************************************************/
1163 char *template_load(struct client_state *csp, const char *templatename)
1165 char buf[BUFFER_SIZE];
1166 char *file_buffer = NULL;
1170 * Open template file or fail
1172 snprintf(buf, BUFFER_SIZE, "%s/templates/%s", csp->config->confdir, templatename);
1174 if(NULL == (fp = fopen(buf, "r")))
1176 log_error(LOG_LEVEL_ERROR, "error loading template %s: %E", buf);
1182 * Read the file, ignoring comments
1184 while (fgets(buf, BUFFER_SIZE, fp))
1186 /* skip lines starting with '#' */
1192 file_buffer = strsav(file_buffer, buf);
1196 return(file_buffer);
1200 /*********************************************************************
1202 * Function : fill_template
1204 * Description : CGI support function that loads a given HTML
1205 * template from the confdir, and fills it in
1206 * by replacing @name@ with value using pcrs,
1207 * for each item in the output map.
1210 * 1 : template_ptr = IN: Template to be filled out.
1212 * OUT: Filled out template.
1213 * Caller must free().
1214 * 2 : exports = map with fill in symbol -> name pairs
1218 *********************************************************************/
1219 void template_fill(char ** template_ptr, struct map *exports)
1221 struct map_entry *m;
1223 char buf[BUFFER_SIZE];
1224 char *tmp_out_buffer;
1230 assert(template_ptr);
1231 assert(*template_ptr);
1234 file_buffer = *template_ptr;
1235 size = strlen(file_buffer) + 1;
1238 * Assemble pcrs joblist from exports map
1240 for (m = exports->first; m != NULL; m = m->next)
1242 if (*m->name == '$')
1245 * First character of name is '$', so remove this flag
1246 * character and allow backreferences ($1 etc) in the
1247 * "replace with" text.
1249 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1255 * Treat the "replace with" text as a literal string -
1256 * no quoting needed, no backreferences allowed.
1257 * ("Trivial" ['T'] flag).
1261 /* Enclose name in @@ */
1262 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1266 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1268 /* Make and run job. */
1269 job = pcrs_compile(buf, m->value, flags, &error);
1272 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1276 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1277 if (file_buffer != tmp_out_buffer)
1280 file_buffer = tmp_out_buffer;
1289 *template_ptr = file_buffer;
1293 /*********************************************************************
1295 * Function : default_exports
1297 * Description : returns a struct map list that contains exports
1298 * which are common to all CGI functions.
1301 * 1 : exports = Structure to write output to. This
1302 * structure should be newly allocated and will be
1304 * 1 : csp = Current client state (buffers, headers, etc...)
1305 * 2 : caller = name of CGI who calls us and which should
1306 * be excluded from the generated menu.
1307 * Returns : NULL if no memory, else map
1309 *********************************************************************/
1310 struct map * default_exports(const struct client_state *csp, const char *caller)
1313 struct map * exports = new_map();
1315 map(exports, "version", 1, VERSION, 1);
1316 map(exports, "my-ip-address", 1, csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown", 1);
1317 map(exports, "my-hostname", 1, csp->my_hostname ? csp->my_hostname : "unknown", 1);
1318 map(exports, "admin-address", 1, csp->config->admin_address ? csp->config->admin_address : "fill@me.in.please", 1);
1319 map(exports, "homepage", 1, HOME_PAGE_URL, 1);
1320 map(exports, "default-cgi", 1, HOME_PAGE_URL "/config", 1);
1321 map(exports, "menu", 1, make_menu(caller), 0);
1322 map(exports, "code-status", 1, CODE_STATUS, 1);
1324 snprintf(buf, 20, "%d", csp->config->hport);
1325 map(exports, "my-port", 1, buf, 1);
1327 if(!strcmp(CODE_STATUS, "stable"))
1329 map_block_killer(exports, "unstable");
1332 if(csp->config->proxy_info_url != NULL)
1334 map(exports, "proxy-info-url", 1, csp->config->proxy_info_url, 1);
1338 map_block_killer(exports, "have-proxy-info");
1345 /*********************************************************************
1347 * Function : map_block_killer
1349 * Description : Convenience function.
1350 * Adds a "killer" for the conditional HTML-template
1351 * block <name>, i.e. a substitution of the regex
1352 * "if-<name>-start.*if-<name>-end" to the given
1356 * 1 : exports = map to extend
1357 * 2 : name = name of conditional block
1359 * Returns : extended map
1361 *********************************************************************/
1362 void map_block_killer(struct map *exports, const char *name)
1364 char buf[1000]; /* Will do, since the names are hardwired */
1366 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1367 map(exports, buf, 1, "", 1);
1371 /*********************************************************************
1373 * Function : map_conditional
1375 * Description : Convenience function.
1376 * Adds an "if-then-else" for the conditional HTML-template
1377 * block <name>, i.e. a substitution of the form:
1384 * The control structure and one of the alternatives
1388 * 1 : exports = map to extend
1389 * 2 : name = name of conditional block
1390 * 3 : choose_first = nonzero for first, zero for second.
1392 * Returns : extended map
1394 *********************************************************************/
1395 void map_conditional(struct map *exports, const char *name, int choose_first)
1397 char buf[1000]; /* Will do, since the names are hardwired */
1399 snprintf(buf, 1000, (choose_first
1400 ? "else-not-%s@.*@endif-%s"
1401 : "if-%s-then@.*@else-not-%s"),
1403 map(exports, buf, 1, "", 1);
1405 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1406 map(exports, buf, 1, "", 1);
1410 /*********************************************************************
1412 * Function : make_menu
1414 * Description : Returns an HTML-formatted menu of the available
1415 * unhidden CGIs, excluding the one given in <self>.
1417 * Parameters : self = name of CGI to leave out, can be NULL
1419 * Returns : menu string
1421 *********************************************************************/
1422 char *make_menu(const char *self)
1424 const struct cgi_dispatcher *d;
1425 char buf[BUFFER_SIZE];
1426 char *result = NULL;
1430 self = "NO-SUCH-CGI!";
1433 /* List available unhidden CGI's and export as "other-cgis" */
1434 for (d = cgi_dispatcher; d->handler; d++)
1436 if (strncmp(d->description, "HIDE", 4) && strcmp(d->name, self))
1438 snprintf(buf, BUFFER_SIZE, "<li><a href=%s/config/%s>%s</a></li>\n",
1439 HOME_PAGE_URL, d->name, d->description);
1440 result = strsav(result, buf);
1448 /*********************************************************************
1450 * Function : dump_map
1452 * Description : HTML-dump a map for debugging
1455 * 1 : the_map = map to dump
1457 * Returns : string with HTML
1459 *********************************************************************/
1460 char *dump_map(const struct map *the_map)
1462 struct map_entry *cur_entry = the_map->first;
1465 ret = strsav(ret, "<table>\n");
1469 ret = strsav(ret, "<tr><td><b>");
1470 ret = strsav(ret, cur_entry->name);
1471 ret = strsav(ret, "</b></td><td>");
1472 ret = strsav(ret, cur_entry->value);
1473 ret = strsav(ret, "</td></tr>\n");
1474 cur_entry = cur_entry->next;
1477 ret = strsav(ret, "</table>\n");
1483 /*********************************************************************
1485 * Function : cgi_robots_txt
1487 * Description : CGI function to return "/robots.txt".
1490 * 1 : csp = Current client state (buffers, headers, etc...)
1491 * 2 : rsp = http_response data structure for output
1492 * 3 : parameters = map of cgi parameters
1494 * CGI Parameters : None
1498 *********************************************************************/
1499 int cgi_robots_txt(struct client_state *csp, struct http_response *rsp,
1500 struct map *parameters)
1505 "# This is the Internet Junkbuster control interface.\n"
1506 "# It isn't very useful to index it, and you're likely to break stuff.\n"
1513 enlist_unique(rsp->headers, "Content-Type: text/plain", 13);
1517 get_http_time(7 * 24 * 60 * 60, buf); /* 7 days into future */
1518 enlist_unique_header(rsp->headers, "Expires", buf);