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