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