Changed to conform to new pcrs interface
[privoxy.git] / cgi.c
1 const char cgi_rcs[] = "$Id: cgi.c,v 1.10 2001/07/13 13:53:13 oes 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.10  2001/07/13 13:53:13  oes
40  *    Removed all #ifdef PCRS and related code
41  *
42  *    Revision 1.9  2001/06/29 21:45:41  oes
43  *    Indentation, CRLF->LF, Tab-> Space
44  *
45  *    Revision 1.8  2001/06/29 13:21:46  oes
46  *    - Cosmetics: renamed and reordered functions, variables,
47  *      texts, improved comments  etc
48  *
49  *    - Removed ij_untrusted_url() The relevant
50  *      info is now part of the "untrusted" page,
51  *      which is generated by filters.c:trust_url()
52  *
53  *    - Generators of content now call finish_http_response()
54  *      themselves, making jcc.c:chat() a little less
55  *      cluttered
56  *
57  *    - Removed obsolete "Pragma: no-cache" from our headers
58  *
59  *    - http_responses now know their head length
60  *
61  *    - fill_template now uses the new interface to pcrs, so that
62  *       - long jobs (like whole files) no longer have to be assembled
63  *         in a fixed size buffer
64  *       - the new T (trivial) option is used, and the replacement may
65  *         contain Perl syntax backrefs without confusing pcrs
66  *
67  *    - Introduced default_exports() which generates a set of exports
68  *      common to all CGIs and other content generators
69  *
70  *    - Introduced convenience function map_block_killer()
71  *
72  *    - Introduced convenience function make_menu()
73  *
74  *    - Introduced CGI-like function error_response() which generates
75  *      the "No such domain" and "Connect failed" messages using the
76  *      CGI platform
77  *
78  *    - cgi_show_url_info:
79  *      - adapted to new CGI features
80  *      - form and answers now generated from same template
81  *      - http:// prefix in URL now OK
82  *
83  *    - cgi_show_status:
84  *      - adapted to new CGI features
85  *      - no longer uses csp->init_proxy_args
86  *
87  *    - cgi_default:
88  *      - moved menu generation to make_menu()
89  *
90  *    - add_stats now writes single export map entries instead
91  *      of a fixed string
92  *
93  *    - Moved redirect_url() to filters.c
94  *
95  *    - Fixed mem leak in free_http_response(), map_block_killer(),
96  *
97  *    - Removed logentry from cancelled commit
98  *
99  *    Revision 1.7  2001/06/09 10:51:58  jongfoster
100  *    Changing "show URL info" handler to new style.
101  *    Changing BUFSIZ ==> BUFFER_SIZE
102  *
103  *    Revision 1.6  2001/06/07 23:05:19  jongfoster
104  *    Removing code related to old forward and ACL files.
105  *
106  *    Revision 1.5  2001/06/05 19:59:16  jongfoster
107  *    Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
108  *
109  *    Revision 1.4  2001/06/04 10:41:52  swa
110  *    show version string of cgi.h and cgi.c
111  *
112  *    Revision 1.3  2001/06/03 19:12:16  oes
113  *    introduced new cgi handling
114  *
115  *    No revisions before 1.3
116  *
117  **********************************************************************/
118 \f
119
120 #include "config.h"
121
122 #include <stdio.h>
123 #include <sys/types.h>
124 #include <stdlib.h>
125 #include <ctype.h>
126 #include <string.h>
127
128 #ifdef _WIN32
129 #define snprintf _snprintf
130 #endif /* def _WIN32 */
131
132 #include "project.h"
133 #include "cgi.h"
134 #include "list.h"
135 #include "encode.h"
136 #include "ssplit.h"
137 #include "jcc.h"
138 #include "filters.h"
139 #include "actions.h"
140 #include "errlog.h"
141 #include "miscutil.h"
142 #include "showargs.h"
143
144 const char cgi_h_rcs[] = CGI_H_VERSION;
145
146 const struct cgi_dispatcher cgi_dispatcher[] = {
147    { "show-status", 
148          11, cgi_show_status,  
149          "Show information about the version and configuration" }, 
150    { "show-url-info",
151          13, cgi_show_url_info, 
152          "Show which actions apply to a URL and why"  },
153    { "send-banner",
154          11, cgi_send_banner, 
155          "HIDE Send the transparent or \"Junkbuster\" gif" },
156    { "",
157          0, cgi_default,
158          "Junkbuster main page" },
159    { NULL, 0, NULL, NULL }
160 };
161
162
163 /*********************************************************************
164  * 
165  * Function    :  dispatch_cgi
166  *
167  * Description :  Checks if a request URL has either the magical hostname
168  *                i.j.b or matches HOME_PAGE_URL/config/. If so, it parses
169  *                the (rest of the) path as a cgi name plus query string,
170  *                prepares a map that maps CGI parameter names to their values,
171  *                initializes the http_response struct, and calls the 
172  *                relevant CGI handler function.
173  *
174  * Parameters  :
175  *          1  :  csp = Current client state (buffers, headers, etc...)
176  *
177  * Returns     :  http_response if match, NULL if nonmatch or handler fail
178  *
179  *********************************************************************/
180 struct http_response *dispatch_cgi(struct client_state *csp)
181 {
182    char *argstring = NULL;
183    const struct cgi_dispatcher *d;
184    struct map *param_list;
185    struct http_response *rsp;
186
187    /*
188     * Should we intercept ?
189     */
190
191    /* Either the host matches CGI_PREFIX_HOST ..*/
192    if (0 == strcmpic(csp->http->host, CGI_PREFIX_HOST))
193    {
194       /* ..then the path will all be for us */
195       argstring = csp->http->path;
196    }
197    /* Or it's the host part HOME_PAGE_URL, and the path /config ? */
198    else if (   (0 == strcmpic(csp->http->host, HOME_PAGE_URL + 7 ))
199             && (0 == strncmpic(csp->http->path,"/config", 7))
200             && ((csp->http->path[7] == '/') || (csp->http->path[7] == '\0')))
201    {
202       /* then it's everything following "/config" */
203       argstring = csp->http->path + 7;
204    }
205    else
206    {
207       return NULL;
208    }
209
210    /* 
211     * This is a CGI call.
212     */
213
214    /* Get mem for response or fail*/
215    if (NULL == ( rsp = zalloc(sizeof(*rsp))))
216    {
217       return NULL;
218    }
219
220    /* Remove leading slash */
221    if (*argstring == '/')
222    {
223       argstring++;
224    }
225
226    log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
227    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", 
228                             csp->ip_addr_str, csp->http->cmd); 
229
230    /* Find and start the right CGI function*/
231    for (d = cgi_dispatcher; d->handler; d++)
232    {
233       if (strncmp(argstring, d->name, d->name_length) == 0)
234       {
235          param_list = parse_cgi_parameters(argstring + d->name_length);
236          if ((d->handler)(csp, rsp, param_list))
237          {
238             freez(rsp);
239          }
240
241          free_map(param_list);
242          return(finish_http_response(rsp));
243       }
244    }
245
246    /* Can't get here, since cgi_default will match all requests */
247    freez(rsp);
248    return(NULL);
249
250 }
251
252
253 /*********************************************************************
254  *
255  * Function    :  parse_cgi_parameters
256  *
257  * Description :  Parse a URL-encoded argument string into name/value
258  *                pairs and store them in a struct map list.
259  *
260  * Parameters  :
261  *          1  :  string = string to be parsed 
262  *
263  * Returns     :  poniter to param list, or NULL if failiure
264  *
265  *********************************************************************/
266 struct map *parse_cgi_parameters(char *argstring)
267 {
268    char *tmp, *p;
269    char *vector[BUFFER_SIZE];
270    int pairs, i;
271    struct map *cgi_params = NULL;
272
273    if(*argstring == '?') argstring++;
274    tmp = strdup(argstring);
275
276    pairs = ssplit(tmp, "&", vector, SZ(vector), 1, 1);
277
278    for (i = 0; i < pairs; i++)
279    {
280       if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
281       {
282          *p = '\0';
283          cgi_params = map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0);
284       }
285    }
286
287    free(tmp);
288    return(cgi_params);
289
290 }
291
292
293 /*********************************************************************
294  *
295  * Function    :  cgi_default
296  *
297  * Description :  CGI function that is called if no action was given.
298  *                Lists menu of available unhidden CGIs.
299  *               
300  * Parameters  :
301  *           1 :  csp = Current client state (buffers, headers, etc...)
302  *           2 :  rsp = http_response data structure for output
303  *           3 :  parameters = map of cgi parameters
304  *
305  * Returns     :  0
306  *
307  *********************************************************************/
308 int cgi_default(struct client_state *csp, struct http_response *rsp,
309                 struct map *parameters)
310 {
311    char *p, *tmp = NULL;
312    struct map *exports = default_exports(csp, "");
313
314    /* If there were other parameters, export a dump as "cgi-parameters" */
315    if(parameters)
316    {
317       p = dump_map(parameters);
318       tmp = strsav(tmp, "<p>What made you think this cgi takes parameters?\n"
319                         "Anyway, here they are, in case you're interested:</p>\n");
320       tmp = strsav(tmp, p);
321       exports = map(exports, "cgi-parameters", 1, tmp, 0);
322       free(p);
323    }
324    else
325    {
326       exports = map(exports, "cgi-parameters", 1, "", 1);
327    }
328
329    rsp->body = fill_template(csp, "default", exports);
330    free_map(exports);
331    return(0);
332
333 }
334
335
336 /*********************************************************************
337  *
338  * Function    :  cgi_send_banner
339  *
340  * Description :  CGI function that returns a banner. 
341  *
342  * Parameters  :
343  *           1 :  csp = Current client state (buffers, headers, etc...)
344  *           2 :  rsp = http_response data structure for output
345  *           3 :  parameters = map of cgi parameters
346  *
347  * CGI Parameters :
348  *           type : Selects the type of banner between "trans" and "jb".
349  *                  Defaults to "jb" if absent or != "trans".
350  *
351  * Returns     :  0
352  *
353  *********************************************************************/
354 int cgi_send_banner(struct client_state *csp, struct http_response *rsp,
355                     struct map *parameters)
356 {
357    if(strcmp(lookup(parameters, "type"), "trans"))
358    {
359       rsp->body = bindup(JBGIF, sizeof(JBGIF));
360       rsp->content_length = sizeof(JBGIF);
361    }
362    else
363    {
364       rsp->body = bindup(BLANKGIF, sizeof(BLANKGIF));
365       rsp->content_length = sizeof(BLANKGIF);
366    }   
367
368    enlist(rsp->headers, "Content-Type: image/gif");
369
370    return(0);
371
372 }
373
374
375 /*********************************************************************
376  *
377  * Function    :  cgi_show_status
378  *
379  * Description :  CGI function that returns a a web page describing the
380  *                current status of IJB.
381  *
382  * Parameters  :
383  *           1 :  csp = Current client state (buffers, headers, etc...)
384  *           2 :  rsp = http_response data structure for output
385  *           3 :  parameters = map of cgi parameters
386  *
387  * CGI Parameters :
388  *           type : Selects the type of banner between "trans" and "jb".
389  *                  Defaults to "jb" if absent or != "trans".
390  *
391  * Returns     :  0
392  *
393  *********************************************************************/
394 int cgi_show_status(struct client_state *csp, struct http_response *rsp,
395                     struct map *parameters)
396 {
397    char *s = NULL;
398    int i;
399    struct map *exports = default_exports(csp, "show-status");
400
401 #ifdef SPLIT_PROXY_ARGS
402    FILE * fp;
403    char buf[BUFFER_SIZE];
404    char * p;
405    const char * filename = NULL;
406    char * file_description = NULL;
407
408
409    p = lookup(parameters, "file");
410    switch (*p)
411    {
412    case 'p':
413       if (csp->actions_list)
414       {
415          filename = csp->actions_list->filename;
416          file_description = "Actions List";
417       }
418       break;
419
420    case 'r':
421       if (csp->rlist)
422       {
423          filename = csp->rlist->filename;
424          file_description = "Regex Filter List";
425       }
426       break;
427
428 #ifdef TRUST_FILES
429    case 't':
430       if (csp->tlist)
431       {
432          filename = csp->tlist->filename;
433          file_description = "Trust List";
434       }
435       break;
436 #endif /* def TRUST_FILES */
437    }
438
439    if (NULL != filename)
440    {
441       exports = map(exports, "file-description", 1, file_description, 1);
442       exports = map(exports, "filepath", 1, html_encode(filename), 0);
443
444       if ((fp = fopen(filename, "r")) == NULL)
445       {
446          exports = map(exports, "content", 1, "<h1>ERROR OPENING FILE!</h1>", 1);
447       }
448       else
449       {
450          while (fgets(buf, sizeof(buf), fp))
451          {
452             p = html_encode(buf);
453             if (p)
454             {
455                s = strsav(s, p);
456                freez(p);
457                s = strsav(s, "<br>");
458             }
459          }
460          fclose(fp);
461          exports = map(exports, "contents", 1, s, 0);
462       }
463       rsp->body = fill_template(csp, "show-status-file", exports);
464       free_map(exports);
465       return(0);
466
467    }
468
469 #endif /* def SPLIT_PROXY_ARGS */
470
471    exports = map(exports, "redirect-url", 1, REDIRECT_URL, 1);
472    
473    s = NULL;
474    for (i=0; i < Argc; i++)
475    {
476       s = strsav(s, Argv[i]);
477       s = strsav(s, " ");
478    }
479    exports = map(exports, "invocation", 1, s, 0);
480
481    exports = map(exports, "options", 1, csp->config->proxy_args, 1);
482    s =   show_rcs();
483    exports = map(exports, "sourceversions", 1, s, 0);  
484    s =   show_defines();
485    exports = map(exports, "defines", 1, s, 0); 
486
487 #ifdef STATISTICS
488    exports = add_stats(exports);
489 #else
490    exports = map_block_killer(exports, "statistics");
491 #endif /* ndef STATISTICS */
492
493 #ifdef SPLIT_PROXY_ARGS
494
495    exports = map_block_killer(exports, "no-split-args");
496
497    if (csp->actions_list)
498    {
499       exports = map(exports, "actions-filename", 1,  csp->actions_list->filename, 1);
500    }
501    else
502    {
503       exports = map(exports, "actions-filename", 1, "None specified", 1);
504    }
505
506    if (csp->rlist)
507    {
508       exports = map(exports, "re-filter-filename", 1,  csp->rlist->filename, 1);
509    }
510    else
511    {
512       exports = map(exports, "re-filter-filename", 1, "None specified", 1);
513    }
514
515 #ifdef TRUST_FILES
516    if (csp->tlist)
517    {
518       exports = map(exports, "trust-filename", 1,  csp->tlist->filename, 1);
519    }
520    else
521    {
522        exports = map(exports, "trust-filename", 1, "None specified", 1);
523    }
524 #else
525    exports = map_block_killer(exports, "trust-support");
526 #endif /* ndef TRUST_FILES */
527
528 #else /* ifndef SPLIT_PROXY_ARGS */
529    exports = map_block_killer(exports, "split-args");
530
531    if (csp->clist)
532    {
533       map(exports, "clist", 1, csp->clist->proxy_args , 1);
534    }
535
536    if (csp->rlist)
537    {
538       map(exports, "rlist", 1, csp->rlist->proxy_args , 1);
539    }
540
541 #ifdef TRUST_FILES
542     if (csp->tlist)
543    {
544       map(exports, "tlist", 1, csp->tlist->proxy_args , 1);
545    }
546 #endif /* def TRUST_FILES */
547
548 #endif /* ndef SPLIT_PROXY_ARGS */
549
550    rsp->body = fill_template(csp, "show-status", exports);
551    free_map(exports);
552    return(0);
553
554 }
555
556  
557  /*********************************************************************
558  *
559  * Function    :  cgi_show_url_info
560  *
561  * Description :  CGI function that determines and shows which actions
562  *                junkbuster will perform for a given url, and which
563  *                matches starting from the defaults have lead to that.
564  *
565  * Parameters  :
566  *           1 :  csp = Current client state (buffers, headers, etc...)
567  *           2 :  rsp = http_response data structure for output
568  *           3 :  parameters = map of cgi parameters
569  *
570  * CGI Parameters :
571  *            url : The url whose actions are to be determined.
572  *                  If url is unset, the url-given conditional will be
573  *                  set, so that all but the form can be suppressed in
574  *                  the template.
575  *
576  * Returns     :  0
577  *
578  *********************************************************************/
579 int cgi_show_url_info(struct client_state *csp, struct http_response *rsp,
580                       struct map *parameters)
581 {
582    struct map *exports = default_exports(csp, "show-url-info");
583    char *url_param, *host = NULL;
584
585    if (NULL == (url_param = strdup(lookup(parameters, "url"))) || *url_param == '\0')
586    {
587       exports = map_block_killer(exports, "url-given");
588       exports = map(exports, "url", 1, "", 1);
589    }
590    else
591    {
592       char *matches = NULL;
593       char *path;
594       char *s;
595       int port = 80;
596       int hits = 0;
597       struct file_list *fl;
598       struct url_actions *b;
599       struct url_spec url[1];
600       struct current_action_spec action[1];
601       
602       host = url_param;
603       host += (strncmp(url_param, "http://", 7)) ? 0 : 7;
604
605       exports = map(exports, "url", 1, host, 1);
606       exports = map(exports, "url-html", 1, html_encode(host), 0);
607
608       init_current_action(action);
609
610       s = current_action_to_text(action);
611       exports = map(exports, "default", 1, s , 0);
612
613       if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
614       {
615          exports = map(exports, "matches", 1, "none" , 1);
616          exports = map(exports, "final", 1, lookup(exports, "default"), 1);
617
618          freez(url_param);
619          free_current_action(action);
620
621          rsp->body = fill_template(csp, "show-url-info", exports);
622          free_map(exports);
623
624          return 0;
625       }
626
627       s = strchr(host, '/');
628       if (s != NULL)
629       {
630          path = strdup(s);
631          *s = '\0';
632       }
633       else
634       {
635          path = strdup("");
636       }
637       s = strchr(host, ':');
638       if (s != NULL)
639       {
640          *s++ = '\0';
641          port = atoi(s);
642          s = NULL;
643       }
644
645       *url = dsplit(host);
646
647       /* if splitting the domain fails, punt */
648       if (url->dbuf == NULL)
649       {
650          exports = map(exports, "matches", 1, "none" , 1);
651          exports = map(exports, "final", 1, lookup(exports, "default"), 1);
652
653          freez(url_param);
654          freez(path);
655          free_current_action(action);
656
657          rsp->body = fill_template(csp, "show-url-info", exports);
658          free_map(exports);
659
660          return 0;
661       }
662
663       for (b = b->next; NULL != b; b = b->next)
664       {
665          if ((b->url->port == 0) || (b->url->port == port))
666          {
667             if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
668             {
669                if ((b->url->path == NULL) ||
670 #ifdef REGEX
671                   (regexec(b->url->preg, path, 0, NULL, 0) == 0)
672 #else
673                   (strncmp(b->url->path, path, b->url->pathlen) == 0)
674 #endif
675                )
676                {
677                   s = actions_to_text(b->action);
678                   matches = strsav(matches, "<b>{");
679                   matches = strsav(matches, s);
680                   matches = strsav(matches, " }</b><br>\n<code>");
681                   matches = strsav(matches, b->url->spec);
682                   matches = strsav(matches, "</code><br>\n<br>\n");
683                   freez(s);
684
685                   merge_current_action(action, b->action);
686                   hits++;
687                }
688             }
689          }
690       }
691
692       if (hits)
693       {
694          exports = map(exports, "matches", 1, matches , 0);
695       }
696       else
697       {
698          exports = map(exports, "matches", 1, "none", 1);
699       }
700       matches = NULL;
701
702       freez(url->dbuf);
703       freez(url->dvec);
704
705       freez(url_param);
706       freez(path);
707
708       s = current_action_to_text(action);
709       exports = map(exports, "final", 1, s, 0);
710       s = NULL;
711
712       free_current_action(action);
713    }
714
715    rsp->body = fill_template(csp, "show-url-info", exports);
716    free_map(exports);
717    return 0;
718
719 }
720
721
722 /*********************************************************************
723  *
724  * Function    :  error_response
725  *
726  * Description :  returns an http_response that explains the reason
727  *                why a request failed.
728  *
729  * Parameters  :
730  *          1  :  csp = Current client state (buffers, headers, etc...)
731  *          2  :  template = Which template should be used for the answer
732  *          3  :  errno = system error number
733  *
734  * Returns     :  NULL if no memory, else http_response
735  *
736  *********************************************************************/
737 struct http_response *error_response(struct client_state *csp, const char *template, int err)
738 {
739    struct http_response *rsp;
740    struct map *exports = default_exports(csp, NULL);
741
742    if (NULL == ( rsp = (struct http_response *)zalloc(sizeof(*rsp))))
743    {
744       return NULL;
745    }  
746
747       exports = map(exports, "host-html", 1, html_encode(csp->http->host), 0);
748       exports = map(exports, "hostport", 1, csp->http->hostport, 1);
749       exports = map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
750       exports = map(exports, "path", 1, csp->http->path, 1);
751       exports = map(exports, "path-html", 1, html_encode(csp->http->path), 0);
752       exports = map(exports, "error", 1, safe_strerror(err), 0);
753       exports = map(exports, "host-ip", 1, csp->http->host_ip_addr_str, 1);
754
755       rsp->body = fill_template(csp, template, exports);
756       free_map(exports);
757       
758       if (!strcmp(template, "no-such-domain"))
759       {
760          rsp->status = strdup("404 No such domain"); 
761       }
762       else if (!strcmp(template, "connect-failed"))
763       {
764          rsp->status = strdup("503 Connect failed");
765       }
766
767       return(finish_http_response(rsp));
768 }
769
770
771 /*********************************************************************
772  *
773  * Function    :  finish_http_response
774  *
775  * Description :  Fill in the missing headers in an http response,
776  *                and flatten the headers to an http head.
777  *
778  * Parameters  :
779  *          1  :  rsp = pointer to http_response to be processed
780  *
781  * Returns     :  http_response, or NULL on failiure
782  *
783  *********************************************************************/
784 struct http_response *finish_http_response(struct http_response *rsp)
785 {
786    char buf[BUFFER_SIZE];
787
788    /* 
789     * Fill in the HTTP Status
790     */
791    sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
792    enlist_first(rsp->headers, buf);
793
794    /* 
795     * Set the Content-Length
796     */
797    if (rsp->content_length == 0)
798    {
799       rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
800    }
801    sprintf(buf, "Content-Length: %d", rsp->content_length);
802    enlist(rsp->headers, buf);
803
804    /* 
805     * Fill in the default headers FIXME: Are these correct? sequence OK? check rfc!
806     */
807    enlist_unique(rsp->headers, "Last-Modified: Thu Jul 31, 1997 07:42:22 pm GMT", 14);
808    enlist_unique(rsp->headers, "Expires:       Thu Jul 31, 1997 07:42:22 pm GMT", 8);
809    enlist_unique(rsp->headers, "Content-Type: text/html", 13);
810    enlist(rsp->headers, "");
811   
812
813    /* 
814     * Write the head
815     */
816    if (NULL == (rsp->head = list_to_text(rsp->headers)))
817    {
818       free_http_response(rsp);
819       return(NULL);
820    }
821    rsp->head_length = strlen(rsp->head);
822
823    return(rsp);
824
825 }
826   
827
828 /*********************************************************************
829  *
830  * Function    :  free_http_response
831  *
832  * Description :  Free the memory occupied by an http_response
833  *                and its depandant structures.
834  *
835  * Parameters  :
836  *          1  :  rsp = pointer to http_response to be freed
837  *
838  * Returns     :  N/A
839  *
840  *********************************************************************/
841 void free_http_response(struct http_response *rsp)
842 {
843    if(rsp)
844    {
845       freez(rsp->status);
846       freez(rsp->head);
847       freez(rsp->body);
848       destroy_list(rsp->headers);
849       freez(rsp);
850    }
851
852 }
853
854
855 /*********************************************************************
856  *
857  * Function    :  fill_template
858  *
859  * Description :  CGI support function that loads a given HTML
860  *                template from the confdir, and fills it in
861  *                by replacing @name@ with value using pcrs,
862  *                for each item in the output map.
863  *
864  * Parameters  :
865  *           1 :  csp = Current client state (buffers, headers, etc...)
866  *           3 :  template = name of the HTML template to be used
867  *           2 :  exports = map with fill in symbol -> name pairs
868  *
869  * Returns     :  char * with filled out form, or NULL if failiure
870  *
871  *********************************************************************/
872 char *fill_template(struct client_state *csp, const char *template, struct map *exports)
873 {
874    struct map *m;
875    pcrs_job *job, *joblist = NULL;
876    char buf[BUFFER_SIZE];
877    char *new, *old = NULL;
878    int size;
879    FILE *fp;
880
881
882    /*
883     * Open template file or fail
884     */
885    snprintf(buf, BUFFER_SIZE, "%s/templates/%s", csp->config->confdir, template);
886
887    if(NULL == (fp = fopen(buf, "r")))
888    {
889       log_error(LOG_LEVEL_ERROR, "error loading template %s: %E", buf);
890       return NULL;
891    }
892    
893
894    /* 
895     * Assemble pcrs joblist from exports map
896     */
897    for (m = exports; m; m = m->next)
898    {
899       int error;
900
901       /* Enclose name in @@ */
902       snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
903
904       /* Make and chain job */
905       if ( NULL == (job = (pcrs_compile(buf, m->value, "sigTU", &error))) ) 
906       {
907          log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
908       }
909       else
910       {
911          job->next = joblist;
912          joblist = job;
913       }
914    }
915
916
917    /* 
918     * Read the file, ignoring comments
919     */
920    while (fgets(buf, BUFFER_SIZE, fp))
921    {
922       /* skip lines starting with '#' */
923       if(*buf == '#') continue;
924    
925       old = strsav(old, buf);
926    }
927    fclose(fp);
928
929
930    /*
931     * Execute the jobs
932     */
933    size = strlen(old) + 1;
934    new = old;
935
936    for (job = joblist; NULL != job; job = job->next)
937    {
938       pcrs_execute(job, old, size, &new, &size);
939       if (old != buf) free(old);
940       old = new;
941    }
942
943
944    /*
945     * Free the jobs & return
946     */
947    pcrs_free_joblist(joblist);
948    return(new);
949
950 }
951
952
953 /*********************************************************************
954  *
955  * Function    :  default_exports
956  *
957  * Description :  returns a struct map list that contains exports
958  *                which are common to all CGI functions.
959  *
960  * Parameters  :
961  *          1  :  csp = Current client state (buffers, headers, etc...)
962  *          2  :  caller = name of CGI who calls us and which should
963  *                         be excluded from the generated menu.
964  * Returns     :  NULL if no memory, else map
965  *
966  *********************************************************************/
967 struct map *default_exports(struct client_state *csp, char *caller)
968 {
969    struct map *exports = NULL;
970    char buf[20];
971
972    exports = map(exports, "version", 1, VERSION, 1);
973    exports = map(exports, "my-ip-address", 1, csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown", 1);
974    exports = map(exports, "my-hostname", 1, csp->my_hostname ? csp->my_hostname : "unknown", 1);
975    exports = map(exports, "admin-address", 1, csp->config->admin_address ? csp->config->admin_address : "fill@me.in.please", 1);
976    exports = map(exports, "homepage", 1, HOME_PAGE_URL, 1);
977    exports = map(exports, "default-cgi", 1, HOME_PAGE_URL "/config", 1);
978    exports = map(exports, "menu", 1, make_menu(caller), 0);
979    exports = map(exports, "code-status", 1, CODE_STATUS, 1);
980
981    snprintf(buf, 20, "%d", csp->config->hport);
982    exports = map(exports, "my-port", 1, buf, 1);
983
984    if(!strcmp(CODE_STATUS, "stable"))
985    {
986       exports = map_block_killer(exports, "unstable");
987    }
988
989    if(csp->config->proxy_info_url != NULL)
990    {
991       exports = map(exports, "proxy-info-url", 1, csp->config->proxy_info_url, 1);
992    }
993    else
994    {
995       exports = map_block_killer(exports, "have-proxy-info");
996    }   
997
998    return(exports);
999
1000 }
1001
1002
1003 /*********************************************************************
1004  *
1005  * Function    :  map_block_killer
1006  *
1007  * Description :  Convenience function.
1008  *                Adds a "killer" for the conditional HTML-template
1009  *                block <name>, i.e. a substitution of the regex
1010  *                "if-<name>-start.*if-<name>-end" to the given
1011  *                export list.
1012  *
1013  * Parameters  :  
1014  *          1  :  exports = map to extend
1015  *          2  :  name = name of conditional block
1016  *
1017  * Returns     :  extended map
1018  *
1019  *********************************************************************/
1020 struct map *map_block_killer(struct map *exports, char *name)
1021 {
1022    char buf[1000]; /* Will do, since the names are hardwired */
1023
1024    snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1025    exports = map(exports, buf, 1, "", 1);
1026
1027    return(exports);
1028
1029 }
1030
1031
1032 /*********************************************************************
1033  *
1034  * Function    :  make_menu
1035  *
1036  * Description :  Returns an HTML-formatted menu of the available 
1037  *                unhidden CGIs, excluding the one given in <self>.
1038  *
1039  * Parameters  :  self = name of CGI to leave out, can be NULL
1040  *
1041  * Returns     :  menu string
1042  *
1043  *********************************************************************/
1044 char *make_menu(const char *self)
1045 {
1046    const struct cgi_dispatcher *d;
1047    char buf[BUFFER_SIZE], *tmp = NULL;
1048
1049    if (self == NULL) self = "NO-SUCH-CGI!";
1050
1051    /* List available unhidden CGI's and export as "other-cgis" */
1052    for (d = cgi_dispatcher; d->handler; d++)
1053    {
1054       if (strncmp(d->description, "HIDE", 4) && strcmp(d->name, self))
1055       {
1056          snprintf(buf, BUFFER_SIZE, "<li><a href=%s/config/%s>%s</a></li>\n",
1057                HOME_PAGE_URL, d->name, d->description);
1058          tmp = strsav(tmp, buf);
1059       }
1060    }
1061    return(tmp);
1062
1063 }
1064
1065
1066 /*********************************************************************
1067  *
1068  * Function    :  dump_map
1069  *
1070  * Description :  HTML-dump a map for debugging
1071  *
1072  * Parameters  :
1073  *          1  :  map = map to dump
1074  *
1075  * Returns     :  string with HTML
1076  *
1077  *********************************************************************/
1078 char *dump_map(struct map *map)
1079 {
1080    struct map *p = map;
1081    char *ret = NULL;
1082
1083    ret = strsav(ret, "<table>\n");
1084
1085    while (p)
1086    {
1087       ret = strsav(ret, "<tr><td><b>");
1088       ret = strsav(ret, p->name);
1089       ret = strsav(ret, "</b></td><td>");
1090       ret = strsav(ret, p->value);
1091       ret = strsav(ret, "</td></tr>\n");
1092       p = p->next;
1093    }
1094
1095    ret = strsav(ret, "</table>\n");
1096    return(ret);
1097
1098 }
1099
1100
1101 #ifdef STATISTICS
1102 /*********************************************************************
1103  *
1104  * Function    :  add_stats
1105  *
1106  * Description :  Add the blocking statistics to a given map.
1107  *
1108  * Parameters  :
1109  *          1  :  exports = map to write to.
1110  *
1111  * Returns     :  pointer to extended map
1112  *
1113  *********************************************************************/
1114 struct map *add_stats(struct map *exports)
1115 {
1116    float perc_rej;   /* Percentage of http requests rejected */
1117    char buf[1000];
1118    int local_urls_read     = urls_read;
1119    int local_urls_rejected = urls_rejected;
1120
1121    /*
1122     * Need to alter the stats not to include the fetch of this
1123     * page.
1124     *
1125     * Can't do following thread safely! doh!
1126     *
1127     * urls_read--;
1128     * urls_rejected--; * This will be incremented subsequently *
1129     */
1130
1131    if (local_urls_read == 0)
1132    {
1133       exports = map_block_killer(exports, "have-stats");
1134    }
1135    else
1136    {
1137       exports = map_block_killer(exports, "have-no-stats");
1138
1139       perc_rej = (float)local_urls_rejected * 100.0F /
1140             (float)local_urls_read;
1141
1142       sprintf(buf, "%d", local_urls_read);
1143       exports = map(exports, "requests-received", 1, buf, 1);
1144
1145       sprintf(buf, "%d", local_urls_rejected);
1146       exports = map(exports, "requests-blocked", 1, buf, 1);
1147
1148       sprintf(buf, "%6.2f", perc_rej);
1149       exports = map(exports, "percent-blocked", 1, buf, 1);
1150    }
1151
1152    return(exports);
1153
1154 }
1155 #endif /* def STATISTICS */
1156
1157 /*
1158   Local Variables:
1159   tab-width: 3
1160   end:
1161 */