New function alloc_http_response, for symmetry with free_http_response
[privoxy.git] / cgi.c
1 const char cgi_rcs[] = "$Id: cgi.c,v 1.21 2001/09/13 23:53:03 jongfoster Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/cgi.c,v $
5  *
6  * Purpose     :  Declares functions to intercept request, generate
7  *                html or gif answers, and to compose HTTP resonses.
8  *                
9  *                Functions declared include:
10  * 
11  *
12  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
13  *                IJBSWA team.  http://ijbswa.sourceforge.net
14  *
15  *                Based on the Internet Junkbuster originally written
16  *                by and Copyright (C) 1997 Anonymous Coders and 
17  *                Junkbusters Corporation.  http://www.junkbusters.com
18  *
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.
24  *
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.
30  *
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.
36  *
37  * Revisions   :
38  *    $Log: cgi.c,v $
39  *    Revision 1.21  2001/09/13 23:53:03  jongfoster
40  *    Support for both static and dynamically generated CGI pages.
41  *    Correctly setting Last-Modified: and Expires: HTTP headers.
42  *
43  *    Revision 1.20  2001/09/13 23:40:36  jongfoster
44  *    (Cosmetic only) Indentation correction
45  *
46  *    Revision 1.19  2001/09/13 23:31:25  jongfoster
47  *    Moving image data to cgi.c rather than cgi.h.
48  *
49  *    Revision 1.18  2001/08/05 16:06:20  jongfoster
50  *    Modifiying "struct map" so that there are now separate header and
51  *    "map_entry" structures.  This means that functions which modify a
52  *    map no longer need to return a pointer to the modified map.
53  *    Also, it no longer reverses the order of the entries (which may be
54  *    important with some advanced template substitutions).
55  *
56  *    Revision 1.17  2001/08/05 15:57:38  oes
57  *    Adapted finish_http_response to new list_to_text
58  *
59  *    Revision 1.16  2001/08/01 21:33:18  jongfoster
60  *    Changes to fill_template() that reduce memory usage without having
61  *    an impact on performance.  I also renamed some variables so as not
62  *    to clash with the C++ keywords "new" and "template".
63  *
64  *    Revision 1.15  2001/08/01 21:19:22  jongfoster
65  *    Moving file version information to a separate CGI page.
66  *
67  *    Revision 1.14  2001/08/01 00:19:03  jongfoster
68  *    New function: map_conditional() for an if-then-else syntax.
69  *    Changing to use new version of show_defines()
70  *
71  *    Revision 1.13  2001/07/30 22:08:36  jongfoster
72  *    Tidying up #defines:
73  *    - All feature #defines are now of the form FEATURE_xxx
74  *    - Permanently turned off WIN_GUI_EDIT
75  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
76  *
77  *    Revision 1.12  2001/07/29 18:47:05  jongfoster
78  *    Adding missing #include "loadcfg.h"
79  *
80  *    Revision 1.11  2001/07/18 17:24:37  oes
81  *    Changed to conform to new pcrs interface
82  *
83  *    Revision 1.10  2001/07/13 13:53:13  oes
84  *    Removed all #ifdef PCRS and related code
85  *
86  *    Revision 1.9  2001/06/29 21:45:41  oes
87  *    Indentation, CRLF->LF, Tab-> Space
88  *
89  *    Revision 1.8  2001/06/29 13:21:46  oes
90  *    - Cosmetics: renamed and reordered functions, variables,
91  *      texts, improved comments  etc
92  *
93  *    - Removed ij_untrusted_url() The relevant
94  *      info is now part of the "untrusted" page,
95  *      which is generated by filters.c:trust_url()
96  *
97  *    - Generators of content now call finish_http_response()
98  *      themselves, making jcc.c:chat() a little less
99  *      cluttered
100  *
101  *    - Removed obsolete "Pragma: no-cache" from our headers
102  *
103  *    - http_responses now know their head length
104  *
105  *    - fill_template now uses the new interface to pcrs, so that
106  *       - long jobs (like whole files) no longer have to be assembled
107  *         in a fixed size buffer
108  *       - the new T (trivial) option is used, and the replacement may
109  *         contain Perl syntax backrefs without confusing pcrs
110  *
111  *    - Introduced default_exports() which generates a set of exports
112  *      common to all CGIs and other content generators
113  *
114  *    - Introduced convenience function map_block_killer()
115  *
116  *    - Introduced convenience function make_menu()
117  *
118  *    - Introduced CGI-like function error_response() which generates
119  *      the "No such domain" and "Connect failed" messages using the
120  *      CGI platform
121  *
122  *    - cgi_show_url_info:
123  *      - adapted to new CGI features
124  *      - form and answers now generated from same template
125  *      - http:// prefix in URL now OK
126  *
127  *    - cgi_show_status:
128  *      - adapted to new CGI features
129  *      - no longer uses csp->init_proxy_args
130  *
131  *    - cgi_default:
132  *      - moved menu generation to make_menu()
133  *
134  *    - add_stats now writes single export map entries instead
135  *      of a fixed string
136  *
137  *    - Moved redirect_url() to filters.c
138  *
139  *    - Fixed mem leak in free_http_response(), map_block_killer(),
140  *
141  *    - Removed logentry from cancelled commit
142  *
143  *    Revision 1.7  2001/06/09 10:51:58  jongfoster
144  *    Changing "show URL info" handler to new style.
145  *    Changing BUFSIZ ==> BUFFER_SIZE
146  *
147  *    Revision 1.6  2001/06/07 23:05:19  jongfoster
148  *    Removing code related to old forward and ACL files.
149  *
150  *    Revision 1.5  2001/06/05 19:59:16  jongfoster
151  *    Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
152  *
153  *    Revision 1.4  2001/06/04 10:41:52  swa
154  *    show version string of cgi.h and cgi.c
155  *
156  *    Revision 1.3  2001/06/03 19:12:16  oes
157  *    introduced new cgi handling
158  *
159  *    No revisions before 1.3
160  *
161  **********************************************************************/
162 \f
163
164 #include "config.h"
165
166 #include <stdio.h>
167 #include <sys/types.h>
168 #include <stdlib.h>
169 #include <ctype.h>
170 #include <string.h>
171 #include <assert.h>
172
173 #ifdef _WIN32
174 #define snprintf _snprintf
175 #endif /* def _WIN32 */
176
177 #include "project.h"
178 #include "cgi.h"
179 #include "list.h"
180 #include "encode.h"
181 #include "ssplit.h"
182 #include "jcc.h"
183 #include "filters.h"
184 #include "actions.h"
185 #include "errlog.h"
186 #include "miscutil.h"
187 #include "showargs.h"
188 #include "loadcfg.h"
189
190 const char cgi_h_rcs[] = CGI_H_VERSION;
191
192 const struct cgi_dispatcher cgi_dispatcher[] = {
193    { "show-status", 
194          11, cgi_show_status,  
195          "Show information about the current configuration" }, 
196    { "show-url-info",
197          13, cgi_show_url_info, 
198          "Show which actions apply to a URL and why"  },
199    { "show-version", 
200          12, cgi_show_version,  
201          "Show the source code version numbers" }, 
202    { "send-banner",
203          11, cgi_send_banner, 
204          "HIDE Send the transparent or \"Junkbuster\" gif" },
205    { "",
206          0, cgi_default,
207          "Junkbuster main page" },
208    { NULL, 0, NULL, NULL }
209 };
210
211
212 /*
213  * Some images
214  *
215  * Hint: You can encode your own GIFs like that:
216  * perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o,", unpack("C", $c)); }'
217  */
218
219 const char image_junkbuster_gif_data[] =
220    "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
221    "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
222    "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
223    "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
224    "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
225    "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
226    "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
227    "\037Q\000\000;";
228
229 const int image_junkbuster_gif_length = sizeof(image_junkbuster_gif_data) - 1;
230
231
232 const char image_blank_gif_data[] =
233    "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
234    "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
235    "\000\001\000\000\002\002D\001\000;";
236
237 const int image_blank_gif_length = sizeof(image_blank_gif_data) - 1;
238
239
240 /*********************************************************************
241  * 
242  * Function    :  dispatch_cgi
243  *
244  * Description :  Checks if a request URL has either the magical hostname
245  *                i.j.b or matches HOME_PAGE_URL/config/. If so, it parses
246  *                the (rest of the) path as a cgi name plus query string,
247  *                prepares a map that maps CGI parameter names to their values,
248  *                initializes the http_response struct, and calls the 
249  *                relevant CGI handler function.
250  *
251  * Parameters  :
252  *          1  :  csp = Current client state (buffers, headers, etc...)
253  *
254  * Returns     :  http_response if match, NULL if nonmatch or handler fail
255  *
256  *********************************************************************/
257 struct http_response *dispatch_cgi(struct client_state *csp)
258 {
259    char *argstring = NULL;
260    const struct cgi_dispatcher *d;
261    struct map *param_list;
262    struct http_response *rsp;
263
264    /*
265     * Should we intercept ?
266     */
267
268    /* Either the host matches CGI_PREFIX_HOST ..*/
269    if (0 == strcmpic(csp->http->host, CGI_PREFIX_HOST))
270    {
271       /* ..then the path will all be for us */
272       argstring = csp->http->path;
273    }
274    /* Or it's the host part HOME_PAGE_URL, and the path /config ? */
275    else if (   (0 == strcmpic(csp->http->host, HOME_PAGE_URL + 7 ))
276             && (0 == strncmpic(csp->http->path,"/config", 7))
277             && ((csp->http->path[7] == '/') || (csp->http->path[7] == '\0')))
278    {
279       /* then it's everything following "/config" */
280       argstring = csp->http->path + 7;
281    }
282    else
283    {
284       return NULL;
285    }
286
287    /* 
288     * This is a CGI call.
289     */
290
291    /* Get mem for response or fail*/
292    if (NULL == (rsp = alloc_http_response()))
293    {
294       return NULL;
295    }
296
297    /* Remove leading slash */
298    if (*argstring == '/')
299    {
300       argstring++;
301    }
302
303    log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
304    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", 
305                             csp->ip_addr_str, csp->http->cmd); 
306
307    /* Find and start the right CGI function*/
308    for (d = cgi_dispatcher; d->handler; d++)
309    {
310       if (strncmp(argstring, d->name, d->name_length) == 0)
311       {
312          param_list = parse_cgi_parameters(argstring + d->name_length);
313          if ((d->handler)(csp, rsp, param_list))
314          {
315             freez(rsp);
316          }
317
318          free_map(param_list);
319          return(finish_http_response(rsp));
320       }
321    }
322
323    /* Can't get here, since cgi_default will match all requests */
324    freez(rsp);
325    return(NULL);
326
327 }
328
329
330 /*********************************************************************
331  *
332  * Function    :  parse_cgi_parameters
333  *
334  * Description :  Parse a URL-encoded argument string into name/value
335  *                pairs and store them in a struct map list.
336  *
337  * Parameters  :
338  *          1  :  string = string to be parsed 
339  *
340  * Returns     :  pointer to param list
341  *
342  *********************************************************************/
343 struct map *parse_cgi_parameters(char *argstring)
344 {
345    char *tmp, *p;
346    char *vector[BUFFER_SIZE];
347    int pairs, i;
348    struct map *cgi_params = new_map();
349
350    if(*argstring == '?')
351    {
352       argstring++;
353    }
354    tmp = strdup(argstring);
355
356    pairs = ssplit(tmp, "&", vector, SZ(vector), 1, 1);
357
358    for (i = 0; i < pairs; i++)
359    {
360       if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
361       {
362          *p = '\0';
363          map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0);
364       }
365    }
366
367    free(tmp);
368    return(cgi_params);
369
370 }
371
372
373 /*********************************************************************
374  *
375  * Function    :  cgi_default
376  *
377  * Description :  CGI function that is called if no action was given.
378  *                Lists menu of available unhidden CGIs.
379  *               
380  * Parameters  :
381  *           1 :  csp = Current client state (buffers, headers, etc...)
382  *           2 :  rsp = http_response data structure for output
383  *           3 :  parameters = map of cgi parameters
384  *
385  * Returns     :  0
386  *
387  *********************************************************************/
388 int cgi_default(struct client_state *csp, struct http_response *rsp,
389                 struct map *parameters)
390 {
391    char *p;
392    char *tmp = NULL;
393    struct map * exports = default_exports(csp, "");
394
395    /* If there were other parameters, export a dump as "cgi-parameters" */
396    if(parameters)
397    {
398       p = dump_map(parameters);
399       tmp = strsav(tmp, "<p>What made you think this cgi takes parameters?\n"
400                         "Anyway, here they are, in case you're interested:</p>\n");
401       tmp = strsav(tmp, p);
402       map(exports, "cgi-parameters", 1, tmp, 0);
403       free(p);
404    }
405    else
406    {
407       map(exports, "cgi-parameters", 1, "", 1);
408    }
409
410    rsp->body = fill_template(csp, "default", exports);
411    free_map(exports);
412    return(0);
413
414 }
415
416
417 /*********************************************************************
418  *
419  * Function    :  cgi_send_banner
420  *
421  * Description :  CGI function that returns a banner. 
422  *
423  * Parameters  :
424  *           1 :  csp = Current client state (buffers, headers, etc...)
425  *           2 :  rsp = http_response data structure for output
426  *           3 :  parameters = map of cgi parameters
427  *
428  * CGI Parameters :
429  *           type : Selects the type of banner between "trans" and "jb".
430  *                  Defaults to "jb" if absent or != "trans".
431  *
432  * Returns     :  0
433  *
434  *********************************************************************/
435 int cgi_send_banner(struct client_state *csp, struct http_response *rsp,
436                     struct map *parameters)
437 {
438    if(strcmp(lookup(parameters, "type"), "trans"))
439    {
440       rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
441       rsp->content_length = image_junkbuster_gif_length;
442    }
443    else
444    {
445       rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
446       rsp->content_length = image_blank_gif_length;
447    }   
448
449    enlist(rsp->headers, "Content-Type: image/gif");
450    rsp->is_static = 1;
451
452    return(0);
453
454 }
455
456
457 /*********************************************************************
458  *
459  * Function    :  cgi_show_version
460  *
461  * Description :  CGI function that returns a a web page describing the
462  *                file versions of IJB.
463  *
464  * Parameters  :
465  *           1 :  csp = Current client state (buffers, headers, etc...)
466  *           2 :  rsp = http_response data structure for output
467  *           3 :  parameters = map of cgi parameters
468  *
469  * CGI Parameters :
470  *           type : Selects the type of banner between "trans" and "jb".
471  *                  Defaults to "jb" if absent or != "trans".
472  *
473  * Returns     :  0
474  *
475  *********************************************************************/
476 int cgi_show_version(struct client_state *csp, struct http_response *rsp,
477                      struct map *parameters)
478 {
479    struct map * exports = default_exports(csp, "show-version");
480
481    map(exports, "sourceversions", 1, show_rcs(), 0);  
482
483    rsp->body = fill_template(csp, "show-version", exports);
484    free_map(exports);
485    return(0);
486
487 }
488
489  
490 /*********************************************************************
491  *
492  * Function    :  cgi_show_status
493  *
494  * Description :  CGI function that returns a a web page describing the
495  *                current status of IJB.
496  *
497  * Parameters  :
498  *           1 :  csp = Current client state (buffers, headers, etc...)
499  *           2 :  rsp = http_response data structure for output
500  *           3 :  parameters = map of cgi parameters
501  *
502  * CGI Parameters :
503  *           type : Selects the type of banner between "trans" and "jb".
504  *                  Defaults to "jb" if absent or != "trans".
505  *
506  * Returns     :  0
507  *
508  *********************************************************************/
509 int cgi_show_status(struct client_state *csp, struct http_response *rsp,
510                     struct map *parameters)
511 {
512    char *s = NULL;
513    int i;
514
515    FILE * fp;
516    char buf[BUFFER_SIZE];
517    char * p;
518    const char * filename = NULL;
519    char * file_description = NULL;
520
521    struct map * exports = default_exports(csp, "show-status");
522
523    switch (*(lookup(parameters, "file")))
524    {
525    case 'p':
526       if (csp->actions_list)
527       {
528          filename = csp->actions_list->filename;
529          file_description = "Actions List";
530       }
531       break;
532
533    case 'r':
534       if (csp->rlist)
535       {
536          filename = csp->rlist->filename;
537          file_description = "Regex Filter List";
538       }
539       break;
540
541 #ifdef FEATURE_TRUST
542    case 't':
543       if (csp->tlist)
544       {
545          filename = csp->tlist->filename;
546          file_description = "Trust List";
547       }
548       break;
549 #endif /* def FEATURE_TRUST */
550    }
551
552    if (NULL != filename)
553    {
554       map(exports, "file-description", 1, file_description, 1);
555       map(exports, "filepath", 1, html_encode(filename), 0);
556
557       if ((fp = fopen(filename, "r")) == NULL)
558       {
559          map(exports, "content", 1, "<h1>ERROR OPENING FILE!</h1>", 1);
560       }
561       else
562       {
563          while (fgets(buf, sizeof(buf), fp))
564          {
565             p = html_encode(buf);
566             if (p)
567             {
568                s = strsav(s, p);
569                freez(p);
570                s = strsav(s, "<br>");
571             }
572          }
573          fclose(fp);
574          map(exports, "contents", 1, s, 0);
575       }
576       rsp->body = fill_template(csp, "show-status-file", exports);
577       free_map(exports);
578       return(0);
579
580    }
581
582    map(exports, "redirect-url", 1, REDIRECT_URL, 1);
583    
584    s = NULL;
585    for (i=0; i < Argc; i++)
586    {
587       s = strsav(s, Argv[i]);
588       s = strsav(s, " ");
589    }
590    map(exports, "invocation", 1, s, 0);
591
592    map(exports, "options", 1, csp->config->proxy_args, 1);
593    show_defines(exports);
594
595 #ifdef FEATURE_STATISTICS
596    add_stats(exports);
597 #else /* ndef FEATURE_STATISTICS */
598    map_block_killer(exports, "statistics");
599 #endif /* ndef FEATURE_STATISTICS */
600
601    if (csp->actions_list)
602    {
603       map(exports, "actions-filename", 1,  csp->actions_list->filename, 1);
604    }
605    else
606    {
607       map(exports, "actions-filename", 1, "None specified", 1);
608    }
609
610    if (csp->rlist)
611    {
612       map(exports, "re-filter-filename", 1,  csp->rlist->filename, 1);
613    }
614    else
615    {
616       map(exports, "re-filter-filename", 1, "None specified", 1);
617    }
618
619 #ifdef FEATURE_TRUST
620    if (csp->tlist)
621    {
622       map(exports, "trust-filename", 1,  csp->tlist->filename, 1);
623    }
624    else
625    {
626        map(exports, "trust-filename", 1, "None specified", 1);
627    }
628 #else
629    map_block_killer(exports, "trust-support");
630 #endif /* ndef FEATURE_TRUST */
631
632    rsp->body = fill_template(csp, "show-status", exports);
633    free_map(exports);
634    return(0);
635
636 }
637
638  
639  /*********************************************************************
640  *
641  * Function    :  cgi_show_url_info
642  *
643  * Description :  CGI function that determines and shows which actions
644  *                junkbuster will perform for a given url, and which
645  *                matches starting from the defaults have lead to that.
646  *
647  * Parameters  :
648  *           1 :  csp = Current client state (buffers, headers, etc...)
649  *           2 :  rsp = http_response data structure for output
650  *           3 :  parameters = map of cgi parameters
651  *
652  * CGI Parameters :
653  *            url : The url whose actions are to be determined.
654  *                  If url is unset, the url-given conditional will be
655  *                  set, so that all but the form can be suppressed in
656  *                  the template.
657  *
658  * Returns     :  0
659  *
660  *********************************************************************/
661 int cgi_show_url_info(struct client_state *csp, struct http_response *rsp,
662                       struct map *parameters)
663 {
664    char *url_param;
665    char *host = NULL;
666    struct map * exports = default_exports(csp, "show-url-info");
667
668    if (NULL == (url_param = strdup(lookup(parameters, "url"))) || *url_param == '\0')
669    {
670       map_block_killer(exports, "url-given");
671       map(exports, "url", 1, "", 1);
672    }
673    else
674    {
675       char *matches = NULL;
676       char *path;
677       char *s;
678       int port = 80;
679       int hits = 0;
680       struct file_list *fl;
681       struct url_actions *b;
682       struct url_spec url[1];
683       struct current_action_spec action[1];
684       
685       host = url_param;
686       host += (strncmp(url_param, "http://", 7)) ? 0 : 7;
687
688       map(exports, "url", 1, host, 1);
689       map(exports, "url-html", 1, html_encode(host), 0);
690
691       init_current_action(action);
692
693       s = current_action_to_text(action);
694       map(exports, "default", 1, s , 0);
695
696       if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
697       {
698          map(exports, "matches", 1, "none" , 1);
699          map(exports, "final", 1, lookup(exports, "default"), 1);
700
701          freez(url_param);
702          free_current_action(action);
703
704          rsp->body = fill_template(csp, "show-url-info", exports);
705          free_map(exports);
706
707          return 0;
708       }
709
710       s = strchr(host, '/');
711       if (s != NULL)
712       {
713          path = strdup(s);
714          *s = '\0';
715       }
716       else
717       {
718          path = strdup("");
719       }
720       s = strchr(host, ':');
721       if (s != NULL)
722       {
723          *s++ = '\0';
724          port = atoi(s);
725          s = NULL;
726       }
727
728       *url = dsplit(host);
729
730       /* if splitting the domain fails, punt */
731       if (url->dbuf == NULL)
732       {
733          map(exports, "matches", 1, "none" , 1);
734          map(exports, "final", 1, lookup(exports, "default"), 1);
735
736          freez(url_param);
737          freez(path);
738          free_current_action(action);
739
740          rsp->body = fill_template(csp, "show-url-info", exports);
741          free_map(exports);
742
743          return 0;
744       }
745
746       for (b = b->next; NULL != b; b = b->next)
747       {
748          if ((b->url->port == 0) || (b->url->port == port))
749          {
750             if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
751             {
752                if ((b->url->path == NULL) ||
753 #ifdef REGEX
754                   (regexec(b->url->preg, path, 0, NULL, 0) == 0)
755 #else
756                   (strncmp(b->url->path, path, b->url->pathlen) == 0)
757 #endif
758                )
759                {
760                   s = actions_to_text(b->action);
761                   matches = strsav(matches, "<b>{");
762                   matches = strsav(matches, s);
763                   matches = strsav(matches, " }</b><br>\n<code>");
764                   matches = strsav(matches, b->url->spec);
765                   matches = strsav(matches, "</code><br>\n<br>\n");
766                   freez(s);
767
768                   merge_current_action(action, b->action);
769                   hits++;
770                }
771             }
772          }
773       }
774
775       if (hits)
776       {
777          map(exports, "matches", 1, matches , 0);
778       }
779       else
780       {
781          map(exports, "matches", 1, "none", 1);
782       }
783       matches = NULL;
784
785       freez(url->dbuf);
786       freez(url->dvec);
787
788       freez(url_param);
789       freez(path);
790
791       s = current_action_to_text(action);
792       map(exports, "final", 1, s, 0);
793       s = NULL;
794
795       free_current_action(action);
796    }
797
798    rsp->body = fill_template(csp, "show-url-info", exports);
799    free_map(exports);
800    return 0;
801
802 }
803
804
805 /*********************************************************************
806  *
807  * Function    :  error_response
808  *
809  * Description :  returns an http_response that explains the reason
810  *                why a request failed.
811  *
812  * Parameters  :
813  *          1  :  csp = Current client state (buffers, headers, etc...)
814  *          2  :  templatename = Which template should be used for the answer
815  *          3  :  errno = system error number
816  *
817  * Returns     :  NULL if no memory, else http_response
818  *
819  *********************************************************************/
820 struct http_response *error_response(struct client_state *csp, const char *templatename, int err)
821 {
822    struct http_response *rsp;
823    struct map * exports = default_exports(csp, NULL);
824
825    if (NULL == (rsp = alloc_http_response()))
826    {
827       return NULL;
828    }  
829
830    map(exports, "host-html", 1, html_encode(csp->http->host), 0);
831    map(exports, "hostport", 1, csp->http->hostport, 1);
832    map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
833    map(exports, "path", 1, csp->http->path, 1);
834    map(exports, "path-html", 1, html_encode(csp->http->path), 0);
835    map(exports, "error", 1, safe_strerror(err), 0);
836    map(exports, "host-ip", 1, csp->http->host_ip_addr_str, 1);
837
838    rsp->body = fill_template(csp, templatename, exports);
839    free_map(exports);
840   
841    if (!strcmp(templatename, "no-such-domain"))
842    {
843       rsp->status = strdup("404 No such domain"); 
844    }
845    else if (!strcmp(templatename, "connect-failed"))
846    {
847       rsp->status = strdup("503 Connect failed");
848    }
849
850    return(finish_http_response(rsp));
851 }
852
853
854 /*********************************************************************
855  *
856  * Function    :  get_http_time
857  *
858  * Description :  Get the time in a format suitable for use in a
859  *                HTTP header - e.g.:
860  *                "Sun, 06 Nov 1994 08:49:37 GMT"
861  *
862  * Parameters  :  
863  *          1  :  time_offset = Time returned will be current time
864  *                              plus this number of seconds.
865  *          2  :  buf = Destination for result.  Must be long enough
866  *                      to hold 29 characters plus a trailing zero.
867  *
868  * Returns     :  N/A
869  *
870  *********************************************************************/
871 static void get_http_time(int time_offset, char * buf)
872 {
873    static const char day_names[7][4] =
874       { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
875    static const char month_names[12][4] =
876       { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
877         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
878
879    struct tm *t;
880    time_t current_time;
881
882    assert(buf);
883
884    time(&current_time); /* get current time */
885
886 /* FIXME: is this needed?  time() can't fail on Win32.  What about Linux?
887    if(current_time <= 0)
888    {
889       return NULL;
890    }
891 */
892
893    current_time += time_offset;
894
895    /* get and save the gmt */
896    t = gmtime(&current_time);
897
898    /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
899    snprintf(buf, 30,
900       "%s, %02d %s %4d %02d:%02d:%02d GMT",
901       day_names[t->tm_wday],
902       t->tm_mday,
903       month_names[t->tm_mon],
904       t->tm_year + 1900,
905       t->tm_hour,
906       t->tm_min,
907       t->tm_sec
908       );
909    buf[32] = '\0';
910 }
911
912
913 /*********************************************************************
914  *
915  * Function    :  finish_http_response
916  *
917  * Description :  Fill in the missing headers in an http response,
918  *                and flatten the headers to an http head.
919  *
920  * Parameters  :
921  *          1  :  rsp = pointer to http_response to be processed
922  *
923  * Returns     :  http_response, or NULL on failiure
924  *
925  *********************************************************************/
926 struct http_response *finish_http_response(struct http_response *rsp)
927 {
928    char buf[BUFFER_SIZE];
929
930    /* 
931     * Fill in the HTTP Status
932     */
933    sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
934    enlist_first(rsp->headers, buf);
935
936    /* 
937     * Set the Content-Length
938     */
939    if (rsp->content_length == 0)
940    {
941       rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
942    }
943    sprintf(buf, "Content-Length: %d", rsp->content_length);
944    enlist(rsp->headers, buf);
945
946    /* 
947     * Fill in the default headers:
948     *
949     * Content-Type: default to text/html if not already specified.
950     * Date: set to current date/time.
951     * Last-Modified: set to date/time the page was last changed.
952     * Expires: set to date/time page next needs reloading.
953     * Cache-Control: set to "no-cache" if applicable.
954     * 
955     * See http://www.w3.org/Protocols/rfc2068/rfc2068
956     */
957    enlist_unique(rsp->headers, "Content-Type: text/html", 13);
958
959    if (rsp->is_static)
960    {
961       /*
962        * Set Expires to about 10 min into the future so it'll get reloaded
963        * occasionally, e.g. if IJB gets upgraded.
964        */
965
966       get_http_time(0, buf);
967       enlist_unique_header(rsp->headers, "Date", buf);
968
969       /* Some date in the past. */
970       enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
971
972       get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
973       enlist_unique_header(rsp->headers, "Expires", buf);
974    }
975    else
976    {
977       /*
978        * Compliant browsers should not cache this due to the "Cache-Control"
979        * setting.  However, to be certain, we also set both "Last-Modified"
980        * and "Expires" to the current time.
981        */
982       enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
983       get_http_time(0, buf);
984       enlist_unique_header(rsp->headers, "Date", buf);
985       enlist_unique_header(rsp->headers, "Last-Modified", buf);
986       enlist_unique_header(rsp->headers, "Expires", buf);
987    }
988
989
990    /* 
991     * Write the head
992     */
993    if (NULL == (rsp->head = list_to_text(rsp->headers)))
994    {
995       free_http_response(rsp);
996       return(NULL);
997    }
998    rsp->head_length = strlen(rsp->head);
999
1000    return(rsp);
1001
1002 }
1003
1004
1005 /*********************************************************************
1006  *
1007  * Function    :  alloc_http_response
1008  *
1009  * Description :  Allocates a new http_response structure.
1010  *
1011  * Parameters  :  N/A
1012  *
1013  * Returns     :  pointer to a new http_response, or NULL.
1014  *
1015  *********************************************************************/
1016 struct http_response * alloc_http_response(void)
1017 {
1018    return (struct http_response *) zalloc(sizeof(struct http_response));
1019 }
1020
1021
1022 /*********************************************************************
1023  *
1024  * Function    :  free_http_response
1025  *
1026  * Description :  Free the memory occupied by an http_response
1027  *                and its depandant structures.
1028  *
1029  * Parameters  :
1030  *          1  :  rsp = pointer to http_response to be freed
1031  *
1032  * Returns     :  N/A
1033  *
1034  *********************************************************************/
1035 void free_http_response(struct http_response *rsp)
1036 {
1037    if(rsp)
1038    {
1039       freez(rsp->status);
1040       freez(rsp->head);
1041       freez(rsp->body);
1042       destroy_list(rsp->headers);
1043       freez(rsp);
1044    }
1045
1046 }
1047
1048
1049 /*********************************************************************
1050  *
1051  * Function    :  fill_template
1052  *
1053  * Description :  CGI support function that loads a given HTML
1054  *                template from the confdir, and fills it in
1055  *                by replacing @name@ with value using pcrs,
1056  *                for each item in the output map.
1057  *
1058  * Parameters  :
1059  *           1 :  csp = Current client state (buffers, headers, etc...)
1060  *           3 :  template = name of the HTML template to be used
1061  *           2 :  exports = map with fill in symbol -> name pairs
1062  *
1063  * Returns     :  char * with filled out form, or NULL if failiure
1064  *
1065  *********************************************************************/
1066 char *fill_template(struct client_state *csp, const char *templatename, struct map *exports)
1067 {
1068    struct map_entry *m;
1069    pcrs_job *job;
1070    char buf[BUFFER_SIZE];
1071    char *tmp_out_buffer;
1072    char *file_buffer = NULL;
1073    int size;
1074    int error;
1075    FILE *fp;
1076
1077
1078    /*
1079     * Open template file or fail
1080     */
1081    snprintf(buf, BUFFER_SIZE, "%s/templates/%s", csp->config->confdir, templatename);
1082
1083    if(NULL == (fp = fopen(buf, "r")))
1084    {
1085       log_error(LOG_LEVEL_ERROR, "error loading template %s: %E", buf);
1086       return NULL;
1087    }
1088    
1089
1090    /* 
1091     * Read the file, ignoring comments
1092     */
1093    while (fgets(buf, BUFFER_SIZE, fp))
1094    {
1095       /* skip lines starting with '#' */
1096       if(*buf == '#') continue;
1097    
1098       file_buffer = strsav(file_buffer, buf);
1099    }
1100    fclose(fp);
1101
1102
1103    /*
1104     * Execute the jobs
1105     */
1106    size = strlen(file_buffer) + 1;
1107
1108    /* 
1109     * Assemble pcrs joblist from exports map
1110     */
1111    for (m = exports->first; m != NULL; m = m->next)
1112    {
1113       /* Enclose name in @@ */
1114       snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1115
1116       /* Make and run job. */
1117       job = pcrs_compile(buf, m->value, "sigTU",  &error);
1118       if (job == NULL) 
1119       {
1120          log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1121       }
1122       else
1123       {
1124          pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1125          if (file_buffer != tmp_out_buffer)
1126          {
1127             free(file_buffer);
1128             file_buffer = tmp_out_buffer;
1129          }
1130          pcrs_free_job(job);
1131       }
1132    }
1133
1134
1135    /*
1136     * Return
1137     */
1138    return(file_buffer);
1139
1140 }
1141
1142
1143 /*********************************************************************
1144  *
1145  * Function    :  default_exports
1146  *
1147  * Description :  returns a struct map list that contains exports
1148  *                which are common to all CGI functions.
1149  *
1150  * Parameters  :
1151  *          1  :  exports = Structure to write output to.  This
1152  *                structure should be newly allocated and will be
1153  *                zeroed.
1154  *          1  :  csp = Current client state (buffers, headers, etc...)
1155  *          2  :  caller = name of CGI who calls us and which should
1156  *                         be excluded from the generated menu.
1157  * Returns     :  NULL if no memory, else map
1158  *
1159  *********************************************************************/
1160 struct map * default_exports(const struct client_state *csp, const char *caller)
1161 {
1162    char buf[20];
1163    struct map * exports = new_map();
1164
1165    map(exports, "version", 1, VERSION, 1);
1166    map(exports, "my-ip-address", 1, csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown", 1);
1167    map(exports, "my-hostname", 1, csp->my_hostname ? csp->my_hostname : "unknown", 1);
1168    map(exports, "admin-address", 1, csp->config->admin_address ? csp->config->admin_address : "fill@me.in.please", 1);
1169    map(exports, "homepage", 1, HOME_PAGE_URL, 1);
1170    map(exports, "default-cgi", 1, HOME_PAGE_URL "/config", 1);
1171    map(exports, "menu", 1, make_menu(caller), 0);
1172    map(exports, "code-status", 1, CODE_STATUS, 1);
1173
1174    snprintf(buf, 20, "%d", csp->config->hport);
1175    map(exports, "my-port", 1, buf, 1);
1176
1177    if(!strcmp(CODE_STATUS, "stable"))
1178    {
1179       map_block_killer(exports, "unstable");
1180    }
1181
1182    if(csp->config->proxy_info_url != NULL)
1183    {
1184       map(exports, "proxy-info-url", 1, csp->config->proxy_info_url, 1);
1185    }
1186    else
1187    {
1188       map_block_killer(exports, "have-proxy-info");
1189    }   
1190
1191    return (exports);
1192 }
1193
1194
1195 /*********************************************************************
1196  *
1197  * Function    :  map_block_killer
1198  *
1199  * Description :  Convenience function.
1200  *                Adds a "killer" for the conditional HTML-template
1201  *                block <name>, i.e. a substitution of the regex
1202  *                "if-<name>-start.*if-<name>-end" to the given
1203  *                export list.
1204  *
1205  * Parameters  :  
1206  *          1  :  exports = map to extend
1207  *          2  :  name = name of conditional block
1208  *
1209  * Returns     :  extended map
1210  *
1211  *********************************************************************/
1212 void map_block_killer(struct map *exports, const char *name)
1213 {
1214    char buf[1000]; /* Will do, since the names are hardwired */
1215
1216    snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1217    map(exports, buf, 1, "", 1);
1218 }
1219
1220
1221 /*********************************************************************
1222  *
1223  * Function    :  map_conditional
1224  *
1225  * Description :  Convenience function.
1226  *                Adds an "if-then-else" for the conditional HTML-template
1227  *                block <name>, i.e. a substitution of the form:
1228  *                @if-<name>-then@
1229  *                   True text
1230  *                @else-not-<name>@
1231  *                   False text
1232  *                @endif-<name>@
1233  *
1234  *                The control structure and one of the alternatives
1235  *                will be hidden.
1236  *
1237  * Parameters  :  
1238  *          1  :  exports = map to extend
1239  *          2  :  name = name of conditional block
1240  *          3  :  choose_first = nonzero for first, zero for second.
1241  *
1242  * Returns     :  extended map
1243  *
1244  *********************************************************************/
1245 void map_conditional(struct map *exports, const char *name, int choose_first)
1246 {
1247    char buf[1000]; /* Will do, since the names are hardwired */
1248
1249    snprintf(buf, 1000, (choose_first
1250       ? "else-not-%s@.*@endif-%s"
1251       : "if-%s-then@.*@else-not-%s"),
1252       name, name);
1253    map(exports, buf, 1, "", 1);
1254
1255    snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1256    map(exports, buf, 1, "", 1);
1257 }
1258
1259
1260 /*********************************************************************
1261  *
1262  * Function    :  make_menu
1263  *
1264  * Description :  Returns an HTML-formatted menu of the available 
1265  *                unhidden CGIs, excluding the one given in <self>.
1266  *
1267  * Parameters  :  self = name of CGI to leave out, can be NULL
1268  *
1269  * Returns     :  menu string
1270  *
1271  *********************************************************************/
1272 char *make_menu(const char *self)
1273 {
1274    const struct cgi_dispatcher *d;
1275    char buf[BUFFER_SIZE];
1276    char *result = NULL;
1277
1278    if (self == NULL)
1279    {
1280       self = "NO-SUCH-CGI!";
1281    }
1282
1283    /* List available unhidden CGI's and export as "other-cgis" */
1284    for (d = cgi_dispatcher; d->handler; d++)
1285    {
1286       if (strncmp(d->description, "HIDE", 4) && strcmp(d->name, self))
1287       {
1288          snprintf(buf, BUFFER_SIZE, "<li><a href=%s/config/%s>%s</a></li>\n",
1289                HOME_PAGE_URL, d->name, d->description);
1290          result = strsav(result, buf);
1291       }
1292    }
1293    return(result);
1294
1295 }
1296
1297
1298 /*********************************************************************
1299  *
1300  * Function    :  dump_map
1301  *
1302  * Description :  HTML-dump a map for debugging
1303  *
1304  * Parameters  :
1305  *          1  :  the_map = map to dump
1306  *
1307  * Returns     :  string with HTML
1308  *
1309  *********************************************************************/
1310 char *dump_map(const struct map *the_map)
1311 {
1312    struct map_entry *cur_entry = the_map->first;
1313    char *ret = NULL;
1314
1315    ret = strsav(ret, "<table>\n");
1316
1317    while (cur_entry)
1318    {
1319       ret = strsav(ret, "<tr><td><b>");
1320       ret = strsav(ret, cur_entry->name);
1321       ret = strsav(ret, "</b></td><td>");
1322       ret = strsav(ret, cur_entry->value);
1323       ret = strsav(ret, "</td></tr>\n");
1324       cur_entry = cur_entry->next;
1325    }
1326
1327    ret = strsav(ret, "</table>\n");
1328    return(ret);
1329
1330 }
1331
1332
1333 #ifdef FEATURE_STATISTICS
1334 /*********************************************************************
1335  *
1336  * Function    :  add_stats
1337  *
1338  * Description :  Add the blocking statistics to a given map.
1339  *
1340  * Parameters  :
1341  *          1  :  exports = map to write to.
1342  *
1343  * Returns     :  pointer to extended map
1344  *
1345  *********************************************************************/
1346 struct map *add_stats(struct map *exports)
1347 {
1348    float perc_rej;   /* Percentage of http requests rejected */
1349    char buf[1000];
1350    int local_urls_read     = urls_read;
1351    int local_urls_rejected = urls_rejected;
1352
1353    /*
1354     * Need to alter the stats not to include the fetch of this
1355     * page.
1356     *
1357     * Can't do following thread safely! doh!
1358     *
1359     * urls_read--;
1360     * urls_rejected--; * This will be incremented subsequently *
1361     */
1362
1363    if (local_urls_read == 0)
1364    {
1365       map_block_killer(exports, "have-stats");
1366    }
1367    else
1368    {
1369       map_block_killer(exports, "have-no-stats");
1370
1371       perc_rej = (float)local_urls_rejected * 100.0F /
1372             (float)local_urls_read;
1373
1374       sprintf(buf, "%d", local_urls_read);
1375       map(exports, "requests-received", 1, buf, 1);
1376
1377       sprintf(buf, "%d", local_urls_rejected);
1378       map(exports, "requests-blocked", 1, buf, 1);
1379
1380       sprintf(buf, "%6.2f", perc_rej);
1381       map(exports, "percent-blocked", 1, buf, 1);
1382    }
1383
1384    return(exports);
1385
1386 }
1387 #endif /* def FEATURE_STATISTICS */
1388
1389 /*
1390   Local Variables:
1391   tab-width: 3
1392   end:
1393 */