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