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