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