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