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