Fixing signed/unsigned comparison warning.
[privoxy.git] / cgi.c
1 const char cgi_rcs[] = "$Id: cgi.c,v 1.24 2001/09/16 11:38:01 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  *                
9  *                Functions declared include:
10  * 
11  *
12  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
13  *                IJBSWA team.  http://ijbswa.sourceforge.net
14  *
15  *                Based on the Internet Junkbuster originally written
16  *                by and Copyright (C) 1997 Anonymous Coders and 
17  *                Junkbusters Corporation.  http://www.junkbusters.com
18  *
19  *                This program is free software; you can redistribute it 
20  *                and/or modify it under the terms of the GNU General
21  *                Public License as published by the Free Software
22  *                Foundation; either version 2 of the License, or (at
23  *                your option) any later version.
24  *
25  *                This program is distributed in the hope that it will
26  *                be useful, but WITHOUT ANY WARRANTY; without even the
27  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
28  *                PARTICULAR PURPOSE.  See the GNU General Public
29  *                License for more details.
30  *
31  *                The GNU General Public License should be included with
32  *                this file.  If not, you can view it at
33  *                http://www.gnu.org/copyleft/gpl.html
34  *                or write to the Free Software Foundation, Inc., 59
35  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
36  *
37  * Revisions   :
38  *    $Log: cgi.c,v $
39  *    Revision 1.24  2001/09/16 11:38:01  jongfoster
40  *    Splitting fill_template() into 2 functions:
41  *    template_load() loads the file
42  *    template_fill() performs the PCRS regexps.
43  *    This is because the CGI edit interface has a "table row"
44  *    template which is used many times in the page - this
45  *    change means it's only loaded from disk once.
46  *
47  *    Revision 1.23  2001/09/16 11:16:05  jongfoster
48  *    Better error handling in dispatch_cgi() and parse_cgi_parameters()
49  *
50  *    Revision 1.22  2001/09/16 11:00:10  jongfoster
51  *    New function alloc_http_response, for symmetry with free_http_response
52  *
53  *    Revision 1.21  2001/09/13 23:53:03  jongfoster
54  *    Support for both static and dynamically generated CGI pages.
55  *    Correctly setting Last-Modified: and Expires: HTTP headers.
56  *
57  *    Revision 1.20  2001/09/13 23:40:36  jongfoster
58  *    (Cosmetic only) Indentation correction
59  *
60  *    Revision 1.19  2001/09/13 23:31:25  jongfoster
61  *    Moving image data to cgi.c rather than cgi.h.
62  *
63  *    Revision 1.18  2001/08/05 16:06:20  jongfoster
64  *    Modifiying "struct map" so that there are now separate header and
65  *    "map_entry" structures.  This means that functions which modify a
66  *    map no longer need to return a pointer to the modified map.
67  *    Also, it no longer reverses the order of the entries (which may be
68  *    important with some advanced template substitutions).
69  *
70  *    Revision 1.17  2001/08/05 15:57:38  oes
71  *    Adapted finish_http_response to new list_to_text
72  *
73  *    Revision 1.16  2001/08/01 21:33:18  jongfoster
74  *    Changes to fill_template() that reduce memory usage without having
75  *    an impact on performance.  I also renamed some variables so as not
76  *    to clash with the C++ keywords "new" and "template".
77  *
78  *    Revision 1.15  2001/08/01 21:19:22  jongfoster
79  *    Moving file version information to a separate CGI page.
80  *
81  *    Revision 1.14  2001/08/01 00:19:03  jongfoster
82  *    New function: map_conditional() for an if-then-else syntax.
83  *    Changing to use new version of show_defines()
84  *
85  *    Revision 1.13  2001/07/30 22:08:36  jongfoster
86  *    Tidying up #defines:
87  *    - All feature #defines are now of the form FEATURE_xxx
88  *    - Permanently turned off WIN_GUI_EDIT
89  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
90  *
91  *    Revision 1.12  2001/07/29 18:47:05  jongfoster
92  *    Adding missing #include "loadcfg.h"
93  *
94  *    Revision 1.11  2001/07/18 17:24:37  oes
95  *    Changed to conform to new pcrs interface
96  *
97  *    Revision 1.10  2001/07/13 13:53:13  oes
98  *    Removed all #ifdef PCRS and related code
99  *
100  *    Revision 1.9  2001/06/29 21:45:41  oes
101  *    Indentation, CRLF->LF, Tab-> Space
102  *
103  *    Revision 1.8  2001/06/29 13:21:46  oes
104  *    - Cosmetics: renamed and reordered functions, variables,
105  *      texts, improved comments  etc
106  *
107  *    - Removed ij_untrusted_url() The relevant
108  *      info is now part of the "untrusted" page,
109  *      which is generated by filters.c:trust_url()
110  *
111  *    - Generators of content now call finish_http_response()
112  *      themselves, making jcc.c:chat() a little less
113  *      cluttered
114  *
115  *    - Removed obsolete "Pragma: no-cache" from our headers
116  *
117  *    - http_responses now know their head length
118  *
119  *    - fill_template now uses the new interface to pcrs, so that
120  *       - long jobs (like whole files) no longer have to be assembled
121  *         in a fixed size buffer
122  *       - the new T (trivial) option is used, and the replacement may
123  *         contain Perl syntax backrefs without confusing pcrs
124  *
125  *    - Introduced default_exports() which generates a set of exports
126  *      common to all CGIs and other content generators
127  *
128  *    - Introduced convenience function map_block_killer()
129  *
130  *    - Introduced convenience function make_menu()
131  *
132  *    - Introduced CGI-like function error_response() which generates
133  *      the "No such domain" and "Connect failed" messages using the
134  *      CGI platform
135  *
136  *    - cgi_show_url_info:
137  *      - adapted to new CGI features
138  *      - form and answers now generated from same template
139  *      - http:// prefix in URL now OK
140  *
141  *    - cgi_show_status:
142  *      - adapted to new CGI features
143  *      - no longer uses csp->init_proxy_args
144  *
145  *    - cgi_default:
146  *      - moved menu generation to make_menu()
147  *
148  *    - add_stats now writes single export map entries instead
149  *      of a fixed string
150  *
151  *    - Moved redirect_url() to filters.c
152  *
153  *    - Fixed mem leak in free_http_response(), map_block_killer(),
154  *
155  *    - Removed logentry from cancelled commit
156  *
157  *    Revision 1.7  2001/06/09 10:51:58  jongfoster
158  *    Changing "show URL info" handler to new style.
159  *    Changing BUFSIZ ==> BUFFER_SIZE
160  *
161  *    Revision 1.6  2001/06/07 23:05:19  jongfoster
162  *    Removing code related to old forward and ACL files.
163  *
164  *    Revision 1.5  2001/06/05 19:59:16  jongfoster
165  *    Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
166  *
167  *    Revision 1.4  2001/06/04 10:41:52  swa
168  *    show version string of cgi.h and cgi.c
169  *
170  *    Revision 1.3  2001/06/03 19:12:16  oes
171  *    introduced new cgi handling
172  *
173  *    No revisions before 1.3
174  *
175  **********************************************************************/
176 \f
177
178 #include "config.h"
179
180 #include <stdio.h>
181 #include <sys/types.h>
182 #include <stdlib.h>
183 #include <ctype.h>
184 #include <string.h>
185 #include <assert.h>
186
187 #ifdef _WIN32
188 #define snprintf _snprintf
189 #endif /* def _WIN32 */
190
191 #include "project.h"
192 #include "cgi.h"
193 #include "list.h"
194 #include "encode.h"
195 #include "ssplit.h"
196 #include "jcc.h"
197 #include "filters.h"
198 #include "actions.h"
199 #include "errlog.h"
200 #include "miscutil.h"
201 #include "showargs.h"
202 #include "loadcfg.h"
203
204 const char cgi_h_rcs[] = CGI_H_VERSION;
205
206 const struct cgi_dispatcher cgi_dispatcher[] = {
207    { "robots.txt", 
208          10, cgi_robots_txt,  
209          "HIDE Sends a robots.txt file to tell robots to go away." }, 
210    { "show-status", 
211          11, cgi_show_status,  
212          "Show information about the current configuration" }, 
213    { "show-url-info",
214          13, cgi_show_url_info, 
215          "Show which actions apply to a URL and why"  },
216    { "show-version", 
217          12, cgi_show_version,  
218          "Show the source code version numbers" }, 
219    { "send-banner",
220          11, cgi_send_banner, 
221          "HIDE Send the transparent or \"Junkbuster\" gif" },
222    { "",
223          0, cgi_default,
224          "Junkbuster main page" },
225    { NULL, 0, NULL, NULL }
226 };
227
228
229 /*
230  * Some images
231  *
232  * Hint: You can encode your own GIFs like that:
233  * perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o,", unpack("C", $c)); }'
234  */
235
236 const char image_junkbuster_gif_data[] =
237    "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
238    "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
239    "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
240    "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
241    "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
242    "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
243    "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
244    "\037Q\000\000;";
245
246 const int image_junkbuster_gif_length = sizeof(image_junkbuster_gif_data) - 1;
247
248
249 const char image_blank_gif_data[] =
250    "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
251    "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
252    "\000\001\000\000\002\002D\001\000;";
253
254 const int image_blank_gif_length = sizeof(image_blank_gif_data) - 1;
255
256
257 /*********************************************************************
258  * 
259  * Function    :  dispatch_cgi
260  *
261  * Description :  Checks if a request URL has either the magical hostname
262  *                i.j.b or matches HOME_PAGE_URL/config/. If so, it parses
263  *                the (rest of the) path as a cgi name plus query string,
264  *                prepares a map that maps CGI parameter names to their values,
265  *                initializes the http_response struct, and calls the 
266  *                relevant CGI handler function.
267  *
268  * Parameters  :
269  *          1  :  csp = Current client state (buffers, headers, etc...)
270  *
271  * Returns     :  http_response if match, NULL if nonmatch or handler fail
272  *
273  *********************************************************************/
274 struct http_response *dispatch_cgi(struct client_state *csp)
275 {
276    char *argstring = NULL;
277    const struct cgi_dispatcher *d;
278    struct map *param_list;
279    struct http_response *rsp;
280
281    /*
282     * Should we intercept ?
283     */
284
285    /* Either the host matches CGI_PREFIX_HOST ..*/
286    if (0 == strcmpic(csp->http->host, CGI_PREFIX_HOST))
287    {
288       /* ..then the path will all be for us */
289       argstring = csp->http->path;
290    }
291    /* Or it's the host part HOME_PAGE_URL, and the path /config ? */
292    else if (   (0 == strcmpic(csp->http->host, HOME_PAGE_URL + 7 ))
293             && (0 == strncmpic(csp->http->path,"/config", 7))
294             && ((csp->http->path[7] == '/') || (csp->http->path[7] == '\0')))
295    {
296       /* then it's everything following "/config" */
297       argstring = csp->http->path + 7;
298    }
299    else
300    {
301       return NULL;
302    }
303
304    /* 
305     * This is a CGI call.
306     */
307
308    /* Get mem for response or fail*/
309    if (NULL == (rsp = alloc_http_response()))
310    {
311       return NULL;
312    }
313
314    /* Remove leading slash */
315    if (*argstring == '/')
316    {
317       argstring++;
318    }
319
320    log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
321    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", 
322                             csp->ip_addr_str, csp->http->cmd); 
323
324    /* Find and start the right CGI function*/
325    for (d = cgi_dispatcher; d->handler; d++)
326    {
327       if (strncmp(argstring, d->name, d->name_length) == 0)
328       {
329          if (NULL == (param_list = 
330              parse_cgi_parameters(argstring + d->name_length)))
331          {
332             free_map(param_list);
333             free_http_response(rsp);
334             return(NULL);
335          }
336          if ((d->handler)(csp, rsp, param_list))
337          {
338             free_map(param_list);
339             free_http_response(rsp);
340             return(NULL);
341          }
342
343          free_map(param_list);
344          return(finish_http_response(rsp));
345       }
346    }
347
348    /* Can't get here, since cgi_default will match all requests */
349    free_http_response(rsp);
350    return(NULL);
351 }
352
353
354 /*********************************************************************
355  *
356  * Function    :  parse_cgi_parameters
357  *
358  * Description :  Parse a URL-encoded argument string into name/value
359  *                pairs and store them in a struct map list.
360  *
361  * Parameters  :
362  *          1  :  string = string to be parsed 
363  *
364  * Returns     :  pointer to param list, or NULL if out of memory.
365  *
366  *********************************************************************/
367 struct map *parse_cgi_parameters(char *argstring)
368 {
369    char *tmp, *p;
370    char *vector[BUFFER_SIZE];
371    int pairs, i;
372    struct map *cgi_params;
373
374    if (NULL == (cgi_params = new_map()))
375    {
376       return NULL;
377    }
378
379    if(*argstring == '?')
380    {
381       argstring++;
382    }
383    if (NULL == (tmp = strdup(argstring)))
384    {
385       free_map(cgi_params);
386       return NULL;
387    }
388
389    pairs = ssplit(tmp, "&", vector, SZ(vector), 1, 1);
390
391    for (i = 0; i < pairs; i++)
392    {
393       if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
394       {
395          *p = '\0';
396          map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0);
397       }
398    }
399
400    free(tmp);
401    return(cgi_params);
402
403 }
404
405
406 /*********************************************************************
407  *
408  * Function    :  cgi_default
409  *
410  * Description :  CGI function that is called if no action was given.
411  *                Lists menu of available unhidden CGIs.
412  *               
413  * Parameters  :
414  *           1 :  csp = Current client state (buffers, headers, etc...)
415  *           2 :  rsp = http_response data structure for output
416  *           3 :  parameters = map of cgi parameters
417  *
418  * Returns     :  0
419  *
420  *********************************************************************/
421 int cgi_default(struct client_state *csp, struct http_response *rsp,
422                 struct map *parameters)
423 {
424    char *p;
425    char *tmp = NULL;
426    struct map * exports = default_exports(csp, "");
427
428    /* If there were other parameters, export a dump as "cgi-parameters" */
429    if(parameters)
430    {
431       p = dump_map(parameters);
432       tmp = strsav(tmp, "<p>What made you think this cgi takes parameters?\n"
433                         "Anyway, here they are, in case you're interested:</p>\n");
434       tmp = strsav(tmp, p);
435       map(exports, "cgi-parameters", 1, tmp, 0);
436       free(p);
437    }
438    else
439    {
440       map(exports, "cgi-parameters", 1, "", 1);
441    }
442
443    rsp->body = template_load(csp, "default");
444    template_fill(&rsp->body, exports);
445    free_map(exports);
446    return(0);
447
448 }
449
450
451 /*********************************************************************
452  *
453  * Function    :  cgi_send_banner
454  *
455  * Description :  CGI function that returns a banner. 
456  *
457  * Parameters  :
458  *           1 :  csp = Current client state (buffers, headers, etc...)
459  *           2 :  rsp = http_response data structure for output
460  *           3 :  parameters = map of cgi parameters
461  *
462  * CGI Parameters :
463  *           type : Selects the type of banner between "trans" and "jb".
464  *                  Defaults to "jb" if absent or != "trans".
465  *
466  * Returns     :  0
467  *
468  *********************************************************************/
469 int cgi_send_banner(struct client_state *csp, struct http_response *rsp,
470                     struct map *parameters)
471 {
472    if(strcmp(lookup(parameters, "type"), "trans"))
473    {
474       rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
475       rsp->content_length = image_junkbuster_gif_length;
476    }
477    else
478    {
479       rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
480       rsp->content_length = image_blank_gif_length;
481    }   
482
483    enlist(rsp->headers, "Content-Type: image/gif");
484    rsp->is_static = 1;
485
486    return(0);
487
488 }
489
490
491 /*********************************************************************
492  *
493  * Function    :  cgi_show_version
494  *
495  * Description :  CGI function that returns a a web page describing the
496  *                file versions of IJB.
497  *
498  * Parameters  :
499  *           1 :  csp = Current client state (buffers, headers, etc...)
500  *           2 :  rsp = http_response data structure for output
501  *           3 :  parameters = map of cgi parameters
502  *
503  * CGI Parameters :
504  *           type : Selects the type of banner between "trans" and "jb".
505  *                  Defaults to "jb" if absent or != "trans".
506  *
507  * Returns     :  0
508  *
509  *********************************************************************/
510 int cgi_show_version(struct client_state *csp, struct http_response *rsp,
511                      struct map *parameters)
512 {
513    struct map * exports = default_exports(csp, "show-version");
514
515    map(exports, "sourceversions", 1, show_rcs(), 0);  
516
517    rsp->body = template_load(csp, "show-version");
518    template_fill(&rsp->body, exports);
519    free_map(exports);
520    return(0);
521
522 }
523
524  
525 /*********************************************************************
526  *
527  * Function    :  cgi_show_status
528  *
529  * Description :  CGI function that returns a a web page describing the
530  *                current status of IJB.
531  *
532  * Parameters  :
533  *           1 :  csp = Current client state (buffers, headers, etc...)
534  *           2 :  rsp = http_response data structure for output
535  *           3 :  parameters = map of cgi parameters
536  *
537  * CGI Parameters :
538  *           type : Selects the type of banner between "trans" and "jb".
539  *                  Defaults to "jb" if absent or != "trans".
540  *
541  * Returns     :  0
542  *
543  *********************************************************************/
544 int cgi_show_status(struct client_state *csp, struct http_response *rsp,
545                     struct map *parameters)
546 {
547    char *s = NULL;
548    int i;
549
550    FILE * fp;
551    char buf[BUFFER_SIZE];
552    char * p;
553    const char * filename = NULL;
554    char * file_description = NULL;
555 #ifdef FEATURE_STATISTICS
556    float perc_rej;   /* Percentage of http requests rejected */
557    int local_urls_read;
558    int local_urls_rejected;
559 #endif /* ndef FEATURE_STATISTICS */
560
561    struct map * exports = default_exports(csp, "show-status");
562
563    switch (*(lookup(parameters, "file")))
564    {
565    case 'p':
566       if (csp->actions_list)
567       {
568          filename = csp->actions_list->filename;
569          file_description = "Actions List";
570       }
571       break;
572
573    case 'r':
574       if (csp->rlist)
575       {
576          filename = csp->rlist->filename;
577          file_description = "Regex Filter List";
578       }
579       break;
580
581 #ifdef FEATURE_TRUST
582    case 't':
583       if (csp->tlist)
584       {
585          filename = csp->tlist->filename;
586          file_description = "Trust List";
587       }
588       break;
589 #endif /* def FEATURE_TRUST */
590    }
591
592    if (NULL != filename)
593    {
594       map(exports, "file-description", 1, file_description, 1);
595       map(exports, "filepath", 1, html_encode(filename), 0);
596
597       if ((fp = fopen(filename, "r")) == NULL)
598       {
599          map(exports, "content", 1, "<h1>ERROR OPENING FILE!</h1>", 1);
600       }
601       else
602       {
603          while (fgets(buf, sizeof(buf), fp))
604          {
605             p = html_encode(buf);
606             if (p)
607             {
608                s = strsav(s, p);
609                freez(p);
610                s = strsav(s, "<br>");
611             }
612          }
613          fclose(fp);
614          map(exports, "contents", 1, s, 0);
615       }
616       rsp->body = template_load(csp, "show-status-file");
617       template_fill(&rsp->body, exports);
618       free_map(exports);
619       return(0);
620
621    }
622
623    map(exports, "redirect-url", 1, REDIRECT_URL, 1);
624    
625    s = NULL;
626    for (i=0; i < Argc; i++)
627    {
628       s = strsav(s, Argv[i]);
629       s = strsav(s, " ");
630    }
631    map(exports, "invocation", 1, s, 0);
632
633    map(exports, "options", 1, csp->config->proxy_args, 1);
634    show_defines(exports);
635
636 #ifdef FEATURE_STATISTICS
637    local_urls_read     = urls_read;
638    local_urls_rejected = urls_rejected;
639
640    /*
641     * Need to alter the stats not to include the fetch of this
642     * page.
643     *
644     * Can't do following thread safely! doh!
645     *
646     * urls_read--;
647     * urls_rejected--; * This will be incremented subsequently *
648     */
649
650    if (local_urls_read == 0)
651    {
652       map_block_killer(exports, "have-stats");
653    }
654    else
655    {
656       map_block_killer(exports, "have-no-stats");
657
658       perc_rej = (float)local_urls_rejected * 100.0F /
659             (float)local_urls_read;
660
661       sprintf(buf, "%d", local_urls_read);
662       map(exports, "requests-received", 1, buf, 1);
663
664       sprintf(buf, "%d", local_urls_rejected);
665       map(exports, "requests-blocked", 1, buf, 1);
666
667       sprintf(buf, "%6.2f", perc_rej);
668       map(exports, "percent-blocked", 1, buf, 1);
669    }
670
671 #else /* ndef FEATURE_STATISTICS */
672    map_block_killer(exports, "statistics");
673 #endif /* ndef FEATURE_STATISTICS */
674
675    if (csp->actions_list)
676    {
677       map(exports, "actions-filename", 1,  csp->actions_list->filename, 1);
678    }
679    else
680    {
681       map(exports, "actions-filename", 1, "None specified", 1);
682    }
683
684    if (csp->rlist)
685    {
686       map(exports, "re-filter-filename", 1,  csp->rlist->filename, 1);
687    }
688    else
689    {
690       map(exports, "re-filter-filename", 1, "None specified", 1);
691    }
692
693 #ifdef FEATURE_TRUST
694    if (csp->tlist)
695    {
696       map(exports, "trust-filename", 1,  csp->tlist->filename, 1);
697    }
698    else
699    {
700        map(exports, "trust-filename", 1, "None specified", 1);
701    }
702 #else
703    map_block_killer(exports, "trust-support");
704 #endif /* ndef FEATURE_TRUST */
705
706    rsp->body = template_load(csp, "show-status");
707    template_fill(&rsp->body, exports);
708    free_map(exports);
709    return(0);
710
711 }
712
713  
714 /*********************************************************************
715  *
716  * Function    :  cgi_show_url_info
717  *
718  * Description :  CGI function that determines and shows which actions
719  *                junkbuster will perform for a given url, and which
720  *                matches starting from the defaults have lead to that.
721  *
722  * Parameters  :
723  *           1 :  csp = Current client state (buffers, headers, etc...)
724  *           2 :  rsp = http_response data structure for output
725  *           3 :  parameters = map of cgi parameters
726  *
727  * CGI Parameters :
728  *            url : The url whose actions are to be determined.
729  *                  If url is unset, the url-given conditional will be
730  *                  set, so that all but the form can be suppressed in
731  *                  the template.
732  *
733  * Returns     :  0
734  *
735  *********************************************************************/
736 int cgi_show_url_info(struct client_state *csp, struct http_response *rsp,
737                       struct map *parameters)
738 {
739    char *url_param;
740    char *host = NULL;
741    struct map * exports = default_exports(csp, "show-url-info");
742
743    if (NULL == (url_param = strdup(lookup(parameters, "url"))) || *url_param == '\0')
744    {
745       map_block_killer(exports, "url-given");
746       map(exports, "url", 1, "", 1);
747    }
748    else
749    {
750       char *matches = NULL;
751       char *path;
752       char *s;
753       int port = 80;
754       int hits = 0;
755       struct file_list *fl;
756       struct url_actions *b;
757       struct url_spec url[1];
758       struct current_action_spec action[1];
759       
760       host = url_param;
761       host += (strncmp(url_param, "http://", 7)) ? 0 : 7;
762
763       map(exports, "url", 1, host, 1);
764       map(exports, "url-html", 1, html_encode(host), 0);
765
766       init_current_action(action);
767
768       s = current_action_to_text(action);
769       map(exports, "default", 1, s , 0);
770
771       if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
772       {
773          map(exports, "matches", 1, "none" , 1);
774          map(exports, "final", 1, lookup(exports, "default"), 1);
775
776          freez(url_param);
777          free_current_action(action);
778
779          rsp->body = template_load(csp, "show-url-info");
780          template_fill(&rsp->body, exports);
781          free_map(exports);
782
783          return 0;
784       }
785
786       s = strchr(host, '/');
787       if (s != NULL)
788       {
789          path = strdup(s);
790          *s = '\0';
791       }
792       else
793       {
794          path = strdup("");
795       }
796       s = strchr(host, ':');
797       if (s != NULL)
798       {
799          *s++ = '\0';
800          port = atoi(s);
801          s = NULL;
802       }
803
804       *url = dsplit(host);
805
806       /* if splitting the domain fails, punt */
807       if (url->dbuf == NULL)
808       {
809          map(exports, "matches", 1, "none" , 1);
810          map(exports, "final", 1, lookup(exports, "default"), 1);
811
812          freez(url_param);
813          freez(path);
814          free_current_action(action);
815
816          rsp->body = template_load(csp, "show-url-info");
817          template_fill(&rsp->body, exports);
818          free_map(exports);
819
820          return 0;
821       }
822
823       for (b = b->next; NULL != b; b = b->next)
824       {
825          if ((b->url->port == 0) || (b->url->port == port))
826          {
827             if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
828             {
829                if ((b->url->path == NULL) ||
830 #ifdef REGEX
831                   (regexec(b->url->preg, path, 0, NULL, 0) == 0)
832 #else
833                   (strncmp(b->url->path, path, b->url->pathlen) == 0)
834 #endif
835                )
836                {
837                   s = actions_to_text(b->action);
838                   matches = strsav(matches, "<b>{");
839                   matches = strsav(matches, s);
840                   matches = strsav(matches, " }</b><br>\n<code>");
841                   matches = strsav(matches, b->url->spec);
842                   matches = strsav(matches, "</code><br>\n<br>\n");
843                   freez(s);
844
845                   merge_current_action(action, b->action);
846                   hits++;
847                }
848             }
849          }
850       }
851
852       if (hits)
853       {
854          map(exports, "matches", 1, matches , 0);
855       }
856       else
857       {
858          map(exports, "matches", 1, "none", 1);
859       }
860       matches = NULL;
861
862       freez(url->dbuf);
863       freez(url->dvec);
864
865       freez(url_param);
866       freez(path);
867
868       s = current_action_to_text(action);
869       map(exports, "final", 1, s, 0);
870       s = NULL;
871
872       free_current_action(action);
873    }
874
875    rsp->body = template_load(csp, "show-url-info");
876    template_fill(&rsp->body, exports);
877    free_map(exports);
878    return 0;
879
880 }
881
882
883 /*********************************************************************
884  *
885  * Function    :  error_response
886  *
887  * Description :  returns an http_response that explains the reason
888  *                why a request failed.
889  *
890  * Parameters  :
891  *          1  :  csp = Current client state (buffers, headers, etc...)
892  *          2  :  templatename = Which template should be used for the answer
893  *          3  :  errno = system error number
894  *
895  * Returns     :  NULL if no memory, else http_response
896  *
897  *********************************************************************/
898 struct http_response *error_response(struct client_state *csp, const char *templatename, int err)
899 {
900    struct http_response *rsp;
901    struct map * exports = default_exports(csp, NULL);
902
903    if (NULL == (rsp = alloc_http_response()))
904    {
905       return NULL;
906    }
907
908    map(exports, "host-html", 1, html_encode(csp->http->host), 0);
909    map(exports, "hostport", 1, csp->http->hostport, 1);
910    map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
911    map(exports, "path", 1, csp->http->path, 1);
912    map(exports, "path-html", 1, html_encode(csp->http->path), 0);
913    map(exports, "error", 1, safe_strerror(err), 0);
914    map(exports, "host-ip", 1, csp->http->host_ip_addr_str, 1);
915
916    rsp->body = template_load(csp, templatename);
917    template_fill(&rsp->body, exports);
918    free_map(exports);
919
920    if (!strcmp(templatename, "no-such-domain"))
921    {
922       rsp->status = strdup("404 No such domain"); 
923    }
924    else if (!strcmp(templatename, "connect-failed"))
925    {
926       rsp->status = strdup("503 Connect failed");
927    }
928
929    return(finish_http_response(rsp));
930 }
931
932
933 /*********************************************************************
934  *
935  * Function    :  get_http_time
936  *
937  * Description :  Get the time in a format suitable for use in a
938  *                HTTP header - e.g.:
939  *                "Sun, 06 Nov 1994 08:49:37 GMT"
940  *
941  * Parameters  :  
942  *          1  :  time_offset = Time returned will be current time
943  *                              plus this number of seconds.
944  *          2  :  buf = Destination for result.  Must be long enough
945  *                      to hold 29 characters plus a trailing zero.
946  *
947  * Returns     :  N/A
948  *
949  *********************************************************************/
950 static void get_http_time(int time_offset, char * buf)
951 {
952    static const char day_names[7][4] =
953       { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
954    static const char month_names[12][4] =
955       { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
956         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
957
958    struct tm *t;
959    time_t current_time;
960
961    assert(buf);
962
963    time(&current_time); /* get current time */
964
965 /* FIXME: is this needed?  time() can't fail on Win32.  What about Linux?
966    if(current_time <= 0)
967    {
968       return NULL;
969    }
970 */
971
972    current_time += time_offset;
973
974    /* get and save the gmt */
975    t = gmtime(&current_time);
976
977    /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
978    snprintf(buf, 30,
979       "%s, %02d %s %4d %02d:%02d:%02d GMT",
980       day_names[t->tm_wday],
981       t->tm_mday,
982       month_names[t->tm_mon],
983       t->tm_year + 1900,
984       t->tm_hour,
985       t->tm_min,
986       t->tm_sec
987       );
988    buf[32] = '\0';
989 }
990
991
992 /*********************************************************************
993  *
994  * Function    :  finish_http_response
995  *
996  * Description :  Fill in the missing headers in an http response,
997  *                and flatten the headers to an http head.
998  *
999  * Parameters  :
1000  *          1  :  rsp = pointer to http_response to be processed
1001  *
1002  * Returns     :  http_response, or NULL on failiure
1003  *
1004  *********************************************************************/
1005 struct http_response *finish_http_response(struct http_response *rsp)
1006 {
1007    char buf[BUFFER_SIZE];
1008
1009    /* 
1010     * Fill in the HTTP Status
1011     */
1012    sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1013    enlist_first(rsp->headers, buf);
1014
1015    /* 
1016     * Set the Content-Length
1017     */
1018    if (rsp->content_length == 0)
1019    {
1020       rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1021    }
1022    sprintf(buf, "Content-Length: %d", rsp->content_length);
1023    enlist(rsp->headers, buf);
1024
1025    /* 
1026     * Fill in the default headers:
1027     *
1028     * Content-Type: default to text/html if not already specified.
1029     * Date: set to current date/time.
1030     * Last-Modified: set to date/time the page was last changed.
1031     * Expires: set to date/time page next needs reloading.
1032     * Cache-Control: set to "no-cache" if applicable.
1033     * 
1034     * See http://www.w3.org/Protocols/rfc2068/rfc2068
1035     */
1036    enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1037
1038    if (rsp->is_static)
1039    {
1040       /*
1041        * Set Expires to about 10 min into the future so it'll get reloaded
1042        * occasionally, e.g. if IJB gets upgraded.
1043        */
1044
1045       get_http_time(0, buf);
1046       enlist_unique_header(rsp->headers, "Date", buf);
1047
1048       /* Some date in the past. */
1049       enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1050
1051       get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1052       enlist_unique_header(rsp->headers, "Expires", buf);
1053    }
1054    else
1055    {
1056       /*
1057        * Compliant browsers should not cache this due to the "Cache-Control"
1058        * setting.  However, to be certain, we also set both "Last-Modified"
1059        * and "Expires" to the current time.
1060        */
1061       enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1062       get_http_time(0, buf);
1063       enlist_unique_header(rsp->headers, "Date", buf);
1064       enlist_unique_header(rsp->headers, "Last-Modified", buf);
1065       enlist_unique_header(rsp->headers, "Expires", buf);
1066    }
1067
1068
1069    /* 
1070     * Write the head
1071     */
1072    if (NULL == (rsp->head = list_to_text(rsp->headers)))
1073    {
1074       free_http_response(rsp);
1075       return(NULL);
1076    }
1077    rsp->head_length = strlen(rsp->head);
1078
1079    return(rsp);
1080
1081 }
1082   
1083
1084 /*********************************************************************
1085  *
1086  * Function    :  alloc_http_response
1087  *
1088  * Description :  Allocates a new http_response structure.
1089  *
1090  * Parameters  :  N/A
1091  *
1092  * Returns     :  pointer to a new http_response, or NULL.
1093  *
1094  *********************************************************************/
1095 struct http_response * alloc_http_response(void)
1096 {
1097    return (struct http_response *) zalloc(sizeof(struct http_response));
1098 }
1099
1100
1101 /*********************************************************************
1102  *
1103  * Function    :  free_http_response
1104  *
1105  * Description :  Free the memory occupied by an http_response
1106  *                and its depandant structures.
1107  *
1108  * Parameters  :
1109  *          1  :  rsp = pointer to http_response to be freed
1110  *
1111  * Returns     :  N/A
1112  *
1113  *********************************************************************/
1114 void free_http_response(struct http_response *rsp)
1115 {
1116    if (rsp)
1117    {
1118       freez(rsp->status);
1119       freez(rsp->head);
1120       freez(rsp->body);
1121       destroy_list(rsp->headers);
1122       free(rsp);
1123    }
1124
1125 }
1126
1127
1128 /*********************************************************************
1129  *
1130  * Function    :  fill_template
1131  *
1132  * Description :  CGI support function that loads a given HTML
1133  *                template from the confdir, and fills it in
1134  *                by replacing @name@ with value using pcrs,
1135  *                for each item in the output map.
1136  *
1137  * Parameters  :
1138  *           1 :  csp = Current client state (buffers, headers, etc...)
1139  *           3 :  template = name of the HTML template to be used
1140  *
1141  * Returns     :  char * with loaded template, or NULL if failure
1142  *
1143  *********************************************************************/
1144 char *template_load(struct client_state *csp, const char *templatename)
1145 {
1146    char buf[BUFFER_SIZE];
1147    char *file_buffer = NULL;
1148    FILE *fp;
1149
1150    /*
1151     * Open template file or fail
1152     */
1153    snprintf(buf, BUFFER_SIZE, "%s/templates/%s", csp->config->confdir, templatename);
1154
1155    if(NULL == (fp = fopen(buf, "r")))
1156    {
1157       log_error(LOG_LEVEL_ERROR, "error loading template %s: %E", buf);
1158       return NULL;
1159    }
1160    
1161
1162    /* 
1163     * Read the file, ignoring comments
1164     */
1165    while (fgets(buf, BUFFER_SIZE, fp))
1166    {
1167       /* skip lines starting with '#' */
1168       if(*buf == '#')
1169       {
1170          continue;
1171       }
1172    
1173       file_buffer = strsav(file_buffer, buf);
1174    }
1175    fclose(fp);
1176
1177    return(file_buffer);
1178 }
1179
1180
1181 /*********************************************************************
1182  *
1183  * Function    :  fill_template
1184  *
1185  * Description :  CGI support function that loads a given HTML
1186  *                template from the confdir, and fills it in
1187  *                by replacing @name@ with value using pcrs,
1188  *                for each item in the output map.
1189  *
1190  * Parameters  :
1191  *           1 :  template_ptr = IN: Template to be filled out.
1192  *                                   Will be free()d.
1193  *                               OUT: Filled out template.
1194  *                                    Caller must free().
1195  *           2 :  exports = map with fill in symbol -> name pairs
1196  *
1197  * Returns     :  N/A
1198  *
1199  *********************************************************************/
1200 void template_fill(char ** template_ptr, struct map *exports)
1201 {
1202    struct map_entry *m;
1203    pcrs_job *job;
1204    char buf[BUFFER_SIZE];
1205    char *tmp_out_buffer;
1206    char *file_buffer;
1207    int size;
1208    int error;
1209    const char * flags;
1210
1211    assert(template_ptr);
1212    assert(*template_ptr);
1213    assert(exports);
1214
1215    file_buffer = *template_ptr;
1216    size = strlen(file_buffer) + 1;
1217
1218    /* 
1219     * Assemble pcrs joblist from exports map
1220     */
1221    for (m = exports->first; m != NULL; m = m->next)
1222    {
1223       if (*m->name == '$')
1224       {
1225          /*
1226           * First character of name is '$', so remove this flag
1227           * character and allow backreferences ($1 etc) in the
1228           * "replace with" text.
1229           */
1230          snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1231          flags = "sigU";
1232       }
1233       else
1234       {
1235          /*
1236           * Treat the "replace with" text as a literal string - 
1237           * no quoting needed, no backreferences allowed.
1238           * ("Trivial" ['T'] flag).
1239           */
1240          flags = "sigTU";
1241
1242          /* Enclose name in @@ */
1243          snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1244       }
1245
1246
1247       log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1248
1249       /* Make and run job. */
1250       job = pcrs_compile(buf, m->value, flags,  &error);
1251       if (job == NULL) 
1252       {
1253          log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1254       }
1255       else
1256       {
1257          pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1258          if (file_buffer != tmp_out_buffer)
1259          {
1260             free(file_buffer);
1261             file_buffer = tmp_out_buffer;
1262          }
1263          pcrs_free_job(job);
1264       }
1265    }
1266
1267    /*
1268     * Return
1269     */
1270    *template_ptr = file_buffer;
1271 }
1272
1273
1274 /*********************************************************************
1275  *
1276  * Function    :  default_exports
1277  *
1278  * Description :  returns a struct map list that contains exports
1279  *                which are common to all CGI functions.
1280  *
1281  * Parameters  :
1282  *          1  :  exports = Structure to write output to.  This
1283  *                structure should be newly allocated and will be
1284  *                zeroed.
1285  *          1  :  csp = Current client state (buffers, headers, etc...)
1286  *          2  :  caller = name of CGI who calls us and which should
1287  *                         be excluded from the generated menu.
1288  * Returns     :  NULL if no memory, else map
1289  *
1290  *********************************************************************/
1291 struct map * default_exports(const struct client_state *csp, const char *caller)
1292 {
1293    char buf[20];
1294    struct map * exports = new_map();
1295
1296    map(exports, "version", 1, VERSION, 1);
1297    map(exports, "my-ip-address", 1, csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown", 1);
1298    map(exports, "my-hostname", 1, csp->my_hostname ? csp->my_hostname : "unknown", 1);
1299    map(exports, "admin-address", 1, csp->config->admin_address ? csp->config->admin_address : "fill@me.in.please", 1);
1300    map(exports, "homepage", 1, HOME_PAGE_URL, 1);
1301    map(exports, "default-cgi", 1, HOME_PAGE_URL "/config", 1);
1302    map(exports, "menu", 1, make_menu(caller), 0);
1303    map(exports, "code-status", 1, CODE_STATUS, 1);
1304
1305    snprintf(buf, 20, "%d", csp->config->hport);
1306    map(exports, "my-port", 1, buf, 1);
1307
1308    if(!strcmp(CODE_STATUS, "stable"))
1309    {
1310       map_block_killer(exports, "unstable");
1311    }
1312
1313    if(csp->config->proxy_info_url != NULL)
1314    {
1315       map(exports, "proxy-info-url", 1, csp->config->proxy_info_url, 1);
1316    }
1317    else
1318    {
1319       map_block_killer(exports, "have-proxy-info");
1320    }   
1321
1322    return (exports);
1323 }
1324
1325
1326 /*********************************************************************
1327  *
1328  * Function    :  map_block_killer
1329  *
1330  * Description :  Convenience function.
1331  *                Adds a "killer" for the conditional HTML-template
1332  *                block <name>, i.e. a substitution of the regex
1333  *                "if-<name>-start.*if-<name>-end" to the given
1334  *                export list.
1335  *
1336  * Parameters  :  
1337  *          1  :  exports = map to extend
1338  *          2  :  name = name of conditional block
1339  *
1340  * Returns     :  extended map
1341  *
1342  *********************************************************************/
1343 void map_block_killer(struct map *exports, const char *name)
1344 {
1345    char buf[1000]; /* Will do, since the names are hardwired */
1346
1347    snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1348    map(exports, buf, 1, "", 1);
1349 }
1350
1351
1352 /*********************************************************************
1353  *
1354  * Function    :  map_conditional
1355  *
1356  * Description :  Convenience function.
1357  *                Adds an "if-then-else" for the conditional HTML-template
1358  *                block <name>, i.e. a substitution of the form:
1359  *                @if-<name>-then@
1360  *                   True text
1361  *                @else-not-<name>@
1362  *                   False text
1363  *                @endif-<name>@
1364  *
1365  *                The control structure and one of the alternatives
1366  *                will be hidden.
1367  *
1368  * Parameters  :  
1369  *          1  :  exports = map to extend
1370  *          2  :  name = name of conditional block
1371  *          3  :  choose_first = nonzero for first, zero for second.
1372  *
1373  * Returns     :  extended map
1374  *
1375  *********************************************************************/
1376 void map_conditional(struct map *exports, const char *name, int choose_first)
1377 {
1378    char buf[1000]; /* Will do, since the names are hardwired */
1379
1380    snprintf(buf, 1000, (choose_first
1381       ? "else-not-%s@.*@endif-%s"
1382       : "if-%s-then@.*@else-not-%s"),
1383       name, name);
1384    map(exports, buf, 1, "", 1);
1385
1386    snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1387    map(exports, buf, 1, "", 1);
1388 }
1389
1390
1391 /*********************************************************************
1392  *
1393  * Function    :  make_menu
1394  *
1395  * Description :  Returns an HTML-formatted menu of the available 
1396  *                unhidden CGIs, excluding the one given in <self>.
1397  *
1398  * Parameters  :  self = name of CGI to leave out, can be NULL
1399  *
1400  * Returns     :  menu string
1401  *
1402  *********************************************************************/
1403 char *make_menu(const char *self)
1404 {
1405    const struct cgi_dispatcher *d;
1406    char buf[BUFFER_SIZE];
1407    char *result = NULL;
1408
1409    if (self == NULL)
1410    {
1411       self = "NO-SUCH-CGI!";
1412    }
1413
1414    /* List available unhidden CGI's and export as "other-cgis" */
1415    for (d = cgi_dispatcher; d->handler; d++)
1416    {
1417       if (strncmp(d->description, "HIDE", 4) && strcmp(d->name, self))
1418       {
1419          snprintf(buf, BUFFER_SIZE, "<li><a href=%s/config/%s>%s</a></li>\n",
1420                HOME_PAGE_URL, d->name, d->description);
1421          result = strsav(result, buf);
1422       }
1423    }
1424    return(result);
1425
1426 }
1427
1428
1429 /*********************************************************************
1430  *
1431  * Function    :  dump_map
1432  *
1433  * Description :  HTML-dump a map for debugging
1434  *
1435  * Parameters  :
1436  *          1  :  the_map = map to dump
1437  *
1438  * Returns     :  string with HTML
1439  *
1440  *********************************************************************/
1441 char *dump_map(const struct map *the_map)
1442 {
1443    struct map_entry *cur_entry = the_map->first;
1444    char *ret = NULL;
1445
1446    ret = strsav(ret, "<table>\n");
1447
1448    while (cur_entry)
1449    {
1450       ret = strsav(ret, "<tr><td><b>");
1451       ret = strsav(ret, cur_entry->name);
1452       ret = strsav(ret, "</b></td><td>");
1453       ret = strsav(ret, cur_entry->value);
1454       ret = strsav(ret, "</td></tr>\n");
1455       cur_entry = cur_entry->next;
1456    }
1457
1458    ret = strsav(ret, "</table>\n");
1459    return(ret);
1460
1461 }
1462
1463
1464 /*********************************************************************
1465  *
1466  * Function    :  cgi_robots_txt
1467  *
1468  * Description :  CGI function to return "/robots.txt".
1469  *
1470  * Parameters  :
1471  *           1 :  csp = Current client state (buffers, headers, etc...)
1472  *           2 :  rsp = http_response data structure for output
1473  *           3 :  parameters = map of cgi parameters
1474  *
1475  * CGI Parameters : None
1476  *
1477  * Returns     :  0
1478  *
1479  *********************************************************************/
1480 int cgi_robots_txt(struct client_state *csp, struct http_response *rsp,
1481                    struct map *parameters)
1482 {
1483    char buf[100];
1484
1485    rsp->body = strdup(
1486       "# This is the Internet Junkbuster control interface.\n"
1487       "# It isn't very useful to index it, and you're likely to break stuff.\n"
1488       "# So go away!\n"
1489       "\n"
1490       "User-agent: *\n"
1491       "Disallow: /\n"
1492       "\n");
1493
1494    enlist_unique(rsp->headers, "Content-Type: text/plain", 13);
1495
1496    rsp->is_static = 1;
1497
1498    get_http_time(7 * 24 * 60 * 60, buf); /* 7 days into future */
1499    enlist_unique_header(rsp->headers, "Expires", buf);
1500
1501    return 0;
1502 }
1503
1504
1505 /*
1506   Local Variables:
1507   tab-width: 3
1508   end:
1509 */