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