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