1 const char cgi_rcs[] = "$Id: cgi.c,v 1.23 2001/09/16 11:16:05 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.23 2001/09/16 11:16:05 jongfoster
40 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
42 * Revision 1.22 2001/09/16 11:00:10 jongfoster
43 * New function alloc_http_response, for symmetry with free_http_response
45 * Revision 1.21 2001/09/13 23:53:03 jongfoster
46 * Support for both static and dynamically generated CGI pages.
47 * Correctly setting Last-Modified: and Expires: HTTP headers.
49 * Revision 1.20 2001/09/13 23:40:36 jongfoster
50 * (Cosmetic only) Indentation correction
52 * Revision 1.19 2001/09/13 23:31:25 jongfoster
53 * Moving image data to cgi.c rather than cgi.h.
55 * Revision 1.18 2001/08/05 16:06:20 jongfoster
56 * Modifiying "struct map" so that there are now separate header and
57 * "map_entry" structures. This means that functions which modify a
58 * map no longer need to return a pointer to the modified map.
59 * Also, it no longer reverses the order of the entries (which may be
60 * important with some advanced template substitutions).
62 * Revision 1.17 2001/08/05 15:57:38 oes
63 * Adapted finish_http_response to new list_to_text
65 * Revision 1.16 2001/08/01 21:33:18 jongfoster
66 * Changes to fill_template() that reduce memory usage without having
67 * an impact on performance. I also renamed some variables so as not
68 * to clash with the C++ keywords "new" and "template".
70 * Revision 1.15 2001/08/01 21:19:22 jongfoster
71 * Moving file version information to a separate CGI page.
73 * Revision 1.14 2001/08/01 00:19:03 jongfoster
74 * New function: map_conditional() for an if-then-else syntax.
75 * Changing to use new version of show_defines()
77 * Revision 1.13 2001/07/30 22:08:36 jongfoster
78 * Tidying up #defines:
79 * - All feature #defines are now of the form FEATURE_xxx
80 * - Permanently turned off WIN_GUI_EDIT
81 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
83 * Revision 1.12 2001/07/29 18:47:05 jongfoster
84 * Adding missing #include "loadcfg.h"
86 * Revision 1.11 2001/07/18 17:24:37 oes
87 * Changed to conform to new pcrs interface
89 * Revision 1.10 2001/07/13 13:53:13 oes
90 * Removed all #ifdef PCRS and related code
92 * Revision 1.9 2001/06/29 21:45:41 oes
93 * Indentation, CRLF->LF, Tab-> Space
95 * Revision 1.8 2001/06/29 13:21:46 oes
96 * - Cosmetics: renamed and reordered functions, variables,
97 * texts, improved comments etc
99 * - Removed ij_untrusted_url() The relevant
100 * info is now part of the "untrusted" page,
101 * which is generated by filters.c:trust_url()
103 * - Generators of content now call finish_http_response()
104 * themselves, making jcc.c:chat() a little less
107 * - Removed obsolete "Pragma: no-cache" from our headers
109 * - http_responses now know their head length
111 * - fill_template now uses the new interface to pcrs, so that
112 * - long jobs (like whole files) no longer have to be assembled
113 * in a fixed size buffer
114 * - the new T (trivial) option is used, and the replacement may
115 * contain Perl syntax backrefs without confusing pcrs
117 * - Introduced default_exports() which generates a set of exports
118 * common to all CGIs and other content generators
120 * - Introduced convenience function map_block_killer()
122 * - Introduced convenience function make_menu()
124 * - Introduced CGI-like function error_response() which generates
125 * the "No such domain" and "Connect failed" messages using the
128 * - cgi_show_url_info:
129 * - adapted to new CGI features
130 * - form and answers now generated from same template
131 * - http:// prefix in URL now OK
134 * - adapted to new CGI features
135 * - no longer uses csp->init_proxy_args
138 * - moved menu generation to make_menu()
140 * - add_stats now writes single export map entries instead
143 * - Moved redirect_url() to filters.c
145 * - Fixed mem leak in free_http_response(), map_block_killer(),
147 * - Removed logentry from cancelled commit
149 * Revision 1.7 2001/06/09 10:51:58 jongfoster
150 * Changing "show URL info" handler to new style.
151 * Changing BUFSIZ ==> BUFFER_SIZE
153 * Revision 1.6 2001/06/07 23:05:19 jongfoster
154 * Removing code related to old forward and ACL files.
156 * Revision 1.5 2001/06/05 19:59:16 jongfoster
157 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
159 * Revision 1.4 2001/06/04 10:41:52 swa
160 * show version string of cgi.h and cgi.c
162 * Revision 1.3 2001/06/03 19:12:16 oes
163 * introduced new cgi handling
165 * No revisions before 1.3
167 **********************************************************************/
173 #include <sys/types.h>
180 #define snprintf _snprintf
181 #endif /* def _WIN32 */
192 #include "miscutil.h"
193 #include "showargs.h"
196 const char cgi_h_rcs[] = CGI_H_VERSION;
198 const struct cgi_dispatcher cgi_dispatcher[] = {
201 "Show information about the current configuration" },
203 13, cgi_show_url_info,
204 "Show which actions apply to a URL and why" },
206 12, cgi_show_version,
207 "Show the source code version numbers" },
210 "HIDE Send the transparent or \"Junkbuster\" gif" },
213 "Junkbuster main page" },
214 { NULL, 0, NULL, NULL }
221 * Hint: You can encode your own GIFs like that:
222 * perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o,", unpack("C", $c)); }'
225 const char image_junkbuster_gif_data[] =
226 "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
227 "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
228 "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
229 "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
230 "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
231 "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
232 "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
235 const int image_junkbuster_gif_length = sizeof(image_junkbuster_gif_data) - 1;
238 const char image_blank_gif_data[] =
239 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
240 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
241 "\000\001\000\000\002\002D\001\000;";
243 const int image_blank_gif_length = sizeof(image_blank_gif_data) - 1;
246 /*********************************************************************
248 * Function : dispatch_cgi
250 * Description : Checks if a request URL has either the magical hostname
251 * i.j.b or matches HOME_PAGE_URL/config/. If so, it parses
252 * the (rest of the) path as a cgi name plus query string,
253 * prepares a map that maps CGI parameter names to their values,
254 * initializes the http_response struct, and calls the
255 * relevant CGI handler function.
258 * 1 : csp = Current client state (buffers, headers, etc...)
260 * Returns : http_response if match, NULL if nonmatch or handler fail
262 *********************************************************************/
263 struct http_response *dispatch_cgi(struct client_state *csp)
265 char *argstring = NULL;
266 const struct cgi_dispatcher *d;
267 struct map *param_list;
268 struct http_response *rsp;
271 * Should we intercept ?
274 /* Either the host matches CGI_PREFIX_HOST ..*/
275 if (0 == strcmpic(csp->http->host, CGI_PREFIX_HOST))
277 /* ..then the path will all be for us */
278 argstring = csp->http->path;
280 /* Or it's the host part HOME_PAGE_URL, and the path /config ? */
281 else if ( (0 == strcmpic(csp->http->host, HOME_PAGE_URL + 7 ))
282 && (0 == strncmpic(csp->http->path,"/config", 7))
283 && ((csp->http->path[7] == '/') || (csp->http->path[7] == '\0')))
285 /* then it's everything following "/config" */
286 argstring = csp->http->path + 7;
294 * This is a CGI call.
297 /* Get mem for response or fail*/
298 if (NULL == (rsp = alloc_http_response()))
303 /* Remove leading slash */
304 if (*argstring == '/')
309 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
310 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
311 csp->ip_addr_str, csp->http->cmd);
313 /* Find and start the right CGI function*/
314 for (d = cgi_dispatcher; d->handler; d++)
316 if (strncmp(argstring, d->name, d->name_length) == 0)
318 if (NULL == (param_list =
319 parse_cgi_parameters(argstring + d->name_length)))
321 free_map(param_list);
322 free_http_response(rsp);
325 if ((d->handler)(csp, rsp, param_list))
327 free_map(param_list);
328 free_http_response(rsp);
332 free_map(param_list);
333 return(finish_http_response(rsp));
337 /* Can't get here, since cgi_default will match all requests */
338 free_http_response(rsp);
343 /*********************************************************************
345 * Function : parse_cgi_parameters
347 * Description : Parse a URL-encoded argument string into name/value
348 * pairs and store them in a struct map list.
351 * 1 : string = string to be parsed
353 * Returns : pointer to param list, or NULL if out of memory.
355 *********************************************************************/
356 struct map *parse_cgi_parameters(char *argstring)
359 char *vector[BUFFER_SIZE];
361 struct map *cgi_params;
363 if (NULL == (cgi_params = new_map()))
368 if(*argstring == '?')
372 if (NULL == (tmp = strdup(argstring)))
374 free_map(cgi_params);
378 pairs = ssplit(tmp, "&", vector, SZ(vector), 1, 1);
380 for (i = 0; i < pairs; i++)
382 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
385 map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0);
395 /*********************************************************************
397 * Function : cgi_default
399 * Description : CGI function that is called if no action was given.
400 * Lists menu of available unhidden CGIs.
403 * 1 : csp = Current client state (buffers, headers, etc...)
404 * 2 : rsp = http_response data structure for output
405 * 3 : parameters = map of cgi parameters
409 *********************************************************************/
410 int cgi_default(struct client_state *csp, struct http_response *rsp,
411 struct map *parameters)
415 struct map * exports = default_exports(csp, "");
417 /* If there were other parameters, export a dump as "cgi-parameters" */
420 p = dump_map(parameters);
421 tmp = strsav(tmp, "<p>What made you think this cgi takes parameters?\n"
422 "Anyway, here they are, in case you're interested:</p>\n");
423 tmp = strsav(tmp, p);
424 map(exports, "cgi-parameters", 1, tmp, 0);
429 map(exports, "cgi-parameters", 1, "", 1);
432 rsp->body = template_load(csp, "default");
433 template_fill(&rsp->body, exports);
440 /*********************************************************************
442 * Function : cgi_send_banner
444 * Description : CGI function that returns a banner.
447 * 1 : csp = Current client state (buffers, headers, etc...)
448 * 2 : rsp = http_response data structure for output
449 * 3 : parameters = map of cgi parameters
452 * type : Selects the type of banner between "trans" and "jb".
453 * Defaults to "jb" if absent or != "trans".
457 *********************************************************************/
458 int cgi_send_banner(struct client_state *csp, struct http_response *rsp,
459 struct map *parameters)
461 if(strcmp(lookup(parameters, "type"), "trans"))
463 rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
464 rsp->content_length = image_junkbuster_gif_length;
468 rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
469 rsp->content_length = image_blank_gif_length;
472 enlist(rsp->headers, "Content-Type: image/gif");
480 /*********************************************************************
482 * Function : cgi_show_version
484 * Description : CGI function that returns a a web page describing the
485 * file versions of IJB.
488 * 1 : csp = Current client state (buffers, headers, etc...)
489 * 2 : rsp = http_response data structure for output
490 * 3 : parameters = map of cgi parameters
493 * type : Selects the type of banner between "trans" and "jb".
494 * Defaults to "jb" if absent or != "trans".
498 *********************************************************************/
499 int cgi_show_version(struct client_state *csp, struct http_response *rsp,
500 struct map *parameters)
502 struct map * exports = default_exports(csp, "show-version");
504 map(exports, "sourceversions", 1, show_rcs(), 0);
506 rsp->body = template_load(csp, "show-version");
507 template_fill(&rsp->body, exports);
514 /*********************************************************************
516 * Function : cgi_show_status
518 * Description : CGI function that returns a a web page describing the
519 * current status of IJB.
522 * 1 : csp = Current client state (buffers, headers, etc...)
523 * 2 : rsp = http_response data structure for output
524 * 3 : parameters = map of cgi parameters
527 * type : Selects the type of banner between "trans" and "jb".
528 * Defaults to "jb" if absent or != "trans".
532 *********************************************************************/
533 int cgi_show_status(struct client_state *csp, struct http_response *rsp,
534 struct map *parameters)
540 char buf[BUFFER_SIZE];
542 const char * filename = NULL;
543 char * file_description = NULL;
545 struct map * exports = default_exports(csp, "show-status");
547 switch (*(lookup(parameters, "file")))
550 if (csp->actions_list)
552 filename = csp->actions_list->filename;
553 file_description = "Actions List";
560 filename = csp->rlist->filename;
561 file_description = "Regex Filter List";
569 filename = csp->tlist->filename;
570 file_description = "Trust List";
573 #endif /* def FEATURE_TRUST */
576 if (NULL != filename)
578 map(exports, "file-description", 1, file_description, 1);
579 map(exports, "filepath", 1, html_encode(filename), 0);
581 if ((fp = fopen(filename, "r")) == NULL)
583 map(exports, "content", 1, "<h1>ERROR OPENING FILE!</h1>", 1);
587 while (fgets(buf, sizeof(buf), fp))
589 p = html_encode(buf);
594 s = strsav(s, "<br>");
598 map(exports, "contents", 1, s, 0);
600 rsp->body = template_load(csp, "show-status-file");
601 template_fill(&rsp->body, exports);
607 map(exports, "redirect-url", 1, REDIRECT_URL, 1);
610 for (i=0; i < Argc; i++)
612 s = strsav(s, Argv[i]);
615 map(exports, "invocation", 1, s, 0);
617 map(exports, "options", 1, csp->config->proxy_args, 1);
618 show_defines(exports);
620 #ifdef FEATURE_STATISTICS
622 #else /* ndef FEATURE_STATISTICS */
623 map_block_killer(exports, "statistics");
624 #endif /* ndef FEATURE_STATISTICS */
626 if (csp->actions_list)
628 map(exports, "actions-filename", 1, csp->actions_list->filename, 1);
632 map(exports, "actions-filename", 1, "None specified", 1);
637 map(exports, "re-filter-filename", 1, csp->rlist->filename, 1);
641 map(exports, "re-filter-filename", 1, "None specified", 1);
647 map(exports, "trust-filename", 1, csp->tlist->filename, 1);
651 map(exports, "trust-filename", 1, "None specified", 1);
654 map_block_killer(exports, "trust-support");
655 #endif /* ndef FEATURE_TRUST */
657 rsp->body = template_load(csp, "show-status");
658 template_fill(&rsp->body, exports);
665 /*********************************************************************
667 * Function : cgi_show_url_info
669 * Description : CGI function that determines and shows which actions
670 * junkbuster will perform for a given url, and which
671 * matches starting from the defaults have lead to that.
674 * 1 : csp = Current client state (buffers, headers, etc...)
675 * 2 : rsp = http_response data structure for output
676 * 3 : parameters = map of cgi parameters
679 * url : The url whose actions are to be determined.
680 * If url is unset, the url-given conditional will be
681 * set, so that all but the form can be suppressed in
686 *********************************************************************/
687 int cgi_show_url_info(struct client_state *csp, struct http_response *rsp,
688 struct map *parameters)
692 struct map * exports = default_exports(csp, "show-url-info");
694 if (NULL == (url_param = strdup(lookup(parameters, "url"))) || *url_param == '\0')
696 map_block_killer(exports, "url-given");
697 map(exports, "url", 1, "", 1);
701 char *matches = NULL;
706 struct file_list *fl;
707 struct url_actions *b;
708 struct url_spec url[1];
709 struct current_action_spec action[1];
712 host += (strncmp(url_param, "http://", 7)) ? 0 : 7;
714 map(exports, "url", 1, host, 1);
715 map(exports, "url-html", 1, html_encode(host), 0);
717 init_current_action(action);
719 s = current_action_to_text(action);
720 map(exports, "default", 1, s , 0);
722 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
724 map(exports, "matches", 1, "none" , 1);
725 map(exports, "final", 1, lookup(exports, "default"), 1);
728 free_current_action(action);
730 rsp->body = template_load(csp, "show-url-info");
731 template_fill(&rsp->body, exports);
737 s = strchr(host, '/');
747 s = strchr(host, ':');
757 /* if splitting the domain fails, punt */
758 if (url->dbuf == NULL)
760 map(exports, "matches", 1, "none" , 1);
761 map(exports, "final", 1, lookup(exports, "default"), 1);
765 free_current_action(action);
767 rsp->body = template_load(csp, "show-url-info");
768 template_fill(&rsp->body, exports);
774 for (b = b->next; NULL != b; b = b->next)
776 if ((b->url->port == 0) || (b->url->port == port))
778 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
780 if ((b->url->path == NULL) ||
782 (regexec(b->url->preg, path, 0, NULL, 0) == 0)
784 (strncmp(b->url->path, path, b->url->pathlen) == 0)
788 s = actions_to_text(b->action);
789 matches = strsav(matches, "<b>{");
790 matches = strsav(matches, s);
791 matches = strsav(matches, " }</b><br>\n<code>");
792 matches = strsav(matches, b->url->spec);
793 matches = strsav(matches, "</code><br>\n<br>\n");
796 merge_current_action(action, b->action);
805 map(exports, "matches", 1, matches , 0);
809 map(exports, "matches", 1, "none", 1);
819 s = current_action_to_text(action);
820 map(exports, "final", 1, s, 0);
823 free_current_action(action);
826 rsp->body = template_load(csp, "show-url-info");
827 template_fill(&rsp->body, exports);
834 /*********************************************************************
836 * Function : error_response
838 * Description : returns an http_response that explains the reason
839 * why a request failed.
842 * 1 : csp = Current client state (buffers, headers, etc...)
843 * 2 : templatename = Which template should be used for the answer
844 * 3 : errno = system error number
846 * Returns : NULL if no memory, else http_response
848 *********************************************************************/
849 struct http_response *error_response(struct client_state *csp, const char *templatename, int err)
851 struct http_response *rsp;
852 struct map * exports = default_exports(csp, NULL);
854 if (NULL == (rsp = alloc_http_response()))
859 map(exports, "host-html", 1, html_encode(csp->http->host), 0);
860 map(exports, "hostport", 1, csp->http->hostport, 1);
861 map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
862 map(exports, "path", 1, csp->http->path, 1);
863 map(exports, "path-html", 1, html_encode(csp->http->path), 0);
864 map(exports, "error", 1, safe_strerror(err), 0);
865 map(exports, "host-ip", 1, csp->http->host_ip_addr_str, 1);
867 rsp->body = template_load(csp, templatename);
868 template_fill(&rsp->body, exports);
871 if (!strcmp(templatename, "no-such-domain"))
873 rsp->status = strdup("404 No such domain");
875 else if (!strcmp(templatename, "connect-failed"))
877 rsp->status = strdup("503 Connect failed");
880 return(finish_http_response(rsp));
884 /*********************************************************************
886 * Function : get_http_time
888 * Description : Get the time in a format suitable for use in a
889 * HTTP header - e.g.:
890 * "Sun, 06 Nov 1994 08:49:37 GMT"
893 * 1 : time_offset = Time returned will be current time
894 * plus this number of seconds.
895 * 2 : buf = Destination for result. Must be long enough
896 * to hold 29 characters plus a trailing zero.
900 *********************************************************************/
901 static void get_http_time(int time_offset, char * buf)
903 static const char day_names[7][4] =
904 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
905 static const char month_names[12][4] =
906 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
907 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
914 time(¤t_time); /* get current time */
916 /* FIXME: is this needed? time() can't fail on Win32. What about Linux?
917 if(current_time <= 0)
923 current_time += time_offset;
925 /* get and save the gmt */
926 t = gmtime(¤t_time);
928 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
930 "%s, %02d %s %4d %02d:%02d:%02d GMT",
931 day_names[t->tm_wday],
933 month_names[t->tm_mon],
943 /*********************************************************************
945 * Function : finish_http_response
947 * Description : Fill in the missing headers in an http response,
948 * and flatten the headers to an http head.
951 * 1 : rsp = pointer to http_response to be processed
953 * Returns : http_response, or NULL on failiure
955 *********************************************************************/
956 struct http_response *finish_http_response(struct http_response *rsp)
958 char buf[BUFFER_SIZE];
961 * Fill in the HTTP Status
963 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
964 enlist_first(rsp->headers, buf);
967 * Set the Content-Length
969 if (rsp->content_length == 0)
971 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
973 sprintf(buf, "Content-Length: %d", rsp->content_length);
974 enlist(rsp->headers, buf);
977 * Fill in the default headers:
979 * Content-Type: default to text/html if not already specified.
980 * Date: set to current date/time.
981 * Last-Modified: set to date/time the page was last changed.
982 * Expires: set to date/time page next needs reloading.
983 * Cache-Control: set to "no-cache" if applicable.
985 * See http://www.w3.org/Protocols/rfc2068/rfc2068
987 enlist_unique(rsp->headers, "Content-Type: text/html", 13);
992 * Set Expires to about 10 min into the future so it'll get reloaded
993 * occasionally, e.g. if IJB gets upgraded.
996 get_http_time(0, buf);
997 enlist_unique_header(rsp->headers, "Date", buf);
999 /* Some date in the past. */
1000 enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1002 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1003 enlist_unique_header(rsp->headers, "Expires", buf);
1008 * Compliant browsers should not cache this due to the "Cache-Control"
1009 * setting. However, to be certain, we also set both "Last-Modified"
1010 * and "Expires" to the current time.
1012 enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1013 get_http_time(0, buf);
1014 enlist_unique_header(rsp->headers, "Date", buf);
1015 enlist_unique_header(rsp->headers, "Last-Modified", buf);
1016 enlist_unique_header(rsp->headers, "Expires", buf);
1023 if (NULL == (rsp->head = list_to_text(rsp->headers)))
1025 free_http_response(rsp);
1028 rsp->head_length = strlen(rsp->head);
1035 /*********************************************************************
1037 * Function : alloc_http_response
1039 * Description : Allocates a new http_response structure.
1043 * Returns : pointer to a new http_response, or NULL.
1045 *********************************************************************/
1046 struct http_response * alloc_http_response(void)
1048 return (struct http_response *) zalloc(sizeof(struct http_response));
1052 /*********************************************************************
1054 * Function : free_http_response
1056 * Description : Free the memory occupied by an http_response
1057 * and its depandant structures.
1060 * 1 : rsp = pointer to http_response to be freed
1064 *********************************************************************/
1065 void free_http_response(struct http_response *rsp)
1072 destroy_list(rsp->headers);
1079 /*********************************************************************
1081 * Function : fill_template
1083 * Description : CGI support function that loads a given HTML
1084 * template from the confdir, and fills it in
1085 * by replacing @name@ with value using pcrs,
1086 * for each item in the output map.
1089 * 1 : csp = Current client state (buffers, headers, etc...)
1090 * 3 : template = name of the HTML template to be used
1092 * Returns : char * with loaded template, or NULL if failure
1094 *********************************************************************/
1095 char *template_load(struct client_state *csp, const char *templatename)
1097 char buf[BUFFER_SIZE];
1098 char *file_buffer = NULL;
1102 * Open template file or fail
1104 snprintf(buf, BUFFER_SIZE, "%s/templates/%s", csp->config->confdir, templatename);
1106 if(NULL == (fp = fopen(buf, "r")))
1108 log_error(LOG_LEVEL_ERROR, "error loading template %s: %E", buf);
1114 * Read the file, ignoring comments
1116 while (fgets(buf, BUFFER_SIZE, fp))
1118 /* skip lines starting with '#' */
1124 file_buffer = strsav(file_buffer, buf);
1128 return(file_buffer);
1132 /*********************************************************************
1134 * Function : fill_template
1136 * Description : CGI support function that loads a given HTML
1137 * template from the confdir, and fills it in
1138 * by replacing @name@ with value using pcrs,
1139 * for each item in the output map.
1142 * 1 : template_ptr = IN: Template to be filled out.
1144 * OUT: Filled out template.
1145 * Caller must free().
1146 * 2 : exports = map with fill in symbol -> name pairs
1150 *********************************************************************/
1151 void template_fill(char ** template_ptr, struct map *exports)
1153 struct map_entry *m;
1155 char buf[BUFFER_SIZE];
1156 char *tmp_out_buffer;
1162 assert(template_ptr);
1163 assert(*template_ptr);
1166 file_buffer = *template_ptr;
1167 size = strlen(file_buffer) + 1;
1170 * Assemble pcrs joblist from exports map
1172 for (m = exports->first; m != NULL; m = m->next)
1174 if (*m->name == '$')
1177 * First character of name is '$', so remove this flag
1178 * character and allow backreferences ($1 etc) in the
1179 * "replace with" text.
1181 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1187 * Treat the "replace with" text as a literal string -
1188 * no quoting needed, no backreferences allowed.
1189 * ("Trivial" ['T'] flag).
1193 /* Enclose name in @@ */
1194 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1198 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1200 /* Make and run job. */
1201 job = pcrs_compile(buf, m->value, flags, &error);
1204 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1208 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1209 if (file_buffer != tmp_out_buffer)
1212 file_buffer = tmp_out_buffer;
1221 *template_ptr = file_buffer;
1225 /*********************************************************************
1227 * Function : default_exports
1229 * Description : returns a struct map list that contains exports
1230 * which are common to all CGI functions.
1233 * 1 : exports = Structure to write output to. This
1234 * structure should be newly allocated and will be
1236 * 1 : csp = Current client state (buffers, headers, etc...)
1237 * 2 : caller = name of CGI who calls us and which should
1238 * be excluded from the generated menu.
1239 * Returns : NULL if no memory, else map
1241 *********************************************************************/
1242 struct map * default_exports(const struct client_state *csp, const char *caller)
1245 struct map * exports = new_map();
1247 map(exports, "version", 1, VERSION, 1);
1248 map(exports, "my-ip-address", 1, csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown", 1);
1249 map(exports, "my-hostname", 1, csp->my_hostname ? csp->my_hostname : "unknown", 1);
1250 map(exports, "admin-address", 1, csp->config->admin_address ? csp->config->admin_address : "fill@me.in.please", 1);
1251 map(exports, "homepage", 1, HOME_PAGE_URL, 1);
1252 map(exports, "default-cgi", 1, HOME_PAGE_URL "/config", 1);
1253 map(exports, "menu", 1, make_menu(caller), 0);
1254 map(exports, "code-status", 1, CODE_STATUS, 1);
1256 snprintf(buf, 20, "%d", csp->config->hport);
1257 map(exports, "my-port", 1, buf, 1);
1259 if(!strcmp(CODE_STATUS, "stable"))
1261 map_block_killer(exports, "unstable");
1264 if(csp->config->proxy_info_url != NULL)
1266 map(exports, "proxy-info-url", 1, csp->config->proxy_info_url, 1);
1270 map_block_killer(exports, "have-proxy-info");
1277 /*********************************************************************
1279 * Function : map_block_killer
1281 * Description : Convenience function.
1282 * Adds a "killer" for the conditional HTML-template
1283 * block <name>, i.e. a substitution of the regex
1284 * "if-<name>-start.*if-<name>-end" to the given
1288 * 1 : exports = map to extend
1289 * 2 : name = name of conditional block
1291 * Returns : extended map
1293 *********************************************************************/
1294 void map_block_killer(struct map *exports, const char *name)
1296 char buf[1000]; /* Will do, since the names are hardwired */
1298 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1299 map(exports, buf, 1, "", 1);
1303 /*********************************************************************
1305 * Function : map_conditional
1307 * Description : Convenience function.
1308 * Adds an "if-then-else" for the conditional HTML-template
1309 * block <name>, i.e. a substitution of the form:
1316 * The control structure and one of the alternatives
1320 * 1 : exports = map to extend
1321 * 2 : name = name of conditional block
1322 * 3 : choose_first = nonzero for first, zero for second.
1324 * Returns : extended map
1326 *********************************************************************/
1327 void map_conditional(struct map *exports, const char *name, int choose_first)
1329 char buf[1000]; /* Will do, since the names are hardwired */
1331 snprintf(buf, 1000, (choose_first
1332 ? "else-not-%s@.*@endif-%s"
1333 : "if-%s-then@.*@else-not-%s"),
1335 map(exports, buf, 1, "", 1);
1337 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1338 map(exports, buf, 1, "", 1);
1342 /*********************************************************************
1344 * Function : make_menu
1346 * Description : Returns an HTML-formatted menu of the available
1347 * unhidden CGIs, excluding the one given in <self>.
1349 * Parameters : self = name of CGI to leave out, can be NULL
1351 * Returns : menu string
1353 *********************************************************************/
1354 char *make_menu(const char *self)
1356 const struct cgi_dispatcher *d;
1357 char buf[BUFFER_SIZE];
1358 char *result = NULL;
1362 self = "NO-SUCH-CGI!";
1365 /* List available unhidden CGI's and export as "other-cgis" */
1366 for (d = cgi_dispatcher; d->handler; d++)
1368 if (strncmp(d->description, "HIDE", 4) && strcmp(d->name, self))
1370 snprintf(buf, BUFFER_SIZE, "<li><a href=%s/config/%s>%s</a></li>\n",
1371 HOME_PAGE_URL, d->name, d->description);
1372 result = strsav(result, buf);
1380 /*********************************************************************
1382 * Function : dump_map
1384 * Description : HTML-dump a map for debugging
1387 * 1 : the_map = map to dump
1389 * Returns : string with HTML
1391 *********************************************************************/
1392 char *dump_map(const struct map *the_map)
1394 struct map_entry *cur_entry = the_map->first;
1397 ret = strsav(ret, "<table>\n");
1401 ret = strsav(ret, "<tr><td><b>");
1402 ret = strsav(ret, cur_entry->name);
1403 ret = strsav(ret, "</b></td><td>");
1404 ret = strsav(ret, cur_entry->value);
1405 ret = strsav(ret, "</td></tr>\n");
1406 cur_entry = cur_entry->next;
1409 ret = strsav(ret, "</table>\n");
1415 #ifdef FEATURE_STATISTICS
1416 /*********************************************************************
1418 * Function : add_stats
1420 * Description : Add the blocking statistics to a given map.
1423 * 1 : exports = map to write to.
1425 * Returns : pointer to extended map
1427 *********************************************************************/
1428 struct map *add_stats(struct map *exports)
1430 float perc_rej; /* Percentage of http requests rejected */
1432 int local_urls_read = urls_read;
1433 int local_urls_rejected = urls_rejected;
1436 * Need to alter the stats not to include the fetch of this
1439 * Can't do following thread safely! doh!
1442 * urls_rejected--; * This will be incremented subsequently *
1445 if (local_urls_read == 0)
1447 map_block_killer(exports, "have-stats");
1451 map_block_killer(exports, "have-no-stats");
1453 perc_rej = (float)local_urls_rejected * 100.0F /
1454 (float)local_urls_read;
1456 sprintf(buf, "%d", local_urls_read);
1457 map(exports, "requests-received", 1, buf, 1);
1459 sprintf(buf, "%d", local_urls_rejected);
1460 map(exports, "requests-blocked", 1, buf, 1);
1462 sprintf(buf, "%6.2f", perc_rej);
1463 map(exports, "percent-blocked", 1, buf, 1);
1469 #endif /* def FEATURE_STATISTICS */