Introduced show-request cgi
[privoxy.git] / cgi.c
1 const char cgi_rcs[] = "$Id: cgi.c,v 1.29 2001/09/20 15:47:44 steudten 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  *                This only contains the framework functions, the
9  *                actual handler functions are declared elsewhere.
10  *                
11  *                Functions declared include:
12  * 
13  *
14  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
15  *                IJBSWA team.  http://ijbswa.sourceforge.net
16  *
17  *                Based on the Internet Junkbuster originally written
18  *                by and Copyright (C) 1997 Anonymous Coders and 
19  *                Junkbusters Corporation.  http://www.junkbusters.com
20  *
21  *                This program is free software; you can redistribute it 
22  *                and/or modify it under the terms of the GNU General
23  *                Public License as published by the Free Software
24  *                Foundation; either version 2 of the License, or (at
25  *                your option) any later version.
26  *
27  *                This program is distributed in the hope that it will
28  *                be useful, but WITHOUT ANY WARRANTY; without even the
29  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
30  *                PARTICULAR PURPOSE.  See the GNU General Public
31  *                License for more details.
32  *
33  *                The GNU General Public License should be included with
34  *                this file.  If not, you can view it at
35  *                http://www.gnu.org/copyleft/gpl.html
36  *                or write to the Free Software Foundation, Inc., 59
37  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
38  *
39  * Revisions   :
40  *    $Log: cgi.c,v $
41  *    Revision 1.29  2001/09/20 15:47:44  steudten
42  *
43  *    Fix BUG: Modify int size to size_t size in fill_template()
44  *     - removes big trouble on machines where sizeof(int) != sizeof(size_t).
45  *
46  *    Revision 1.28  2001/09/19 18:00:37  oes
47  *     - Deletef time() FIXME (Can't fail under Linux either, if
48  *       the argument is guaranteed to be in out address space,
49  *       which it is.)
50  *     - Fixed comments
51  *     - Pointer notation cosmetics
52  *     - Fixed a minor bug in template_fill(): Failiure of
53  *       pcrs_execute() now secure.
54  *
55  *    Revision 1.27  2001/09/16 17:08:54  jongfoster
56  *    Moving simple CGI functions from cgi.c to new file cgisimple.c
57  *
58  *    Revision 1.26  2001/09/16 15:47:37  jongfoster
59  *    First version of CGI-based edit interface.  This is very much a
60  *    work-in-progress, and you can't actually use it to edit anything
61  *    yet.  You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
62  *    to have any effect.
63  *
64  *    Revision 1.25  2001/09/16 15:02:35  jongfoster
65  *    Adding i.j.b/robots.txt.
66  *    Inlining add_stats() since it's only ever called from one place.
67  *
68  *    Revision 1.24  2001/09/16 11:38:01  jongfoster
69  *    Splitting fill_template() into 2 functions:
70  *    template_load() loads the file
71  *    template_fill() performs the PCRS regexps.
72  *    This is because the CGI edit interface has a "table row"
73  *    template which is used many times in the page - this
74  *    change means it's only loaded from disk once.
75  *
76  *    Revision 1.23  2001/09/16 11:16:05  jongfoster
77  *    Better error handling in dispatch_cgi() and parse_cgi_parameters()
78  *
79  *    Revision 1.22  2001/09/16 11:00:10  jongfoster
80  *    New function alloc_http_response, for symmetry with free_http_response
81  *
82  *    Revision 1.21  2001/09/13 23:53:03  jongfoster
83  *    Support for both static and dynamically generated CGI pages.
84  *    Correctly setting Last-Modified: and Expires: HTTP headers.
85  *
86  *    Revision 1.20  2001/09/13 23:40:36  jongfoster
87  *    (Cosmetic only) Indentation correction
88  *
89  *    Revision 1.19  2001/09/13 23:31:25  jongfoster
90  *    Moving image data to cgi.c rather than cgi.h.
91  *
92  *    Revision 1.18  2001/08/05 16:06:20  jongfoster
93  *    Modifiying "struct map" so that there are now separate header and
94  *    "map_entry" structures.  This means that functions which modify a
95  *    map no longer need to return a pointer to the modified map.
96  *    Also, it no longer reverses the order of the entries (which may be
97  *    important with some advanced template substitutions).
98  *
99  *    Revision 1.17  2001/08/05 15:57:38  oes
100  *    Adapted finish_http_response to new list_to_text
101  *
102  *    Revision 1.16  2001/08/01 21:33:18  jongfoster
103  *    Changes to fill_template() that reduce memory usage without having
104  *    an impact on performance.  I also renamed some variables so as not
105  *    to clash with the C++ keywords "new" and "template".
106  *
107  *    Revision 1.15  2001/08/01 21:19:22  jongfoster
108  *    Moving file version information to a separate CGI page.
109  *
110  *    Revision 1.14  2001/08/01 00:19:03  jongfoster
111  *    New function: map_conditional() for an if-then-else syntax.
112  *    Changing to use new version of show_defines()
113  *
114  *    Revision 1.13  2001/07/30 22:08:36  jongfoster
115  *    Tidying up #defines:
116  *    - All feature #defines are now of the form FEATURE_xxx
117  *    - Permanently turned off WIN_GUI_EDIT
118  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
119  *
120  *    Revision 1.12  2001/07/29 18:47:05  jongfoster
121  *    Adding missing #include "loadcfg.h"
122  *
123  *    Revision 1.11  2001/07/18 17:24:37  oes
124  *    Changed to conform to new pcrs interface
125  *
126  *    Revision 1.10  2001/07/13 13:53:13  oes
127  *    Removed all #ifdef PCRS and related code
128  *
129  *    Revision 1.9  2001/06/29 21:45:41  oes
130  *    Indentation, CRLF->LF, Tab-> Space
131  *
132  *    Revision 1.8  2001/06/29 13:21:46  oes
133  *    - Cosmetics: renamed and reordered functions, variables,
134  *      texts, improved comments  etc
135  *
136  *    - Removed ij_untrusted_url() The relevant
137  *      info is now part of the "untrusted" page,
138  *      which is generated by filters.c:trust_url()
139  *
140  *    - Generators of content now call finish_http_response()
141  *      themselves, making jcc.c:chat() a little less
142  *      cluttered
143  *
144  *    - Removed obsolete "Pragma: no-cache" from our headers
145  *
146  *    - http_responses now know their head length
147  *
148  *    - fill_template now uses the new interface to pcrs, so that
149  *       - long jobs (like whole files) no longer have to be assembled
150  *         in a fixed size buffer
151  *       - the new T (trivial) option is used, and the replacement may
152  *         contain Perl syntax backrefs without confusing pcrs
153  *
154  *    - Introduced default_exports() which generates a set of exports
155  *      common to all CGIs and other content generators
156  *
157  *    - Introduced convenience function map_block_killer()
158  *
159  *    - Introduced convenience function make_menu()
160  *
161  *    - Introduced CGI-like function error_response() which generates
162  *      the "No such domain" and "Connect failed" messages using the
163  *      CGI platform
164  *
165  *    - cgi_show_url_info:
166  *      - adapted to new CGI features
167  *      - form and answers now generated from same template
168  *      - http:// prefix in URL now OK
169  *
170  *    - cgi_show_status:
171  *      - adapted to new CGI features
172  *      - no longer uses csp->init_proxy_args
173  *
174  *    - cgi_default:
175  *      - moved menu generation to make_menu()
176  *
177  *    - add_stats now writes single export map entries instead
178  *      of a fixed string
179  *
180  *    - Moved redirect_url() to filters.c
181  *
182  *    - Fixed mem leak in free_http_response(), map_block_killer(),
183  *
184  *    - Removed logentry from cancelled commit
185  *
186  *    Revision 1.7  2001/06/09 10:51:58  jongfoster
187  *    Changing "show URL info" handler to new style.
188  *    Changing BUFSIZ ==> BUFFER_SIZE
189  *
190  *    Revision 1.6  2001/06/07 23:05:19  jongfoster
191  *    Removing code related to old forward and ACL files.
192  *
193  *    Revision 1.5  2001/06/05 19:59:16  jongfoster
194  *    Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
195  *
196  *    Revision 1.4  2001/06/04 10:41:52  swa
197  *    show version string of cgi.h and cgi.c
198  *
199  *    Revision 1.3  2001/06/03 19:12:16  oes
200  *    introduced new cgi handling
201  *
202  *    No revisions before 1.3
203  *
204  **********************************************************************/
205 \f
206
207 #include "config.h"
208
209 #include <stdio.h>
210 #include <sys/types.h>
211 #include <stdlib.h>
212 #include <ctype.h>
213 #include <string.h>
214 #include <assert.h>
215
216 #ifdef _WIN32
217 #define snprintf _snprintf
218 #endif /* def _WIN32 */
219
220 #include "project.h"
221 #include "cgi.h"
222 #include "list.h"
223 #include "encode.h"
224 #include "ssplit.h"
225 #include "errlog.h"
226 #include "miscutil.h"
227 #include "cgisimple.h"
228 #ifdef FEATURE_CGI_EDIT_ACTIONS
229 #include "cgiedit.h"
230 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
231
232 const char cgi_h_rcs[] = CGI_H_VERSION;
233
234 const struct cgi_dispatcher cgi_dispatcher[] = {
235    { "robots.txt", 
236          10, cgi_robots_txt,  
237          "HIDE Sends a robots.txt file to tell robots to go away." }, 
238    { "show-status", 
239          11, cgi_show_status,  
240          "Show information about the current configuration" }, 
241    { "show-url-info",
242          13, cgi_show_url_info, 
243          "Show which actions apply to a URL and why"  },
244    { "show-version", 
245          12, cgi_show_version,  
246          "Show the source code version numbers" }, 
247    { "send-banner",
248          11, cgi_send_banner, 
249          "HIDE Send the transparent or \"Junkbuster\" gif" },
250 #ifdef FEATURE_CGI_EDIT_ACTIONS
251    { "edit-actions-list",
252          17, cgi_edit_actions_list, 
253          "Edit the actions list" },
254    { "edit-actions-submit",
255          19, cgi_edit_actions_submit, 
256          "HIDE Change the actions for (a) specified URL(s)" },
257    { "edit-actions",
258          12, cgi_edit_actions, 
259          "HIDE Edit the actions for (a) specified URL(s)" },
260 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
261    { "show-request", 
262          12, cgi_show_request,  
263          "Show the client's request headers." }, 
264    { "",
265          0, cgi_default,
266          "Junkbuster main page" },
267    { NULL, 0, NULL, NULL }
268 };
269
270
271 /*
272  * Some images
273  *
274  * Hint: You can encode your own GIFs like that:
275  * perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o,", unpack("C", $c)); }'
276  */
277
278 const char image_junkbuster_gif_data[] =
279    "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
280    "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
281    "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
282    "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
283    "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
284    "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
285    "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
286    "\037Q\000\000;";
287
288 const int image_junkbuster_gif_length = sizeof(image_junkbuster_gif_data) - 1;
289
290
291 const char image_blank_gif_data[] =
292    "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
293    "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
294    "\000\001\000\000\002\002D\001\000;";
295
296 const int image_blank_gif_length = sizeof(image_blank_gif_data) - 1;
297
298
299 /*********************************************************************
300  * 
301  * Function    :  dispatch_cgi
302  *
303  * Description :  Checks if a request URL has either the magical hostname
304  *                i.j.b or matches HOME_PAGE_URL/config/. If so, it parses
305  *                the (rest of the) path as a cgi name plus query string,
306  *                prepares a map that maps CGI parameter names to their values,
307  *                initializes the http_response struct, and calls the 
308  *                relevant CGI handler function.
309  *
310  * Parameters  :
311  *          1  :  csp = Current client state (buffers, headers, etc...)
312  *
313  * Returns     :  http_response if match, NULL if nonmatch or handler fail
314  *
315  *********************************************************************/
316 struct http_response *dispatch_cgi(struct client_state *csp)
317 {
318    char *argstring = NULL;
319    const struct cgi_dispatcher *d;
320    struct map *param_list;
321    struct http_response *rsp;
322
323    /*
324     * Should we intercept ?
325     */
326
327    /* Either the host matches CGI_PREFIX_HOST ..*/
328    if (0 == strcmpic(csp->http->host, CGI_PREFIX_HOST))
329    {
330       /* ..then the path will all be for us */
331       argstring = csp->http->path;
332    }
333    /* Or it's the host part HOME_PAGE_URL, and the path /config ? */
334    else if (   (0 == strcmpic(csp->http->host, HOME_PAGE_URL + 7 ))
335             && (0 == strncmpic(csp->http->path,"/config", 7))
336             && ((csp->http->path[7] == '/') || (csp->http->path[7] == '\0')))
337    {
338       /* then it's everything following "/config" */
339       argstring = csp->http->path + 7;
340    }
341    else
342    {
343       return NULL;
344    }
345
346    /* 
347     * This is a CGI call.
348     */
349
350    /* Get mem for response or fail*/
351    if (NULL == (rsp = alloc_http_response()))
352    {
353       return NULL;
354    }
355
356
357    /* Remove leading slash */
358    if (*argstring == '/')
359    {
360       argstring++;
361    }
362
363    log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
364    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", 
365                             csp->ip_addr_str, csp->http->cmd); 
366
367    /* Find and start the right CGI function*/
368    for (d = cgi_dispatcher; d->handler; d++)
369    {
370       if (strncmp(argstring, d->name, d->name_length) == 0)
371       {
372          if (NULL == (param_list = 
373              parse_cgi_parameters(argstring + d->name_length)))
374          {
375             free_map(param_list);
376             free_http_response(rsp);
377             return(NULL);
378          }
379          if ((d->handler)(csp, rsp, param_list))
380          {
381             free_map(param_list);
382             free_http_response(rsp);
383             return(NULL);
384          }
385
386          free_map(param_list);
387          return(finish_http_response(rsp));
388       }
389    }
390
391    /* Can't get here, since cgi_default will match all requests */
392    free_http_response(rsp);
393    return(NULL);
394
395 }
396
397
398 /*********************************************************************
399  *
400  * Function    :  parse_cgi_parameters
401  *
402  * Description :  Parse a URL-encoded argument string into name/value
403  *                pairs and store them in a struct map list.
404  *
405  * Parameters  :
406  *          1  :  string = string to be parsed 
407  *
408  * Returns     :  pointer to param list, or NULL if out of memory.
409  *
410  *********************************************************************/
411 struct map *parse_cgi_parameters(char *argstring)
412 {
413    char *tmp, *p;
414    char *vector[BUFFER_SIZE];
415    int pairs, i;
416    struct map *cgi_params;
417
418    if (NULL == (cgi_params = new_map()))
419    {
420       return NULL;
421    }
422
423    if(*argstring == '?')
424    {
425       argstring++;
426    }
427    if (NULL == (tmp = strdup(argstring)))
428    {
429       free_map(cgi_params);
430       return NULL;
431    }
432
433    pairs = ssplit(tmp, "&", vector, SZ(vector), 1, 1);
434
435    for (i = 0; i < pairs; i++)
436    {
437       if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
438       {
439          *p = '\0';
440          map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0);
441       }
442    }
443
444    free(tmp);
445    return(cgi_params);
446
447 }
448
449
450 /*********************************************************************
451  *
452  * Function    :  error_response
453  *
454  * Description :  returns an http_response that explains the reason
455  *                why a request failed.
456  *
457  * Parameters  :
458  *          1  :  csp = Current client state (buffers, headers, etc...)
459  *          2  :  templatename = Which template should be used for the answer
460  *          3  :  errno = system error number
461  *
462  * Returns     :  NULL if no memory, else http_response
463  *
464  *********************************************************************/
465 struct http_response *error_response(struct client_state *csp, const char *templatename, int err)
466 {
467    struct http_response *rsp;
468    struct map * exports = default_exports(csp, NULL);
469
470    if (NULL == (rsp = alloc_http_response()))
471    {
472       return NULL;
473    }
474
475    map(exports, "host-html", 1, html_encode(csp->http->host), 0);
476    map(exports, "hostport", 1, csp->http->hostport, 1);
477    map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
478    map(exports, "path", 1, csp->http->path, 1);
479    map(exports, "path-html", 1, html_encode(csp->http->path), 0);
480    map(exports, "error", 1, safe_strerror(err), 0);
481    map(exports, "host-ip", 1, csp->http->host_ip_addr_str, 1);
482
483    rsp->body = template_load(csp, templatename);
484    template_fill(&rsp->body, exports);
485    free_map(exports);
486
487    if (!strcmp(templatename, "no-such-domain"))
488    {
489       rsp->status = strdup("404 No such domain"); 
490    }
491    else if (!strcmp(templatename, "connect-failed"))
492    {
493       rsp->status = strdup("503 Connect failed");
494    }
495
496    return(finish_http_response(rsp));
497
498 }
499
500
501 /*********************************************************************
502  *
503  * Function    :  get_http_time
504  *
505  * Description :  Get the time in a format suitable for use in a
506  *                HTTP header - e.g.:
507  *                "Sun, 06 Nov 1994 08:49:37 GMT"
508  *
509  * Parameters  :  
510  *          1  :  time_offset = Time returned will be current time
511  *                              plus this number of seconds.
512  *          2  :  buf = Destination for result.  Must be long enough
513  *                      to hold 29 characters plus a trailing zero.
514  *
515  * Returns     :  N/A
516  *
517  *********************************************************************/
518 void get_http_time(int time_offset, char *buf)
519 {
520    static const char day_names[7][4] =
521       { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
522    static const char month_names[12][4] =
523       { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
524         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
525
526    struct tm *t;
527    time_t current_time;
528
529    assert(buf);
530
531    time(&current_time); /* get current time */
532
533    current_time += time_offset;
534
535    /* get and save the gmt */
536    t = gmtime(&current_time);
537
538    /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
539    snprintf(buf, 30,
540       "%s, %02d %s %4d %02d:%02d:%02d GMT",
541       day_names[t->tm_wday],
542       t->tm_mday,
543       month_names[t->tm_mon],
544       t->tm_year + 1900,
545       t->tm_hour,
546       t->tm_min,
547       t->tm_sec
548       );
549    buf[32] = '\0';
550
551 }
552
553
554 /*********************************************************************
555  *
556  * Function    :  finish_http_response
557  *
558  * Description :  Fill in the missing headers in an http response,
559  *                and flatten the headers to an http head.
560  *
561  * Parameters  :
562  *          1  :  rsp = pointer to http_response to be processed
563  *
564  * Returns     :  http_response, or NULL on failiure
565  *
566  *********************************************************************/
567 struct http_response *finish_http_response(struct http_response *rsp)
568 {
569    char buf[BUFFER_SIZE];
570
571    /* 
572     * Fill in the HTTP Status
573     */
574    sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
575    enlist_first(rsp->headers, buf);
576
577    /* 
578     * Set the Content-Length
579     */
580    if (rsp->content_length == 0)
581    {
582       rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
583    }
584    sprintf(buf, "Content-Length: %d", rsp->content_length);
585    enlist(rsp->headers, buf);
586
587    /* 
588     * Fill in the default headers:
589     *
590     * Content-Type: default to text/html if not already specified.
591     * Date: set to current date/time.
592     * Last-Modified: set to date/time the page was last changed.
593     * Expires: set to date/time page next needs reloading.
594     * Cache-Control: set to "no-cache" if applicable.
595     * 
596     * See http://www.w3.org/Protocols/rfc2068/rfc2068
597     */
598    enlist_unique(rsp->headers, "Content-Type: text/html", 13);
599
600    if (rsp->is_static)
601    {
602       /*
603        * Set Expires to about 10 min into the future so it'll get reloaded
604        * occasionally, e.g. if IJB gets upgraded.
605        */
606
607       get_http_time(0, buf);
608       enlist_unique_header(rsp->headers, "Date", buf);
609
610       /* Some date in the past. */
611       enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
612
613       get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
614       enlist_unique_header(rsp->headers, "Expires", buf);
615    }
616    else
617    {
618       /*
619        * Compliant browsers should not cache this due to the "Cache-Control"
620        * setting.  However, to be certain, we also set both "Last-Modified"
621        * and "Expires" to the current time.
622        */
623       enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
624       get_http_time(0, buf);
625       enlist_unique_header(rsp->headers, "Date", buf);
626       enlist_unique_header(rsp->headers, "Last-Modified", buf);
627       enlist_unique_header(rsp->headers, "Expires", buf);
628    }
629
630
631    /* 
632     * Write the head
633     */
634    if (NULL == (rsp->head = list_to_text(rsp->headers)))
635    {
636       free_http_response(rsp);
637       return(NULL);
638    }
639    rsp->head_length = strlen(rsp->head);
640
641    return(rsp);
642
643 }
644   
645
646 /*********************************************************************
647  *
648  * Function    :  alloc_http_response
649  *
650  * Description :  Allocates a new http_response structure.
651  *
652  * Parameters  :  N/A
653  *
654  * Returns     :  pointer to a new http_response, or NULL.
655  *
656  *********************************************************************/
657 struct http_response *alloc_http_response(void)
658 {
659    return (struct http_response *) zalloc(sizeof(struct http_response));
660
661 }
662
663
664 /*********************************************************************
665  *
666  * Function    :  free_http_response
667  *
668  * Description :  Free the memory occupied by an http_response
669  *                and its depandant structures.
670  *
671  * Parameters  :
672  *          1  :  rsp = pointer to http_response to be freed
673  *
674  * Returns     :  N/A
675  *
676  *********************************************************************/
677 void free_http_response(struct http_response *rsp)
678 {
679    if (rsp)
680    {
681       freez(rsp->status);
682       freez(rsp->head);
683       freez(rsp->body);
684       destroy_list(rsp->headers);
685       free(rsp);
686    }
687
688 }
689
690
691 /*********************************************************************
692  *
693  * Function    :  fill_template
694  *
695  * Description :  CGI support function that loads a given HTML
696  *                template from the confdir, ignoring comment
697  *                lines. 
698  *
699  * Parameters  :
700  *           1 :  csp = Current client state (buffers, headers, etc...)
701  *           3 :  template = name of the HTML template to be used
702  *
703  * Returns     :  char * with loaded template, or NULL if failure
704  *
705  *********************************************************************/
706 char *template_load(struct client_state *csp, const char *templatename)
707 {
708    char buf[BUFFER_SIZE];
709    char *file_buffer = NULL;
710    FILE *fp;
711
712    /*
713     * Open template file or fail
714     */
715    snprintf(buf, BUFFER_SIZE, "%s/templates/%s", csp->config->confdir, templatename);
716
717    if(NULL == (fp = fopen(buf, "r")))
718    {
719       log_error(LOG_LEVEL_ERROR, "error loading template %s: %E", buf);
720       return NULL;
721    }
722    
723
724    /* 
725     * Read the file, ignoring comments
726     */
727    while (fgets(buf, BUFFER_SIZE, fp))
728    {
729       /* skip lines starting with '#' */
730       if(*buf == '#')
731       {
732          continue;
733       }
734    
735       file_buffer = strsav(file_buffer, buf);
736    }
737    fclose(fp);
738
739    return(file_buffer);
740
741 }
742
743
744 /*********************************************************************
745  *
746  * Function    :  fill_template
747  *
748  * Description :  CGI support function that fills in a pre-loaded
749  *                HTML template by replacing @name@ with value using
750  *                pcrs, for each item in the output map.
751  *
752  *                Note that a leading '$' charachter in the export map's
753  *                values will be stripped and toggle on backreference
754  *                interpretation.
755  *
756  * Parameters  :
757  *           1 :  template_ptr = IN: Template to be filled out.
758  *                                   Will be free()d.
759  *                               OUT: Filled out template.
760  *                                    Caller must free().
761  *           2 :  exports = map with fill in symbol -> name pairs
762  *
763  * Returns     :  N/A
764  *
765  *********************************************************************/
766 void template_fill(char **template_ptr, struct map *exports)
767 {
768    struct map_entry *m;
769    pcrs_job *job;
770    char buf[BUFFER_SIZE];
771    char *tmp_out_buffer;
772    char *file_buffer;
773    size_t  size;
774    int error;
775    const char *flags;
776
777    assert(template_ptr);
778    assert(*template_ptr);
779    assert(exports);
780
781    file_buffer = *template_ptr;
782    size = strlen(file_buffer) + 1;
783
784    /* 
785     * Assemble pcrs joblist from exports map
786     */
787    for (m = exports->first; m != NULL; m = m->next)
788    {
789       if (*m->name == '$')
790       {
791          /*
792           * First character of name is '$', so remove this flag
793           * character and allow backreferences ($1 etc) in the
794           * "replace with" text.
795           */
796          snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
797          flags = "sigU";
798       }
799       else
800       {
801          /*
802           * Treat the "replace with" text as a literal string - 
803           * no quoting needed, no backreferences allowed.
804           * ("Trivial" ['T'] flag).
805           */
806          flags = "sigTU";
807
808          /* Enclose name in @@ */
809          snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
810       }
811
812
813       log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
814
815       /* Make and run job. */
816       job = pcrs_compile(buf, m->value, flags,  &error);
817       if (job == NULL) 
818       {
819          log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
820       }
821       else
822       {
823          pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
824          if (NULL != tmp_out_buffer)
825          {
826             free(file_buffer);
827             file_buffer = tmp_out_buffer;
828          }
829          pcrs_free_job(job);
830       }
831    }
832
833    /*
834     * Return
835     */
836    *template_ptr = file_buffer;
837
838 }
839
840
841 /*********************************************************************
842  *
843  * Function    :  default_exports
844  *
845  * Description :  returns a struct map list that contains exports
846  *                which are common to all CGI functions.
847  *
848  * Parameters  :
849  *          1  :  exports = Structure to write output to.  This
850  *                structure should be newly allocated and will be
851  *                zeroed.
852  *          1  :  csp = Current client state (buffers, headers, etc...)
853  *          2  :  caller = name of CGI who calls us and which should
854  *                         be excluded from the generated menu.
855  * Returns     :  NULL if no memory, else map
856  *
857  *********************************************************************/
858 struct map *default_exports(const struct client_state *csp, const char *caller)
859 {
860    char buf[20];
861    struct map * exports = new_map();
862
863    map(exports, "version", 1, VERSION, 1);
864    map(exports, "my-ip-address", 1, csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown", 1);
865    map(exports, "my-hostname", 1, csp->my_hostname ? csp->my_hostname : "unknown", 1);
866    map(exports, "admin-address", 1, csp->config->admin_address ? csp->config->admin_address : "fill@me.in.please", 1);
867    map(exports, "homepage", 1, HOME_PAGE_URL, 1);
868    map(exports, "default-cgi", 1, HOME_PAGE_URL "/config", 1);
869    map(exports, "menu", 1, make_menu(caller), 0);
870    map(exports, "code-status", 1, CODE_STATUS, 1);
871
872    snprintf(buf, 20, "%d", csp->config->hport);
873    map(exports, "my-port", 1, buf, 1);
874
875    if(!strcmp(CODE_STATUS, "stable"))
876    {
877       map_block_killer(exports, "unstable");
878    }
879
880    if(csp->config->proxy_info_url != NULL)
881    {
882       map(exports, "proxy-info-url", 1, csp->config->proxy_info_url, 1);
883    }
884    else
885    {
886       map_block_killer(exports, "have-proxy-info");
887    }   
888
889    return (exports);
890
891 }
892
893
894 /*********************************************************************
895  *
896  * Function    :  map_block_killer
897  *
898  * Description :  Convenience function.
899  *                Adds a "killer" for the conditional HTML-template
900  *                block <name>, i.e. a substitution of the regex
901  *                "if-<name>-start.*if-<name>-end" to the given
902  *                export list.
903  *
904  * Parameters  :  
905  *          1  :  exports = map to extend
906  *          2  :  name = name of conditional block
907  *
908  * Returns     :  extended map
909  *
910  *********************************************************************/
911 void map_block_killer(struct map *exports, const char *name)
912 {
913    char buf[1000]; /* Will do, since the names are hardwired */
914
915    snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
916    map(exports, buf, 1, "", 1);
917
918 }
919
920
921 /*********************************************************************
922  *
923  * Function    :  map_conditional
924  *
925  * Description :  Convenience function.
926  *                Adds an "if-then-else" for the conditional HTML-template
927  *                block <name>, i.e. a substitution of the form:
928  *                @if-<name>-then@
929  *                   True text
930  *                @else-not-<name>@
931  *                   False text
932  *                @endif-<name>@
933  *
934  *                The control structure and one of the alternatives
935  *                will be hidden.
936  *
937  * Parameters  :  
938  *          1  :  exports = map to extend
939  *          2  :  name = name of conditional block
940  *          3  :  choose_first = nonzero for first, zero for second.
941  *
942  * Returns     :  extended map
943  *
944  *********************************************************************/
945 void map_conditional(struct map *exports, const char *name, int choose_first)
946 {
947    char buf[1000]; /* Will do, since the names are hardwired */
948
949    snprintf(buf, 1000, (choose_first
950       ? "else-not-%s@.*@endif-%s"
951       : "if-%s-then@.*@else-not-%s"),
952       name, name);
953    map(exports, buf, 1, "", 1);
954
955    snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
956    map(exports, buf, 1, "", 1);
957
958 }
959
960
961 /*********************************************************************
962  *
963  * Function    :  make_menu
964  *
965  * Description :  Returns an HTML-formatted menu of the available 
966  *                unhidden CGIs, excluding the one given in <self>.
967  *
968  * Parameters  :  self = name of CGI to leave out, can be NULL
969  *
970  * Returns     :  menu string
971  *
972  *********************************************************************/
973 char *make_menu(const char *self)
974 {
975    const struct cgi_dispatcher *d;
976    char buf[BUFFER_SIZE];
977    char *result = NULL;
978
979    if (self == NULL)
980    {
981       self = "NO-SUCH-CGI!";
982    }
983
984    /* List available unhidden CGI's and export as "other-cgis" */
985    for (d = cgi_dispatcher; d->handler; d++)
986    {
987       if (strncmp(d->description, "HIDE", 4) && strcmp(d->name, self))
988       {
989          snprintf(buf, BUFFER_SIZE, "<li><a href=%s/config/%s>%s</a></li>\n",
990                HOME_PAGE_URL, d->name, d->description);
991          result = strsav(result, buf);
992       }
993    }
994    return(result);
995
996 }
997
998
999 /*********************************************************************
1000  *
1001  * Function    :  dump_map
1002  *
1003  * Description :  HTML-dump a map for debugging
1004  *
1005  * Parameters  :
1006  *          1  :  the_map = map to dump
1007  *
1008  * Returns     :  string with HTML
1009  *
1010  *********************************************************************/
1011 char *dump_map(const struct map *the_map)
1012 {
1013    struct map_entry *cur_entry = the_map->first;
1014    char *ret = NULL;
1015
1016    ret = strsav(ret, "<table>\n");
1017
1018    while (cur_entry)
1019    {
1020       ret = strsav(ret, "<tr><td><b>");
1021       ret = strsav(ret, cur_entry->name);
1022       ret = strsav(ret, "</b></td><td>");
1023       ret = strsav(ret, cur_entry->value);
1024       ret = strsav(ret, "</td></tr>\n");
1025       cur_entry = cur_entry->next;
1026    }
1027
1028    ret = strsav(ret, "</table>\n");
1029    return(ret);
1030
1031 }
1032
1033
1034 /*
1035   Local Variables:
1036   tab-width: 3
1037   end:
1038 */