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