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