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