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