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