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