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