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