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