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