Send a template-based response in case of server connection timeouts.
[privoxy.git] / project.h
1 #ifndef PROJECT_H_INCLUDED
2 #define PROJECT_H_INCLUDED
3 /** Version string. */
4 #define PROJECT_H_VERSION "$Id: project.h,v 1.140 2009/06/08 16:47:07 fabiankeil Exp $"
5 /*********************************************************************
6  *
7  * File        :  $Source: /cvsroot/ijbswa/current/project.h,v $
8  *
9  * Purpose     :  Defines data structures which are widely used in the
10  *                project.  Does not define any variables or functions
11  *                (though it does declare some macros).
12  *
13  * Copyright   :  Written by and Copyright (C) 2001-2009 the
14  *                Privoxy team. http://www.privoxy.org/
15  *
16  *                Based on the Internet Junkbuster originally written
17  *                by and Copyright (C) 1997 Anonymous Coders and
18  *                Junkbusters Corporation.  http://www.junkbusters.com
19  *
20  *                This program is free software; you can redistribute it
21  *                and/or modify it under the terms of the GNU General
22  *                Public License as published by the Free Software
23  *                Foundation; either version 2 of the License, or (at
24  *                your option) any later version.
25  *
26  *                This program is distributed in the hope that it will
27  *                be useful, but WITHOUT ANY WARRANTY; without even the
28  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
29  *                PARTICULAR PURPOSE.  See the GNU General Public
30  *                License for more details.
31  *
32  *                The GNU General Public License should be included with
33  *                this file.  If not, you can view it at
34  *                http://www.gnu.org/copyleft/gpl.html
35  *                or write to the Free Software Foundation, Inc., 59
36  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
37  *
38  *********************************************************************/
39
40
41 /* Declare struct FILE for vars and funcs. */
42 #include <stdio.h>
43
44 /* Need time_t for file_list */
45 #include <time.h>
46 /* Needed for pcre choice */
47 #include "config.h"
48
49 #ifdef HAVE_RFC2553
50 /* Need for struct sockaddr_storage */
51 #include <sys/socket.h>
52 #endif
53
54
55 /*
56  * Include appropriate regular expression libraries.
57  * Note that pcrs and pcre (native) are needed for cgi
58  * and are included anyway.
59  */
60
61 #ifdef STATIC_PCRE
62 #  include "pcre.h"
63 #else
64 #  ifdef PCRE_H_IN_SUBDIR
65 #    include <pcre/pcre.h>
66 #  else
67 #    include <pcre.h>
68 #  endif
69 #endif
70
71 #ifdef STATIC_PCRS
72 #  include "pcrs.h"
73 #else
74 #  include <pcrs.h>
75 #endif
76
77 #ifdef STATIC_PCRE
78 #  include "pcreposix.h"
79 #else
80 #  ifdef PCRE_H_IN_SUBDIR
81 #    include <pcre/pcreposix.h>
82 #  else
83 #    include <pcreposix.h>
84 #  endif
85 #endif
86
87 #ifdef AMIGA
88 #include "amiga.h"
89 #endif /* def AMIGA */
90
91 #ifdef _WIN32
92 /*
93  * I don't want to have to #include all this just for the declaration
94  * of SOCKET.  However, it looks like we have to...
95  */
96 #ifndef STRICT
97 #define STRICT
98 #endif
99 #include <windows.h>
100 #endif
101
102
103 #ifdef __cplusplus
104 extern "C" {
105 #endif
106
107 #ifdef _WIN32
108
109 typedef SOCKET jb_socket;
110
111 #define JB_INVALID_SOCKET INVALID_SOCKET
112
113 #else /* ndef _WIN32 */
114
115 /**
116  * The type used by sockets.  On UNIX it's an int.  Microsoft decided to
117  * make it an unsigned.
118  */
119 typedef int jb_socket;
120
121 /**
122  * The error value used for variables of type jb_socket.  On UNIX this
123  * is -1, however Microsoft decided to make socket handles unsigned, so
124  * they use a different value.
125  */
126
127 #define JB_INVALID_SOCKET (-1)
128
129 #endif /* ndef _WIN32 */
130
131
132 /**
133  * A standard error code.  This should be JB_ERR_OK or one of the JB_ERR_xxx
134  * series of errors.
135  */
136 typedef int jb_err;
137
138 #define JB_ERR_OK         0 /**< Success, no error                        */
139 #define JB_ERR_MEMORY     1 /**< Out of memory                            */
140 #define JB_ERR_CGI_PARAMS 2 /**< Missing or corrupt CGI parameters        */
141 #define JB_ERR_FILE       3 /**< Error opening, reading or writing a file */
142 #define JB_ERR_PARSE      4 /**< Error parsing file                       */
143 #define JB_ERR_MODIFIED   5 /**< File has been modified outside of the  
144                                  CGI actions editor.                      */
145 #define JB_ERR_COMPRESS   6 /**< Error on decompression                   */
146
147 /**
148  * This macro is used to free a pointer that may be NULL.
149  * It also sets the variable to NULL after it's been freed.
150  * The paramater should be a simple variable without side effects.
151  */
152 #define freez(X)  { if(X) { free((void*)X); X = NULL ; } }
153
154
155 /**
156  * Fix a problem with Solaris.  There should be no effect on other
157  * platforms.
158  *
159  * Solaris's isspace() is a macro which uses it's argument directly
160  * as an array index.  Therefore we need to make sure that high-bit
161  * characters generate +ve values, and ideally we also want to make
162  * the argument match the declared parameter type of "int".
163  *
164  * Note: Remember to #include <ctype.h> if you use these macros.
165  */
166 #define ijb_toupper(__X) toupper((int)(unsigned char)(__X))
167 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
168 #define ijb_isspace(__X) isspace((int)(unsigned char)(__X))  
169
170 /**
171  * Use for statically allocated buffers if you have no other choice.
172  * Remember to check the length of what you write into the buffer
173  * - we don't want any buffer overflows!
174  */
175 #define BUFFER_SIZE 5000
176
177 /**
178  * Max length of CGI parameters (arbitrary limit).
179  */
180 #define CGI_PARAM_LEN_MAX 500U
181
182 /**
183  * Buffer size for capturing struct hostent data in the
184  * gethostby(name|addr)_r library calls. Since we don't
185  * loop over gethostbyname_r, the buffer must be sufficient
186  * to accomodate multiple IN A RRs, as used in DNS round robin
187  * load balancing. W3C's wwwlib uses 1K, so that should be
188  * good enough for us, too.
189  */
190 /**
191  * XXX: Temporary doubled, for some configurations
192  * 1K is still too small and we didn't get the
193  * real fix ready for inclusion.
194  */
195 #define HOSTENT_BUFFER_SIZE 2048
196
197 /**
198  * Do not use.  Originally this was so that you can
199  * say "while (FOREVER) { ...do something... }".
200  * However, this gives a warning with some compilers (e.g. VC++).
201  * Instead, use "for (;;) { ...do something... }".
202  */
203 #define FOREVER 1
204
205 /**
206  * Default TCP/IP address to listen on, as a string.
207  * Set to "127.0.0.1:8118".
208  */
209 #define HADDR_DEFAULT   "127.0.0.1:8118"
210
211
212 /* Forward def for struct client_state */
213 struct configuration_spec;
214
215
216 /**
217  * Entry in a linked list of strings.
218  */
219 struct list_entry
220 {
221    /**
222     * The string pointer. It must point to a dynamically malloc()ed
223     * string or be NULL for the list functions to work. In the latter
224     * case, just be careful next time you iterate through the list in
225     * your own code.
226     */
227    char *str;
228    
229    /** Next entry in the linked list, or NULL if no more. */
230    struct list_entry *next;
231 };
232
233 /**
234  * A header for a linked list of strings.
235  */
236 struct list
237 {
238    /** First entry in the list, or NULL if the list is empty. */
239    struct list_entry *first;
240
241    /** Last entry in the list, or NULL if the list is empty. */
242    struct list_entry *last;
243 };
244
245
246 /**
247  * An entry in a map.  This is a name=value pair.
248  */
249 struct map_entry
250 {
251    /** The key for the map. */
252    const char *name;
253    /** The value associated with that key. */
254    const char *value;
255    /** The next map entry, or NULL if none. */
256    struct map_entry *next;
257 };
258
259 /**
260  * A map from a string to another string.
261  * This is used for the paramaters passed in a HTTP GET request, and
262  * to store the exports when the CGI interface is filling in a template.
263  */
264 struct map
265 {
266    /** The first map entry, or NULL if the map is empty. */
267    struct map_entry *first;
268    /** The last map entry, or NULL if the map is empty. */
269    struct map_entry *last;
270 };
271
272
273 /**
274  * A HTTP request.  This includes the method (GET, POST) and
275  * the parsed URL.
276  *
277  * This is also used whenever we want to match a URL against a
278  * URL pattern.  This always contains the URL to match, and never
279  * a URL pattern.  (See struct url_spec).
280  */
281 struct http_request
282 {
283    char *cmd;      /**< Whole command line: method, URL, Version */
284    char *ocmd;     /**< Backup of original cmd for CLF logging */
285    char *gpc;      /**< HTTP method: GET, POST, ... */
286    char *url;      /**< The URL */
287    char *ver;      /**< Protocol version */
288    int status;     /**< HTTP Status */
289
290    char *host;     /**< Host part of URL */
291    int   port;     /**< Port of URL or 80 (default) */
292    char *path;     /**< Path of URL */
293    char *hostport; /**< host[:port] */
294    int   ssl;      /**< Flag if protocol is https */
295
296    char *host_ip_addr_str; /**< String with dotted decimal representation
297                                 of host's IP. NULL before connect_to() */
298
299 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
300    char  *dbuffer; /**< Buffer with '\0'-delimited domain name.           */
301    char **dvec;    /**< List of pointers to the strings in dbuffer.       */
302    int    dcount;  /**< How many parts to this domain? (length of dvec)   */
303 #endif /* ndef FEATURE_EXTENDED_HOST_PATTERNS */
304 };
305
306 /**
307  * Reasons for generating a http_response instead of delivering
308  * the requested resource. Mostly ordered the way they are checked
309  * for in chat().
310  */
311 #define RSP_REASON_UNSUPPORTED        1
312 #define RSP_REASON_BLOCKED            2
313 #define RSP_REASON_UNTRUSTED          3
314 #define RSP_REASON_REDIRECTED         4
315 #define RSP_REASON_CGI_CALL           5
316 #define RSP_REASON_NO_SUCH_DOMAIN     6
317 #define RSP_REASON_FORWARDING_FAILED  7
318 #define RSP_REASON_CONNECT_FAILED     8
319 #define RSP_REASON_OUT_OF_MEMORY      9
320 #define RSP_REASON_INTERNAL_ERROR     10
321 #define RSP_REASON_CONNECTION_TIMEOUT 11
322
323 /**
324  * Response generated by CGI, blocker, or error handler
325  */
326 struct http_response
327 {
328   char  *status;          /**< HTTP status (string). */
329   struct list headers[1]; /**< List of header lines. */
330   char  *head;            /**< Formatted http response head. */
331   size_t head_length;     /**< Length of http response head. */
332   char  *body;            /**< HTTP document body. */
333   size_t content_length;  /**< Length of body, REQUIRED if binary body. */
334   int    is_static;       /**< Nonzero if the content will never change and
335                                should be cached by the browser (e.g. images). */
336   int reason;             /**< Why the response was generated in the first place. */
337 };
338
339 /**
340  * A URL or a tag pattern.
341  */
342 struct url_spec
343 {
344    /** The string which was parsed to produce this url_spec.
345        Used for debugging or display only.  */
346    char  *spec;
347
348 #ifdef FEATURE_EXTENDED_HOST_PATTERNS
349    regex_t *host_regex;/**< Regex for host matching                          */
350 #else
351    char  *dbuffer;     /**< Buffer with '\0'-delimited domain name, or NULL to match all hosts. */
352    char **dvec;        /**< List of pointers to the strings in dbuffer.       */
353    int    dcount;      /**< How many parts to this domain? (length of dvec)   */
354    int    unanchored;  /**< Bitmap - flags are ANCHOR_LEFT and ANCHOR_RIGHT.  */
355 #endif /* defined FEATURE_EXTENDED_HOST_PATTERNS */
356
357    char  *port_list;   /**< List of acceptable ports, or NULL to match all ports */
358
359    regex_t *preg;      /**< Regex for matching path part                      */
360    regex_t *tag_regex; /**< Regex for matching tags                           */
361 };
362
363 /**
364  * If you declare a static url_spec, this is the value to initialize it to zero.
365  */
366 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
367 #define URL_SPEC_INITIALIZER { NULL, NULL, NULL, 0, 0, NULL, NULL, NULL }
368 #else
369 #define URL_SPEC_INITIALIZER { NULL, NULL, NULL, NULL, NULL }
370 #endif /* def FEATURE_EXTENDED_HOST_PATTERNS */
371
372 /**
373  * Constant for host part matching in URLs.  If set, indicates that the start of
374  * the pattern must match the start of the URL.  E.g. this is not set for the
375  * pattern ".example.com", so that it will match both "example.com" and
376  * "www.example.com".  It is set for the pattern "example.com", which makes it
377  * match "example.com" only, not "www.example.com".
378  */
379 #define ANCHOR_LEFT  1
380
381 /**
382  * Constant for host part matching in URLs.  If set, indicates that the end of
383  * the pattern must match the end of the URL.  E.g. this is not set for the
384  * pattern "ad.", so that it will match any host called "ad", irrespective
385  * of how many subdomains are in the fully-qualified domain name.
386  */
387 #define ANCHOR_RIGHT 2
388
389
390 /**
391  * An I/O buffer.  Holds a string which can be appended to, and can have data
392  * removed from the beginning.
393  */
394 struct iob
395 {
396    char *buf;    /**< Start of buffer        */
397    char *cur;    /**< Start of relevant data */
398    char *eod;    /**< End of relevant data   */
399    size_t size;  /**< Size as malloc()ed     */
400 };
401
402
403 /**
404  * Return the number of bytes in the I/O buffer associated with the passed
405  * client_state pointer.
406  * May be zero.
407  */
408 #define IOB_PEEK(CSP) ((CSP->iob->cur > CSP->iob->eod) ? (CSP->iob->eod - CSP->iob->cur) : 0)
409
410
411 /**
412  * Remove any data in the I/O buffer associated with the passed
413  * client_state pointer.
414  */
415 #define IOB_RESET(CSP) if(CSP->iob->buf) free(CSP->iob->buf); memset(CSP->iob, '\0', sizeof(CSP->iob));
416
417 /* Bits for csp->content_type bitmask: */
418 #define CT_TEXT    0x0001U /**< Suitable for pcrs filtering. */
419 #define CT_GIF     0x0002U /**< Suitable for GIF filtering.  */
420 #define CT_TABOO   0x0004U /**< DO NOT filter, irrespective of other flags. */
421
422 /* Although these are not, strictly speaking, content types
423  * (they are content encodings), it is simple to handle them
424  * as such.
425  */
426 #define CT_GZIP    0x0010U /**< gzip-compressed data. */
427 #define CT_DEFLATE 0x0020U /**< zlib-compressed data. */
428
429 /**
430  * Flag to signal that the server declared the content type,
431  * so we can differentiate between unknown and undeclared
432  * content types.
433  */
434 #define CT_DECLARED 0x0040U
435
436 /**
437  * The mask which includes all actions.
438  */
439 #define ACTION_MASK_ALL        (~0UL)
440
441 /**
442  * The most compatible set of actions - i.e. none.
443  */
444 #define ACTION_MOST_COMPATIBLE                       0x00000000UL
445
446 /** Action bitmap: Block the request. */
447 #define ACTION_BLOCK                                 0x00000001UL
448 /** Action bitmap: Deanimate if it's a GIF. */
449 #define ACTION_DEANIMATE                             0x00000002UL
450 /** Action bitmap: Downgrade HTTP/1.1 to 1.0. */
451 #define ACTION_DOWNGRADE                             0x00000004UL
452 /** Action bitmap: Fast redirects. */
453 #define ACTION_FAST_REDIRECTS                        0x00000008UL
454 /** Action bitmap: Remove or add "X-Forwarded-For" header. */
455 #define ACTION_CHANGE_X_FORWARDED_FOR                0x00000010UL
456 /** Action bitmap: Hide "From" header. */
457 #define ACTION_HIDE_FROM                             0x00000020UL
458 /** Action bitmap: Hide "Referer" header.  (sic - follow HTTP, not English). */
459 #define ACTION_HIDE_REFERER                          0x00000040UL
460 /** Action bitmap: Hide "User-Agent" and similar headers. */
461 #define ACTION_HIDE_USER_AGENT                       0x00000080UL
462 /** Action bitmap: This is an image. */
463 #define ACTION_IMAGE                                 0x00000100UL
464 /** Action bitmap: Sets the image blocker. */
465 #define ACTION_IMAGE_BLOCKER                         0x00000200UL
466 /** Action bitmap: Prevent compression. */
467 #define ACTION_NO_COMPRESSION                        0x00000400UL
468 /** Action bitmap: Change cookies to session only cookies. */
469 #define ACTION_NO_COOKIE_KEEP                        0x00000800UL
470 /** Action bitmap: Block rending cookies. */
471 #define ACTION_NO_COOKIE_READ                        0x00001000UL
472 /** Action bitmap: Block setting cookies. */
473 #define ACTION_NO_COOKIE_SET                         0x00002000UL
474 /** Action bitmap: Override the forward settings in the config file */
475 #define ACTION_FORWARD_OVERRIDE                      0x00004000UL
476 /** Action bitmap: Block as empty document */
477 #define  ACTION_HANDLE_AS_EMPTY_DOCUMENT             0x00008000UL
478 /** Action bitmap: Limit CONNECT requests to safe ports. */
479 #define ACTION_LIMIT_CONNECT                         0x00010000UL
480 /** Action bitmap: Redirect request. */
481 #define  ACTION_REDIRECT                             0x00020000UL
482 /** Action bitmap: Crunch or modify "if-modified-since" header. */
483 #define ACTION_HIDE_IF_MODIFIED_SINCE                0x00040000UL
484 /** Action bitmap: Overwrite Content-Type header. */
485 #define ACTION_CONTENT_TYPE_OVERWRITE                0x00080000UL
486 /** Action bitmap: Crunch specified server header. */
487 #define ACTION_CRUNCH_SERVER_HEADER                  0x00100000UL
488 /** Action bitmap: Crunch specified client header */
489 #define ACTION_CRUNCH_CLIENT_HEADER                  0x00200000UL
490 /** Action bitmap: Enable text mode by force */
491 #define ACTION_FORCE_TEXT_MODE                       0x00400000UL
492 /** Action bitmap: Enable text mode by force */
493 #define ACTION_CRUNCH_IF_NONE_MATCH                  0x00800000UL
494 /** Action bitmap: Enable content-dispostion crunching */
495 #define ACTION_HIDE_CONTENT_DISPOSITION              0x01000000UL
496 /** Action bitmap: Replace or block Last-Modified header */
497 #define ACTION_OVERWRITE_LAST_MODIFIED               0x02000000UL
498 /** Action bitmap: Replace or block Accept-Language header */
499 #define ACTION_HIDE_ACCEPT_LANGUAGE                  0x04000000UL
500
501
502 /** Action string index: How to deanimate GIFs */
503 #define ACTION_STRING_DEANIMATE             0
504 /** Action string index: Replacement for "From:" header */
505 #define ACTION_STRING_FROM                  1
506 /** Action string index: How to block images */
507 #define ACTION_STRING_IMAGE_BLOCKER         2
508 /** Action string index: Replacement for "Referer:" header */
509 #define ACTION_STRING_REFERER               3
510 /** Action string index: Replacement for "User-Agent:" header */
511 #define ACTION_STRING_USER_AGENT            4
512 /** Action string index: Legal CONNECT ports. */
513 #define ACTION_STRING_LIMIT_CONNECT         5
514 /** Action string index: Server headers containing this pattern are crunched*/
515 #define ACTION_STRING_SERVER_HEADER         6
516 /** Action string index: Client headers containing this pattern are crunched*/
517 #define ACTION_STRING_CLIENT_HEADER         7
518 /** Action string index: Replacement for the "Accept-Language:" header*/
519 #define ACTION_STRING_LANGUAGE              8
520 /** Action string index: Replacement for the "Content-Type:" header*/
521 #define ACTION_STRING_CONTENT_TYPE          9
522 /** Action string index: Replacement for the "content-dispostion:" header*/
523 #define ACTION_STRING_CONTENT_DISPOSITION  10
524 /** Action string index: Replacement for the "If-Modified-Since:" header*/
525 #define ACTION_STRING_IF_MODIFIED_SINCE    11
526 /** Action string index: Replacement for the "Last-Modified:" header. */
527 #define ACTION_STRING_LAST_MODIFIED        12
528 /** Action string index: Redirect URL */
529 #define ACTION_STRING_REDIRECT             13
530 /** Action string index: Decode before redirect? */
531 #define ACTION_STRING_FAST_REDIRECTS       14
532 /** Action string index: Overriding forward rule. */
533 #define ACTION_STRING_FORWARD_OVERRIDE     15
534 /** Action string index: Reason for the block. */
535 #define ACTION_STRING_BLOCK                16
536 /** Action string index: what to do with the "X-Forwarded-For" header. */
537 #define ACTION_STRING_CHANGE_X_FORWARDED_FOR 17
538 /** Number of string actions. */
539 #define ACTION_STRING_COUNT                18
540
541
542 /* To make the ugly hack in sed easier to understand */
543 #define CHECK_EVERY_HEADER_REMAINING 0
544
545
546 /** Index into current_action_spec::multi[] for headers to add. */
547 #define ACTION_MULTI_ADD_HEADER              0
548 /** Index into current_action_spec::multi[] for content filters to apply. */
549 #define ACTION_MULTI_FILTER                  1
550 /** Index into current_action_spec::multi[] for server-header filters to apply. */
551 #define ACTION_MULTI_SERVER_HEADER_FILTER    2
552 /** Index into current_action_spec::multi[] for client-header filters to apply. */
553 #define ACTION_MULTI_CLIENT_HEADER_FILTER    3
554 /** Index into current_action_spec::multi[] for client-header tags to apply. */
555 #define ACTION_MULTI_CLIENT_HEADER_TAGGER    4
556 /** Index into current_action_spec::multi[] for server-header tags to apply. */
557 #define ACTION_MULTI_SERVER_HEADER_TAGGER    5
558 /** Number of multi-string actions. */
559 #define ACTION_MULTI_COUNT                   6
560
561
562 /**
563  * This structure contains a list of actions to apply to a URL.
564  * It only contains positive instructions - no "-" options.
565  * It is not used to store the actions list itself, only for
566  * url_actions() to return the current values.
567  */
568 struct current_action_spec
569 {
570    /** Actions to apply.  A bit set to "1" means perform the action. */
571    unsigned long flags;
572
573    /**
574     * Paramaters for those actions that require them.
575     * Each entry is valid if & only if the corresponding entry in "flags" is
576     * set.
577     */
578    char * string[ACTION_STRING_COUNT];
579
580    /** Lists of strings for multi-string actions. */
581    struct list multi[ACTION_MULTI_COUNT][1];
582 };
583
584
585 /**
586  * This structure contains a set of changes to actions.
587  * It can contain both positive and negative instructions.
588  * It is used to store an entry in the actions list.
589  */
590 struct action_spec
591 {
592    unsigned long mask; /**< Actions to keep. A bit set to "0" means remove action. */
593    unsigned long add;  /**< Actions to add.  A bit set to "1" means add action.    */
594
595    /**
596     * Paramaters for those actions that require them.
597     * Each entry is valid if & only if the corresponding entry in "flags" is
598     * set.
599     */
600    char * string[ACTION_STRING_COUNT];
601
602    /** Lists of strings to remove, for multi-string actions. */
603    struct list multi_remove[ACTION_MULTI_COUNT][1];
604
605    /** If nonzero, remove *all* strings from the multi-string action. */
606    int         multi_remove_all[ACTION_MULTI_COUNT];
607
608    /** Lists of strings to add, for multi-string actions. */
609    struct list multi_add[ACTION_MULTI_COUNT][1];
610 };
611
612
613 /**
614  * This structure is used to store action files.
615  *
616  * It contains an URL or tag pattern, and the changes to
617  * the actions. It's a linked list and should only be
618  * free'd through unload_actions_file() unless there's
619  * only a single entry.
620  */
621 struct url_actions
622 {
623    struct url_spec url[1];     /**< The URL or tag pattern. */
624
625    struct action_spec *action; /**< Action settings that might be shared with
626                                     the list entry before or after the current
627                                     one and can't be free'd willy nilly. */
628
629    struct url_actions *next;   /**< Next action section in file, or NULL. */
630 };
631
632
633 /*
634  * Structure to make sure we only reuse the server socket
635  * if the host and forwarding settings are the same.
636  */
637 struct reusable_connection
638 {
639    jb_socket sfd;
640    int       in_use;
641    time_t    timestamp;
642    /*
643     * Number of seconds after which this
644     * connection will no longer be reused.
645     */
646    unsigned int keep_alive_timeout;
647
648    char *host;
649    int  port;
650    int  forwarder_type;
651    char *gateway_host;
652    int  gateway_port;
653    char *forward_host;
654    int  forward_port;
655 };
656
657
658 /*
659  * Flags for use in csp->flags
660  */
661  
662 /**
663  * Flag for csp->flags: Set if this client is processing data.
664  * Cleared when the thread associated with this structure dies.
665  */
666 #define CSP_FLAG_ACTIVE     0x01U
667
668 /**
669  * Flag for csp->flags: Set if the server's reply is in "chunked"
670  * transfer encoding
671  */
672 #define CSP_FLAG_CHUNKED    0x02U
673
674 /**
675  * Flag for csp->flags: Set if this request was enforced, although it would
676  * normally have been blocked.
677  */
678 #define CSP_FLAG_FORCED     0x04U
679
680 /**
681  * Flag for csp->flags: Set if any modification to the body was done.
682  */
683 #define CSP_FLAG_MODIFIED   0x08U
684
685 /**
686  * Flag for csp->flags: Set if request was blocked.
687  */
688 #define CSP_FLAG_REJECTED   0x10U
689
690 /**
691  * Flag for csp->flags: Set if we are toggled on (FEATURE_TOGGLE).
692  */
693 #define CSP_FLAG_TOGGLED_ON 0x20U
694
695 /**
696  * Flag for csp->flags: Set if an acceptable Connection header
697  * has already been set by the client.
698  */
699 #define CSP_FLAG_CLIENT_CONNECTION_HEADER_SET  0x00000040U
700
701 /**
702  * Flag for csp->flags: Set if an acceptable Connection header
703  * has already been set by the server.
704  */
705 #define CSP_FLAG_SERVER_CONNECTION_HEADER_SET  0x00000080U
706
707 /**
708  * Flag for csp->flags: Signals header parsers whether they
709  * are parsing server or client headers.
710  */
711 #define CSP_FLAG_CLIENT_HEADER_PARSING_DONE    0x00000100U
712
713 /**
714  * Flag for csp->flags: Set if adding the Host: header
715  * isn't necessary.
716  */
717 #define CSP_FLAG_HOST_HEADER_IS_SET            0x00000200U
718
719 /**
720  * Flag for csp->flags: Set if filtering is disabled by X-Filter: No
721  * XXX: As we now have tags we might as well ditch this.
722  */
723 #define CSP_FLAG_NO_FILTERING                  0x00000400U
724
725 /**
726  * Flag for csp->flags: Set the client IP has appended to
727  * an already existing X-Forwarded-For header in which case
728  * no new header has to be generated.
729  */
730 #define CSP_FLAG_X_FORWARDED_FOR_APPENDED      0x00000800U
731
732 /**
733  * Flag for csp->flags: Set if the server wants to keep
734  * the connection alive.
735  */
736 #define CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE  0x00001000U
737
738 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
739 /**
740  * Flag for csp->flags: Set if the server specified the
741  * content length.
742  */
743 #define CSP_FLAG_SERVER_CONTENT_LENGTH_SET     0x00002000U
744
745 /**
746  * Flag for csp->flags: Set if we know the content lenght,
747  * either because the server set it, or we figured it out
748  * on our own.
749  */
750 #define CSP_FLAG_CONTENT_LENGTH_SET            0x00004000U
751
752 /**
753  * Flag for csp->flags: Set if the client wants to keep
754  * the connection alive.
755  */
756 #define CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE  0x00008000U
757 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
758
759 /*
760  * Flags for use in return codes of child processes
761  */
762
763 /**
764  * Flag for process return code: Set if exiting porcess has been toggled
765  * during its lifetime.
766  */
767 #define RC_FLAG_TOGGLED   0x10
768
769 /**
770  * Flag for process return code: Set if exiting porcess has blocked its
771  * request.
772  */
773 #define RC_FLAG_BLOCKED   0x20
774
775 /**
776  * Maximum number of actions/filter files.  This limit is arbitrary - it's just used
777  * to size an array.
778  */
779 #define MAX_AF_FILES 10
780
781 /**
782  * The state of a Privoxy processing thread.
783  */
784 struct client_state
785 {
786    /** The proxy's configuration */
787    struct configuration_spec * config;
788
789    /** The actions to perform on the current request */
790    struct current_action_spec  action[1];
791
792    /** socket to talk to client (web browser) */
793    jb_socket cfd;
794
795    /** socket to talk to server (web server or proxy) */
796    jb_socket sfd;
797
798    /** current connection to the server (may go through a proxy) */
799    struct reusable_connection server_connection;
800
801    /** Multi-purpose flag container, see CSP_FLAG_* above */
802    unsigned int flags;
803
804    /** Client PC's IP address, as reported by the accept() function.
805        As a string. */
806    char *ip_addr_str;
807 #ifdef HAVE_RFC2553
808    /** Client PC's TCP address, as reported by the accept() function.
809        As a sockaddr. */
810    struct sockaddr_storage tcp_addr;
811 #else
812    /** Client PC's IP address, as reported by the accept() function.
813        As a number. */
814    unsigned long ip_addr_long;
815 #endif /* def HAVE_RFC2553 */
816
817    /** The URL that was requested */
818    struct http_request http[1];
819
820    /*
821     * The final forwarding settings.
822     * XXX: Currently this is only used for forward-override,
823     * so we can free the space in sweep.
824     */
825    struct forward_spec * fwd;
826
827    /** An I/O buffer used for buffering data read from the network */
828    struct iob iob[1];
829
830    /** List of all headers for this request */
831    struct list headers[1];
832
833    /** List of all tags that apply to this request */
834    struct list tags[1];
835
836    /** MIME-Type key, see CT_* above */
837    unsigned int content_type;
838
839    /** Actions files associated with this client */
840    struct file_list *actions_list[MAX_AF_FILES];
841
842    /** pcrs job files. */
843    struct file_list *rlist[MAX_AF_FILES];
844
845    /** Length after content modification. */
846    unsigned long long content_length;
847
848 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
849    /** Expected length of content after which we
850     * should stop reading from the server socket.
851     */
852    /* XXX: is this the right location? */
853    unsigned long long expected_content_length;
854 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
855
856 #ifdef FEATURE_TRUST
857
858    /** Trust file. */
859    struct file_list *tlist;
860
861 #endif /* def FEATURE_TRUST */
862
863    /**
864     * Failure reason to embedded in the CGI error page,
865     * or NULL. Currently only used for socks errors.
866     */
867    char *error_message;
868
869    /** Next thread in linked list. Only read or modify from the main thread! */
870    struct client_state *next;
871 };
872
873
874 /**
875  * A function to add a header
876  */
877 typedef jb_err (*add_header_func_ptr)(struct client_state *);
878
879 /**
880  * A function to process a header
881  */
882 typedef jb_err (*parser_func_ptr    )(struct client_state *, char **);
883
884
885 /**
886  * List of available CGI functions.
887  */
888 struct cgi_dispatcher
889 {
890    /** The URL of the CGI, relative to the CGI root. */
891    const char * const name;
892
893    /** The handler function for the CGI */
894    jb_err    (* const handler)(struct client_state *csp, struct http_response *rsp, const struct map *parameters);
895
896    /** The description of the CGI, to appear on the main menu, or NULL to hide it. */
897    const char * const description;
898
899    /** A flag that indicates whether unintentional calls to this CGI can cause damage */
900    int harmless;
901 };
902
903
904 /**
905  * A data file used by Privoxy.  Kept in a linked list.
906  */
907 struct file_list
908 {
909    /**
910     * This is a pointer to the data structures associated with the file.
911     * Read-only once the structure has been created.
912     */
913    void *f;
914
915    /**
916     * The unloader function.
917     * Normally NULL.  When we are finished with file (i.e. when we have
918     * loaded a new one), set to a pointer to an unloader function.
919     * Unloader will be called by sweep() (called from main loop) when
920     * all clients using this file are done.  This prevents threading
921     * problems.
922     */
923    void (*unloader)(void *);
924
925    /**
926     * Used internally by sweep().  Do not access from elsewhere.
927     */
928    int active;
929
930    /**
931     * File last-modified time, so we can check if file has been changed.
932     * Read-only once the structure has been created.
933     */
934    time_t lastmodified;
935    
936    /**
937     * The full filename.
938     */
939    char * filename;
940
941    /**
942     * Pointer to next entry in the linked list of all "file_list"s.
943     * This linked list is so that sweep() can navigate it.
944     * Since sweep() can remove items from the list, we must be careful
945     * to only access this value from main thread (when we know sweep
946     * won't be running).
947     */
948    struct file_list *next;
949 };
950
951
952 #ifdef FEATURE_TRUST
953
954 /**
955  * The format of a trust file when loaded into memory.
956  */
957 struct block_spec
958 {
959    struct url_spec url[1];   /**< The URL pattern              */
960    int    reject;            /**< FIXME: Please document this! */
961    struct block_spec *next;  /**< Next entry in linked list    */
962 };
963
964 /**
965  * Arbitrary limit for the number of trusted referrers.
966  */
967 #define MAX_TRUSTED_REFERRERS 512
968
969 #endif /* def FEATURE_TRUST */
970
971
972 #define SOCKS_NONE    0    /**< Don't use a SOCKS server               */
973 #define SOCKS_4      40    /**< original SOCKS 4 protocol              */
974 #define SOCKS_4A     41    /**< as modified for hosts w/o external DNS */
975 #define SOCKS_5      50    /**< as modified for hosts w/o external DNS */
976
977
978 /**
979  * How to forward a connection to a parent proxy.
980  */
981 struct forward_spec
982 {
983    /** URL pattern that this forward_spec is for. */
984    struct url_spec url[1];
985
986    /** Connection type.  Must be SOCKS_NONE, SOCKS_4, SOCKS_4A or SOCKS_5. */
987    int   type;
988
989    /** SOCKS server hostname.  Only valid if "type" is SOCKS_4 or SOCKS_4A. */
990    char *gateway_host;
991
992    /** SOCKS server port. */
993    int   gateway_port;
994
995    /** Parent HTTP proxy hostname, or NULL for none. */
996    char *forward_host;
997
998    /** Parent HTTP proxy port. */
999    int   forward_port;
1000
1001    /** Next entry in the linked list. */
1002    struct forward_spec *next;
1003 };
1004
1005
1006 /**
1007  * Initializer for a static struct forward_spec.
1008  */
1009 #define FORWARD_SPEC_INITIALIZER { { URL_SPEC_INITIALIZER }, 0, NULL, 0, NULL, 0, NULL }
1010
1011 /* Supported filter types */
1012 #define FT_CONTENT_FILTER       0
1013 #define FT_CLIENT_HEADER_FILTER 1
1014 #define FT_SERVER_HEADER_FILTER 2
1015 #define FT_CLIENT_HEADER_TAGGER 3
1016 #define FT_SERVER_HEADER_TAGGER 4
1017
1018 #define MAX_FILTER_TYPES        5
1019
1020 /**
1021  * This struct represents one filter (one block) from
1022  * the re_filterfile. If there is more than one filter
1023  * in the file, the file will be represented by a
1024  * chained list of re_filterfile specs.
1025  */
1026 struct re_filterfile_spec
1027 {
1028    char *name;                      /**< Name from FILTER: statement in re_filterfile. */
1029    char *description;               /**< Description from FILTER: statement in re_filterfile. */
1030    struct list patterns[1];         /**< The patterns from the re_filterfile. */
1031    pcrs_job *joblist;               /**< The resulting compiled pcrs_jobs. */
1032    int type;                        /**< Filter type (content, client-header, server-header). */
1033    int dynamic;                     /**< Set to one if the pattern might contain variables
1034                                          and has to be recompiled for every request. */
1035    struct re_filterfile_spec *next; /**< The pointer for chaining. */
1036 };
1037
1038
1039 #ifdef FEATURE_ACL
1040
1041 #define ACL_PERMIT   1  /**< Accept connection request */
1042 #define ACL_DENY     2  /**< Reject connection request */
1043
1044 /**
1045  * An IP address pattern.  Used to specify networks in the ACL.
1046  */
1047 struct access_control_addr
1048 {
1049 #ifdef HAVE_RFC2553
1050    struct sockaddr_storage addr; /* <The TCP address in network order. */
1051    struct sockaddr_storage mask; /* <The TCP mask in network order. */
1052 #else
1053    unsigned long addr;  /**< The IP address as an integer. */
1054    unsigned long mask;  /**< The network mask as an integer. */
1055    unsigned long port;  /**< The port number. */
1056 #endif /* HAVE_RFC2553 */
1057 };
1058
1059 /**
1060  * An access control list (ACL) entry.
1061  *
1062  * This is a linked list.
1063  */
1064 struct access_control_list
1065 {
1066    struct access_control_addr src[1];  /**< Client IP address */
1067    struct access_control_addr dst[1];  /**< Website or parent proxy IP address */
1068 #ifdef HAVE_RFC2553
1069    int wildcard_dst;                   /** < dst address is wildcard */
1070 #endif
1071
1072    short action;                       /**< ACL_PERMIT or ACL_DENY */
1073    struct access_control_list *next;   /**< The next entry in the ACL. */
1074 };
1075
1076 #endif /* def FEATURE_ACL */
1077
1078
1079 /** Maximum number of loaders (actions, re_filter, ...) */
1080 #define NLOADERS 8
1081
1082
1083 /** configuration_spec::feature_flags: CGI actions editor. */
1084 #define RUNTIME_FEATURE_CGI_EDIT_ACTIONS             1U
1085
1086 /** configuration_spec::feature_flags: Web-based toggle. */
1087 #define RUNTIME_FEATURE_CGI_TOGGLE                   2U
1088
1089 /** configuration_spec::feature_flags: HTTP-header-based toggle. */
1090 #define RUNTIME_FEATURE_HTTP_TOGGLE                  4U
1091
1092 /** configuration_spec::feature_flags: Split large forms to limit the number of GET arguments. */
1093 #define RUNTIME_FEATURE_SPLIT_LARGE_FORMS            8U
1094
1095 /** configuration_spec::feature_flags: Check the host header for requests with host-less request lines. */
1096 #define RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS 16U
1097
1098 /** configuration_spec::feature_flags: Don't allow to circumvent blocks with the force prefix. */
1099 #define RUNTIME_FEATURE_ENFORCE_BLOCKS              32U
1100
1101 /** configuration_spec::feature_flags: Allow to block or redirect CGI requests. */
1102 #define RUNTIME_FEATURE_CGI_CRUNCHING               64U
1103
1104 /** configuration_spec::feature_flags: Try to keep the connection to the server alive. */
1105 #define RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE      128U
1106
1107 /** configuration_spec::feature_flags: Share outgoing connections between different client connections. */
1108 #define RUNTIME_FEATURE_CONNECTION_SHARING         256U
1109
1110 /**
1111  * Data loaded from the configuration file.
1112  *
1113  * (Anomaly: toggle is still handled through a global, not this structure)
1114  */
1115 struct configuration_spec
1116 {
1117    /** What to log */
1118    int debug;
1119    
1120    /** Nonzero to enable multithreading. */
1121    int multi_threaded;
1122
1123    /**
1124     * Bitmask of features that can be enabled/disabled through the config
1125     * file.  Currently defined bits:
1126     *
1127     * - RUNTIME_FEATURE_CGI_EDIT_ACTIONS
1128     * - RUNTIME_FEATURE_CGI_TOGGLE
1129     * - RUNTIME_FEATURE_HTTP_TOGGLE
1130     * - RUNTIME_FEATURE_SPLIT_LARGE_FORMS
1131     */
1132    unsigned feature_flags;
1133
1134    /** The log file name. */
1135    const char *logfile;
1136
1137    /** The config file directory. */
1138    const char *confdir;
1139
1140    /** The directory for customized CGI templates. */
1141    const char *templdir;
1142
1143    /** The log file directory. */
1144    const char *logdir;
1145
1146    /** The full paths to the actions files. */
1147    const char *actions_file[MAX_AF_FILES];
1148
1149    /** The short names of the actions files. */
1150    const char *actions_file_short[MAX_AF_FILES];
1151
1152    /** The administrator's email address */
1153    char *admin_address;
1154
1155    /** A URL with info on this proxy */
1156    char *proxy_info_url;
1157
1158    /** URL to the user manual (on our website or local copy) */
1159    char *usermanual;
1160
1161    /** The file names of the pcre filter files. */
1162    const char *re_filterfile[MAX_AF_FILES];
1163
1164    /** The short names of the pcre filter files. */
1165    const char *re_filterfile_short[MAX_AF_FILES];
1166
1167    /** The hostname to show on CGI pages, or NULL to use the real one. */
1168    const char *hostname;
1169
1170    /** IP address to bind to.  Defaults to HADDR_DEFAULT == 127.0.0.1. */
1171    const char *haddr;
1172
1173    /** Port to bind to.  Defaults to HADDR_PORT == 8118. */
1174    int         hport;
1175
1176    /** Size limit for IOB */
1177    size_t buffer_limit;
1178
1179 #ifdef FEATURE_TRUST
1180
1181    /** The file name of the trust file. */
1182    const char * trustfile;
1183
1184    /** FIXME: DOCME: Document this. */
1185    struct list trust_info[1];
1186
1187    /** FIXME: DOCME: Document this. */
1188    struct url_spec *trust_list[MAX_TRUSTED_REFERRERS];
1189
1190 #endif /* def FEATURE_TRUST */
1191
1192 #ifdef FEATURE_ACL
1193
1194    /** The access control list (ACL). */
1195    struct access_control_list *acl;
1196
1197 #endif /* def FEATURE_ACL */
1198
1199    /** Information about parent proxies (forwarding). */
1200    struct forward_spec *forward;
1201
1202    /** Number of retries in case a forwarded connection attempt fails */
1203    int forwarded_connect_retries;
1204
1205    /** Maximum number of client connections. */
1206    int max_client_connections;
1207
1208    /* Timeout when waiting on sockets for data to become available. */
1209    int socket_timeout;
1210
1211 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1212    /* Maximum number of seconds after which an open connection will no longer be reused. */
1213    unsigned int keep_alive_timeout;
1214 #endif
1215
1216    /** All options from the config file, HTML-formatted. */
1217    char *proxy_args;
1218
1219    /** The configuration file object. */
1220    struct file_list *config_file_list;
1221
1222    /** List of loaders */
1223    int (*loaders[NLOADERS])(struct client_state *);
1224
1225    /** Nonzero if we need to bind() to the new port. */
1226    int need_bind;
1227 };
1228
1229 /** Calculates the number of elements in an array, using sizeof. */
1230 #define SZ(X)  (sizeof(X) / sizeof(*X))
1231
1232 #ifdef FEATURE_FORCE_LOAD
1233 /** The force load URL prefix. */
1234 #define FORCE_PREFIX "/PRIVOXY-FORCE"
1235 #endif /* def FEATURE_FORCE_LOAD */
1236
1237 #ifdef FEATURE_NO_GIFS
1238 /** The MIME type for images ("image/png" or "image/gif"). */
1239 #define BUILTIN_IMAGE_MIMETYPE "image/png"
1240 #else
1241 #define BUILTIN_IMAGE_MIMETYPE "image/gif"
1242 #endif /* def FEATURE_NO_GIFS */
1243
1244
1245 /* 
1246  * Hardwired URLs
1247  */
1248
1249 /** URL for the Privoxy home page. */
1250 #define HOME_PAGE_URL     "http://www.privoxy.org/"
1251
1252 /** URL for the Privoxy user manual. */
1253 #define USER_MANUAL_URL   HOME_PAGE_URL VERSION "/user-manual/"
1254
1255 /** Prefix for actions help links  (append to USER_MANUAL_URL). */
1256 #define ACTIONS_HELP_PREFIX "actions-file.html#"
1257
1258 /** Prefix for config option help links (append to USER_MANUAL_URL). */
1259 #define CONFIG_HELP_PREFIX  "config.html#"
1260
1261 /*
1262  * The "hosts" to intercept and display CGI pages.
1263  * First one is a hostname only, second one can specify host and path.
1264  *
1265  * Notes:
1266  * 1) Do not specify the http: prefix
1267  * 2) CGI_SITE_2_PATH must not end with /, one will be added automatically.
1268  * 3) CGI_SITE_2_PATH must start with /, unless it is the empty string.
1269  */
1270 #define CGI_SITE_1_HOST "p.p"
1271 #define CGI_SITE_2_HOST "config.privoxy.org"
1272 #define CGI_SITE_2_PATH ""
1273
1274 /**
1275  * The prefix for CGI pages.  Written out in generated HTML.
1276  * INCLUDES the trailing slash.
1277  */
1278 #define CGI_PREFIX  "http://" CGI_SITE_2_HOST CGI_SITE_2_PATH "/"
1279
1280 #ifdef __cplusplus
1281 } /* extern "C" */
1282 #endif
1283
1284 #endif /* ndef PROJECT_H_INCLUDED */
1285
1286 /*
1287   Local Variables:
1288   tab-width: 3
1289   end:
1290 */