javascript needs to be blocked with +handle-as-empty-document to
[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.156 2010/05/24 11:38:22 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-2010 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 enum crunch_reason
312 {
313    UNSUPPORTED,
314    BLOCKED,
315    UNTRUSTED,
316    REDIRECTED,
317    CGI_CALL,
318    NO_SUCH_DOMAIN,
319    FORWARDING_FAILED,
320    CONNECT_FAILED,
321    OUT_OF_MEMORY,
322    INTERNAL_ERROR,
323    CONNECTION_TIMEOUT,
324    NO_SERVER_DATA
325 };
326
327 /**
328  * Response generated by CGI, blocker, or error handler
329  */
330 struct http_response
331 {
332   enum crunch_reason crunch_reason; /**< Why the response was generated in the first place. */
333   char  *status;                    /**< HTTP status (string). */
334   struct list headers[1];           /**< List of header lines. */
335   char  *head;                      /**< Formatted http response head. */
336   size_t head_length;               /**< Length of http response head. */
337   char  *body;                      /**< HTTP document body. */
338   size_t content_length;            /**< Length of body, REQUIRED if binary body. */
339   int    is_static;                 /**< Nonzero if the content will never change and
340                                          should be cached by the browser (e.g. images). */
341 };
342
343 /**
344  * A URL or a tag pattern.
345  */
346 struct url_spec
347 {
348    /** The string which was parsed to produce this url_spec.
349        Used for debugging or display only.  */
350    char  *spec;
351
352 #ifdef FEATURE_EXTENDED_HOST_PATTERNS
353    regex_t *host_regex;/**< Regex for host matching                          */
354 #else
355    char  *dbuffer;     /**< Buffer with '\0'-delimited domain name, or NULL to match all hosts. */
356    char **dvec;        /**< List of pointers to the strings in dbuffer.       */
357    int    dcount;      /**< How many parts to this domain? (length of dvec)   */
358    int    unanchored;  /**< Bitmap - flags are ANCHOR_LEFT and ANCHOR_RIGHT.  */
359 #endif /* defined FEATURE_EXTENDED_HOST_PATTERNS */
360
361    char  *port_list;   /**< List of acceptable ports, or NULL to match all ports */
362
363    regex_t *preg;      /**< Regex for matching path part                      */
364    regex_t *tag_regex; /**< Regex for matching tags                           */
365 };
366
367 /**
368  * If you declare a static url_spec, this is the value to initialize it to zero.
369  */
370 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
371 #define URL_SPEC_INITIALIZER { NULL, NULL, NULL, 0, 0, NULL, NULL, NULL }
372 #else
373 #define URL_SPEC_INITIALIZER { NULL, NULL, NULL, NULL, NULL }
374 #endif /* def FEATURE_EXTENDED_HOST_PATTERNS */
375
376 /**
377  * Constant for host part matching in URLs.  If set, indicates that the start of
378  * the pattern must match the start of the URL.  E.g. this is not set for the
379  * pattern ".example.com", so that it will match both "example.com" and
380  * "www.example.com".  It is set for the pattern "example.com", which makes it
381  * match "example.com" only, not "www.example.com".
382  */
383 #define ANCHOR_LEFT  1
384
385 /**
386  * Constant for host part matching in URLs.  If set, indicates that the end of
387  * the pattern must match the end of the URL.  E.g. this is not set for the
388  * pattern "ad.", so that it will match any host called "ad", irrespective
389  * of how many subdomains are in the fully-qualified domain name.
390  */
391 #define ANCHOR_RIGHT 2
392
393
394 /**
395  * An I/O buffer.  Holds a string which can be appended to, and can have data
396  * removed from the beginning.
397  */
398 struct iob
399 {
400    char *buf;    /**< Start of buffer        */
401    char *cur;    /**< Start of relevant data */
402    char *eod;    /**< End of relevant data   */
403    size_t size;  /**< Size as malloc()ed     */
404 };
405
406
407 /**
408  * Return the number of bytes in the I/O buffer associated with the passed
409  * client_state pointer.
410  * May be zero.
411  */
412 #define IOB_PEEK(CSP) ((CSP->iob->cur > CSP->iob->eod) ? (CSP->iob->eod - CSP->iob->cur) : 0)
413
414
415 /**
416  * Remove any data in the I/O buffer associated with the passed
417  * client_state pointer.
418  */
419 #define IOB_RESET(CSP) if(CSP->iob->buf) free(CSP->iob->buf); memset(CSP->iob, '\0', sizeof(CSP->iob));
420
421 /* Bits for csp->content_type bitmask: */
422 #define CT_TEXT    0x0001U /**< Suitable for pcrs filtering. */
423 #define CT_GIF     0x0002U /**< Suitable for GIF filtering.  */
424 #define CT_TABOO   0x0004U /**< DO NOT filter, irrespective of other flags. */
425
426 /* Although these are not, strictly speaking, content types
427  * (they are content encodings), it is simple to handle them
428  * as such.
429  */
430 #define CT_GZIP    0x0010U /**< gzip-compressed data. */
431 #define CT_DEFLATE 0x0020U /**< zlib-compressed data. */
432
433 /**
434  * Flag to signal that the server declared the content type,
435  * so we can differentiate between unknown and undeclared
436  * content types.
437  */
438 #define CT_DECLARED 0x0040U
439
440 /**
441  * The mask which includes all actions.
442  */
443 #define ACTION_MASK_ALL        (~0UL)
444
445 /**
446  * The most compatible set of actions - i.e. none.
447  */
448 #define ACTION_MOST_COMPATIBLE                       0x00000000UL
449
450 /** Action bitmap: Block the request. */
451 #define ACTION_BLOCK                                 0x00000001UL
452 /** Action bitmap: Deanimate if it's a GIF. */
453 #define ACTION_DEANIMATE                             0x00000002UL
454 /** Action bitmap: Downgrade HTTP/1.1 to 1.0. */
455 #define ACTION_DOWNGRADE                             0x00000004UL
456 /** Action bitmap: Fast redirects. */
457 #define ACTION_FAST_REDIRECTS                        0x00000008UL
458 /** Action bitmap: Remove or add "X-Forwarded-For" header. */
459 #define ACTION_CHANGE_X_FORWARDED_FOR                0x00000010UL
460 /** Action bitmap: Hide "From" header. */
461 #define ACTION_HIDE_FROM                             0x00000020UL
462 /** Action bitmap: Hide "Referer" header.  (sic - follow HTTP, not English). */
463 #define ACTION_HIDE_REFERER                          0x00000040UL
464 /** Action bitmap: Hide "User-Agent" and similar headers. */
465 #define ACTION_HIDE_USER_AGENT                       0x00000080UL
466 /** Action bitmap: This is an image. */
467 #define ACTION_IMAGE                                 0x00000100UL
468 /** Action bitmap: Sets the image blocker. */
469 #define ACTION_IMAGE_BLOCKER                         0x00000200UL
470 /** Action bitmap: Prevent compression. */
471 #define ACTION_NO_COMPRESSION                        0x00000400UL
472 /** Action bitmap: Change cookies to session only cookies. */
473 #define ACTION_NO_COOKIE_KEEP                        0x00000800UL
474 /** Action bitmap: Block rending cookies. */
475 #define ACTION_NO_COOKIE_READ                        0x00001000UL
476 /** Action bitmap: Block setting cookies. */
477 #define ACTION_NO_COOKIE_SET                         0x00002000UL
478 /** Action bitmap: Override the forward settings in the config file */
479 #define ACTION_FORWARD_OVERRIDE                      0x00004000UL
480 /** Action bitmap: Block as empty document */
481 #define  ACTION_HANDLE_AS_EMPTY_DOCUMENT             0x00008000UL
482 /** Action bitmap: Limit CONNECT requests to safe ports. */
483 #define ACTION_LIMIT_CONNECT                         0x00010000UL
484 /** Action bitmap: Redirect request. */
485 #define  ACTION_REDIRECT                             0x00020000UL
486 /** Action bitmap: Crunch or modify "if-modified-since" header. */
487 #define ACTION_HIDE_IF_MODIFIED_SINCE                0x00040000UL
488 /** Action bitmap: Overwrite Content-Type header. */
489 #define ACTION_CONTENT_TYPE_OVERWRITE                0x00080000UL
490 /** Action bitmap: Crunch specified server header. */
491 #define ACTION_CRUNCH_SERVER_HEADER                  0x00100000UL
492 /** Action bitmap: Crunch specified client header */
493 #define ACTION_CRUNCH_CLIENT_HEADER                  0x00200000UL
494 /** Action bitmap: Enable text mode by force */
495 #define ACTION_FORCE_TEXT_MODE                       0x00400000UL
496 /** Action bitmap: Enable text mode by force */
497 #define ACTION_CRUNCH_IF_NONE_MATCH                  0x00800000UL
498 /** Action bitmap: Enable content-dispostion crunching */
499 #define ACTION_HIDE_CONTENT_DISPOSITION              0x01000000UL
500 /** Action bitmap: Replace or block Last-Modified header */
501 #define ACTION_OVERWRITE_LAST_MODIFIED               0x02000000UL
502 /** Action bitmap: Replace or block Accept-Language header */
503 #define ACTION_HIDE_ACCEPT_LANGUAGE                  0x04000000UL
504
505
506 /** Action string index: How to deanimate GIFs */
507 #define ACTION_STRING_DEANIMATE             0
508 /** Action string index: Replacement for "From:" header */
509 #define ACTION_STRING_FROM                  1
510 /** Action string index: How to block images */
511 #define ACTION_STRING_IMAGE_BLOCKER         2
512 /** Action string index: Replacement for "Referer:" header */
513 #define ACTION_STRING_REFERER               3
514 /** Action string index: Replacement for "User-Agent:" header */
515 #define ACTION_STRING_USER_AGENT            4
516 /** Action string index: Legal CONNECT ports. */
517 #define ACTION_STRING_LIMIT_CONNECT         5
518 /** Action string index: Server headers containing this pattern are crunched*/
519 #define ACTION_STRING_SERVER_HEADER         6
520 /** Action string index: Client headers containing this pattern are crunched*/
521 #define ACTION_STRING_CLIENT_HEADER         7
522 /** Action string index: Replacement for the "Accept-Language:" header*/
523 #define ACTION_STRING_LANGUAGE              8
524 /** Action string index: Replacement for the "Content-Type:" header*/
525 #define ACTION_STRING_CONTENT_TYPE          9
526 /** Action string index: Replacement for the "content-dispostion:" header*/
527 #define ACTION_STRING_CONTENT_DISPOSITION  10
528 /** Action string index: Replacement for the "If-Modified-Since:" header*/
529 #define ACTION_STRING_IF_MODIFIED_SINCE    11
530 /** Action string index: Replacement for the "Last-Modified:" header. */
531 #define ACTION_STRING_LAST_MODIFIED        12
532 /** Action string index: Redirect URL */
533 #define ACTION_STRING_REDIRECT             13
534 /** Action string index: Decode before redirect? */
535 #define ACTION_STRING_FAST_REDIRECTS       14
536 /** Action string index: Overriding forward rule. */
537 #define ACTION_STRING_FORWARD_OVERRIDE     15
538 /** Action string index: Reason for the block. */
539 #define ACTION_STRING_BLOCK                16
540 /** Action string index: what to do with the "X-Forwarded-For" header. */
541 #define ACTION_STRING_CHANGE_X_FORWARDED_FOR 17
542 /** Number of string actions. */
543 #define ACTION_STRING_COUNT                18
544
545
546 /* To make the ugly hack in sed easier to understand */
547 #define CHECK_EVERY_HEADER_REMAINING 0
548
549
550 /** Index into current_action_spec::multi[] for headers to add. */
551 #define ACTION_MULTI_ADD_HEADER              0
552 /** Index into current_action_spec::multi[] for content filters to apply. */
553 #define ACTION_MULTI_FILTER                  1
554 /** Index into current_action_spec::multi[] for server-header filters to apply. */
555 #define ACTION_MULTI_SERVER_HEADER_FILTER    2
556 /** Index into current_action_spec::multi[] for client-header filters to apply. */
557 #define ACTION_MULTI_CLIENT_HEADER_FILTER    3
558 /** Index into current_action_spec::multi[] for client-header tags to apply. */
559 #define ACTION_MULTI_CLIENT_HEADER_TAGGER    4
560 /** Index into current_action_spec::multi[] for server-header tags to apply. */
561 #define ACTION_MULTI_SERVER_HEADER_TAGGER    5
562 /** Number of multi-string actions. */
563 #define ACTION_MULTI_COUNT                   6
564
565
566 /**
567  * This structure contains a list of actions to apply to a URL.
568  * It only contains positive instructions - no "-" options.
569  * It is not used to store the actions list itself, only for
570  * url_actions() to return the current values.
571  */
572 struct current_action_spec
573 {
574    /** Actions to apply.  A bit set to "1" means perform the action. */
575    unsigned long flags;
576
577    /**
578     * Paramaters for those actions that require them.
579     * Each entry is valid if & only if the corresponding entry in "flags" is
580     * set.
581     */
582    char * string[ACTION_STRING_COUNT];
583
584    /** Lists of strings for multi-string actions. */
585    struct list multi[ACTION_MULTI_COUNT][1];
586 };
587
588
589 /**
590  * This structure contains a set of changes to actions.
591  * It can contain both positive and negative instructions.
592  * It is used to store an entry in the actions list.
593  */
594 struct action_spec
595 {
596    unsigned long mask; /**< Actions to keep. A bit set to "0" means remove action. */
597    unsigned long add;  /**< Actions to add.  A bit set to "1" means add action.    */
598
599    /**
600     * Paramaters for those actions that require them.
601     * Each entry is valid if & only if the corresponding entry in "flags" is
602     * set.
603     */
604    char * string[ACTION_STRING_COUNT];
605
606    /** Lists of strings to remove, for multi-string actions. */
607    struct list multi_remove[ACTION_MULTI_COUNT][1];
608
609    /** If nonzero, remove *all* strings from the multi-string action. */
610    int         multi_remove_all[ACTION_MULTI_COUNT];
611
612    /** Lists of strings to add, for multi-string actions. */
613    struct list multi_add[ACTION_MULTI_COUNT][1];
614 };
615
616
617 /**
618  * This structure is used to store action files.
619  *
620  * It contains an URL or tag pattern, and the changes to
621  * the actions. It's a linked list and should only be
622  * free'd through unload_actions_file() unless there's
623  * only a single entry.
624  */
625 struct url_actions
626 {
627    struct url_spec url[1];     /**< The URL or tag pattern. */
628
629    struct action_spec *action; /**< Action settings that might be shared with
630                                     the list entry before or after the current
631                                     one and can't be free'd willy nilly. */
632
633    struct url_actions *next;   /**< Next action section in file, or NULL. */
634 };
635
636
637 /*
638  * Structure to hold the server socket and the information
639  * required to make sure we only reuse the connection if
640  * the host and forwarding settings are the same.
641  */
642 struct reusable_connection
643 {
644    jb_socket sfd;
645    int       in_use;
646    time_t    timestamp; /* XXX: rename? */
647
648    time_t    request_sent;
649    time_t    response_received;
650
651    /*
652     * Number of seconds after which this
653     * connection will no longer be reused.
654     */
655    unsigned int keep_alive_timeout;
656
657    char *host;
658    int  port;
659    int  forwarder_type;
660    char *gateway_host;
661    int  gateway_port;
662    char *forward_host;
663    int  forward_port;
664 };
665
666
667 /*
668  * Flags for use in csp->flags
669  */
670  
671 /**
672  * Flag for csp->flags: Set if this client is processing data.
673  * Cleared when the thread associated with this structure dies.
674  */
675 #define CSP_FLAG_ACTIVE     0x01U
676
677 /**
678  * Flag for csp->flags: Set if the server's reply is in "chunked"
679  * transfer encoding
680  */
681 #define CSP_FLAG_CHUNKED    0x02U
682
683 /**
684  * Flag for csp->flags: Set if this request was enforced, although it would
685  * normally have been blocked.
686  */
687 #define CSP_FLAG_FORCED     0x04U
688
689 /**
690  * Flag for csp->flags: Set if any modification to the body was done.
691  */
692 #define CSP_FLAG_MODIFIED   0x08U
693
694 /**
695  * Flag for csp->flags: Set if request was blocked.
696  */
697 #define CSP_FLAG_REJECTED   0x10U
698
699 /**
700  * Flag for csp->flags: Set if we are toggled on (FEATURE_TOGGLE).
701  */
702 #define CSP_FLAG_TOGGLED_ON 0x20U
703
704 /**
705  * Flag for csp->flags: Set if we answered the request ourselve.
706  */
707 #define CSP_FLAG_CRUNCHED   0x40U
708
709 /**
710  * Flag for csp->flags: Set if an acceptable Connection header
711  * has already been set by the client.
712  */
713 #define CSP_FLAG_CLIENT_CONNECTION_HEADER_SET  0x00000040U
714
715 /**
716  * Flag for csp->flags: Set if an acceptable Connection header
717  * has already been set by the server.
718  */
719 #define CSP_FLAG_SERVER_CONNECTION_HEADER_SET  0x00000080U
720
721 /**
722  * Flag for csp->flags: Signals header parsers whether they
723  * are parsing server or client headers.
724  */
725 #define CSP_FLAG_CLIENT_HEADER_PARSING_DONE    0x00000100U
726
727 /**
728  * Flag for csp->flags: Set if adding the Host: header
729  * isn't necessary.
730  */
731 #define CSP_FLAG_HOST_HEADER_IS_SET            0x00000200U
732
733 /**
734  * Flag for csp->flags: Set if filtering is disabled by X-Filter: No
735  * XXX: As we now have tags we might as well ditch this.
736  */
737 #define CSP_FLAG_NO_FILTERING                  0x00000400U
738
739 /**
740  * Flag for csp->flags: Set the client IP has appended to
741  * an already existing X-Forwarded-For header in which case
742  * no new header has to be generated.
743  */
744 #define CSP_FLAG_X_FORWARDED_FOR_APPENDED      0x00000800U
745
746 /**
747  * Flag for csp->flags: Set if the server wants to keep
748  * the connection alive.
749  */
750 #define CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE  0x00001000U
751
752 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
753 /**
754  * Flag for csp->flags: Set if the server specified the
755  * content length.
756  */
757 #define CSP_FLAG_SERVER_CONTENT_LENGTH_SET     0x00002000U
758
759 /**
760  * Flag for csp->flags: Set if we know the content lenght,
761  * either because the server set it, or we figured it out
762  * on our own.
763  */
764 #define CSP_FLAG_CONTENT_LENGTH_SET            0x00004000U
765
766 /**
767  * Flag for csp->flags: Set if the client wants to keep
768  * the connection alive.
769  */
770 #define CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE  0x00008000U
771
772 /**
773  * Flag for csp->flags: Set if we think we got the whole
774  * client request and shouldn't read any additional data
775  * coming from the client until the current request has
776  * been dealt with.
777  */
778 #define CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ 0x00010000U
779
780 /**
781  * Flag for csp->flags: Set if the server promised us to
782  * keep the connection open for a known number of seconds.
783  */
784 #define CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET  0x00020000U
785
786 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
787
788 /**
789  * Flag for csp->flags: Set if we think we can't reuse
790  * the server socket.
791  */
792 #define CSP_FLAG_SERVER_SOCKET_TAINTED          0x00040000U
793
794 /**
795  * Flag for csp->flags: Set if the Proxy-Connection header
796  * is among the server headers.
797  */
798 #define CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET 0x00080000U
799
800 /**
801  * Flag for csp->flags: Set if the client reused its connection.
802  */
803 #define CSP_FLAG_REUSED_CLIENT_CONNECTION           0x00100000U
804
805 /*
806  * Flags for use in return codes of child processes
807  */
808
809 /**
810  * Flag for process return code: Set if exiting porcess has been toggled
811  * during its lifetime.
812  */
813 #define RC_FLAG_TOGGLED   0x10
814
815 /**
816  * Flag for process return code: Set if exiting porcess has blocked its
817  * request.
818  */
819 #define RC_FLAG_BLOCKED   0x20
820
821 /**
822  * Maximum number of actions/filter files.  This limit is arbitrary - it's just used
823  * to size an array.
824  */
825 #define MAX_AF_FILES 10
826
827 /**
828  * The state of a Privoxy processing thread.
829  */
830 struct client_state
831 {
832    /** The proxy's configuration */
833    struct configuration_spec * config;
834
835    /** The actions to perform on the current request */
836    struct current_action_spec  action[1];
837
838    /** socket to talk to client (web browser) */
839    jb_socket cfd;
840
841    /** current connection to the server (may go through a proxy) */
842    struct reusable_connection server_connection;
843
844    /** Multi-purpose flag container, see CSP_FLAG_* above */
845    unsigned int flags;
846
847    /** Client PC's IP address, as reported by the accept() function.
848        As a string. */
849    char *ip_addr_str;
850 #ifdef HAVE_RFC2553
851    /** Client PC's TCP address, as reported by the accept() function.
852        As a sockaddr. */
853    struct sockaddr_storage tcp_addr;
854 #else
855    /** Client PC's IP address, as reported by the accept() function.
856        As a number. */
857    unsigned long ip_addr_long;
858 #endif /* def HAVE_RFC2553 */
859
860    /** The URL that was requested */
861    struct http_request http[1];
862
863    /*
864     * The final forwarding settings.
865     * XXX: Currently this is only used for forward-override,
866     * so we can free the space in sweep.
867     */
868    struct forward_spec * fwd;
869
870    /** An I/O buffer used for buffering data read from the network */
871    struct iob iob[1];
872
873    /** List of all headers for this request */
874    struct list headers[1];
875
876    /** List of all tags that apply to this request */
877    struct list tags[1];
878
879    /** MIME-Type key, see CT_* above */
880    unsigned int content_type;
881
882    /** Actions files associated with this client */
883    struct file_list *actions_list[MAX_AF_FILES];
884
885    /** pcrs job files. */
886    struct file_list *rlist[MAX_AF_FILES];
887
888    /** Length after content modification. */
889    unsigned long long content_length;
890
891 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
892    /* XXX: is this the right location? */
893
894    /** Expected length of content after which we
895     * should stop reading from the server socket.
896     */
897    unsigned long long expected_content_length;
898
899    /** Expected length of content after which we
900     *  should stop reading from the client socket.
901     */
902    unsigned long long expected_client_content_length;
903 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
904
905 #ifdef FEATURE_TRUST
906
907    /** Trust file. */
908    struct file_list *tlist;
909
910 #endif /* def FEATURE_TRUST */
911
912    /**
913     * Failure reason to embedded in the CGI error page,
914     * or NULL. Currently only used for socks errors.
915     */
916    char *error_message;
917
918    /** Next thread in linked list. Only read or modify from the main thread! */
919    struct client_state *next;
920 };
921
922
923 /**
924  * A function to add a header
925  */
926 typedef jb_err (*add_header_func_ptr)(struct client_state *);
927
928 /**
929  * A function to process a header
930  */
931 typedef jb_err (*parser_func_ptr    )(struct client_state *, char **);
932
933
934 /**
935  * List of available CGI functions.
936  */
937 struct cgi_dispatcher
938 {
939    /** The URL of the CGI, relative to the CGI root. */
940    const char * const name;
941
942    /** The handler function for the CGI */
943    jb_err    (* const handler)(struct client_state *csp, struct http_response *rsp, const struct map *parameters);
944
945    /** The description of the CGI, to appear on the main menu, or NULL to hide it. */
946    const char * const description;
947
948    /** A flag that indicates whether unintentional calls to this CGI can cause damage */
949    int harmless;
950 };
951
952
953 /**
954  * A data file used by Privoxy.  Kept in a linked list.
955  */
956 struct file_list
957 {
958    /**
959     * This is a pointer to the data structures associated with the file.
960     * Read-only once the structure has been created.
961     */
962    void *f;
963
964    /**
965     * The unloader function.
966     * Normally NULL.  When we are finished with file (i.e. when we have
967     * loaded a new one), set to a pointer to an unloader function.
968     * Unloader will be called by sweep() (called from main loop) when
969     * all clients using this file are done.  This prevents threading
970     * problems.
971     */
972    void (*unloader)(void *);
973
974    /**
975     * Used internally by sweep().  Do not access from elsewhere.
976     */
977    int active;
978
979    /**
980     * File last-modified time, so we can check if file has been changed.
981     * Read-only once the structure has been created.
982     */
983    time_t lastmodified;
984    
985    /**
986     * The full filename.
987     */
988    char * filename;
989
990    /**
991     * Pointer to next entry in the linked list of all "file_list"s.
992     * This linked list is so that sweep() can navigate it.
993     * Since sweep() can remove items from the list, we must be careful
994     * to only access this value from main thread (when we know sweep
995     * won't be running).
996     */
997    struct file_list *next;
998 };
999
1000
1001 #ifdef FEATURE_TRUST
1002
1003 /**
1004  * The format of a trust file when loaded into memory.
1005  */
1006 struct block_spec
1007 {
1008    struct url_spec url[1];   /**< The URL pattern              */
1009    int    reject;            /**< FIXME: Please document this! */
1010    struct block_spec *next;  /**< Next entry in linked list    */
1011 };
1012
1013 /**
1014  * Arbitrary limit for the number of trusted referrers.
1015  */
1016 #define MAX_TRUSTED_REFERRERS 512
1017
1018 #endif /* def FEATURE_TRUST */
1019
1020
1021 #define SOCKS_NONE    0    /**< Don't use a SOCKS server               */
1022 #define SOCKS_4      40    /**< original SOCKS 4 protocol              */
1023 #define SOCKS_4A     41    /**< as modified for hosts w/o external DNS */
1024 #define SOCKS_5      50    /**< as modified for hosts w/o external DNS */
1025
1026
1027 /**
1028  * How to forward a connection to a parent proxy.
1029  */
1030 struct forward_spec
1031 {
1032    /** URL pattern that this forward_spec is for. */
1033    struct url_spec url[1];
1034
1035    /** Connection type.  Must be SOCKS_NONE, SOCKS_4, SOCKS_4A or SOCKS_5. */
1036    int   type;
1037
1038    /** SOCKS server hostname.  Only valid if "type" is SOCKS_4 or SOCKS_4A. */
1039    char *gateway_host;
1040
1041    /** SOCKS server port. */
1042    int   gateway_port;
1043
1044    /** Parent HTTP proxy hostname, or NULL for none. */
1045    char *forward_host;
1046
1047    /** Parent HTTP proxy port. */
1048    int   forward_port;
1049
1050    /** Next entry in the linked list. */
1051    struct forward_spec *next;
1052 };
1053
1054
1055 /**
1056  * Initializer for a static struct forward_spec.
1057  */
1058 #define FORWARD_SPEC_INITIALIZER { { URL_SPEC_INITIALIZER }, 0, NULL, 0, NULL, 0, NULL }
1059
1060 /* Supported filter types */
1061 #define FT_CONTENT_FILTER       0
1062 #define FT_CLIENT_HEADER_FILTER 1
1063 #define FT_SERVER_HEADER_FILTER 2
1064 #define FT_CLIENT_HEADER_TAGGER 3
1065 #define FT_SERVER_HEADER_TAGGER 4
1066
1067 #define MAX_FILTER_TYPES        5
1068
1069 /**
1070  * This struct represents one filter (one block) from
1071  * the re_filterfile. If there is more than one filter
1072  * in the file, the file will be represented by a
1073  * chained list of re_filterfile specs.
1074  */
1075 struct re_filterfile_spec
1076 {
1077    char *name;                      /**< Name from FILTER: statement in re_filterfile. */
1078    char *description;               /**< Description from FILTER: statement in re_filterfile. */
1079    struct list patterns[1];         /**< The patterns from the re_filterfile. */
1080    pcrs_job *joblist;               /**< The resulting compiled pcrs_jobs. */
1081    int type;                        /**< Filter type (content, client-header, server-header). */
1082    int dynamic;                     /**< Set to one if the pattern might contain variables
1083                                          and has to be recompiled for every request. */
1084    struct re_filterfile_spec *next; /**< The pointer for chaining. */
1085 };
1086
1087
1088 #ifdef FEATURE_ACL
1089
1090 #define ACL_PERMIT   1  /**< Accept connection request */
1091 #define ACL_DENY     2  /**< Reject connection request */
1092
1093 /**
1094  * An IP address pattern.  Used to specify networks in the ACL.
1095  */
1096 struct access_control_addr
1097 {
1098 #ifdef HAVE_RFC2553
1099    struct sockaddr_storage addr; /* <The TCP address in network order. */
1100    struct sockaddr_storage mask; /* <The TCP mask in network order. */
1101 #else
1102    unsigned long addr;  /**< The IP address as an integer. */
1103    unsigned long mask;  /**< The network mask as an integer. */
1104    unsigned long port;  /**< The port number. */
1105 #endif /* HAVE_RFC2553 */
1106 };
1107
1108 /**
1109  * An access control list (ACL) entry.
1110  *
1111  * This is a linked list.
1112  */
1113 struct access_control_list
1114 {
1115    struct access_control_addr src[1];  /**< Client IP address */
1116    struct access_control_addr dst[1];  /**< Website or parent proxy IP address */
1117 #ifdef HAVE_RFC2553
1118    int wildcard_dst;                   /** < dst address is wildcard */
1119 #endif
1120
1121    short action;                       /**< ACL_PERMIT or ACL_DENY */
1122    struct access_control_list *next;   /**< The next entry in the ACL. */
1123 };
1124
1125 #endif /* def FEATURE_ACL */
1126
1127
1128 /** Maximum number of loaders (actions, re_filter, ...) */
1129 #define NLOADERS 8
1130
1131
1132 /** configuration_spec::feature_flags: CGI actions editor. */
1133 #define RUNTIME_FEATURE_CGI_EDIT_ACTIONS             1U
1134
1135 /** configuration_spec::feature_flags: Web-based toggle. */
1136 #define RUNTIME_FEATURE_CGI_TOGGLE                   2U
1137
1138 /** configuration_spec::feature_flags: HTTP-header-based toggle. */
1139 #define RUNTIME_FEATURE_HTTP_TOGGLE                  4U
1140
1141 /** configuration_spec::feature_flags: Split large forms to limit the number of GET arguments. */
1142 #define RUNTIME_FEATURE_SPLIT_LARGE_FORMS            8U
1143
1144 /** configuration_spec::feature_flags: Check the host header for requests with host-less request lines. */
1145 #define RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS 16U
1146
1147 /** configuration_spec::feature_flags: Don't allow to circumvent blocks with the force prefix. */
1148 #define RUNTIME_FEATURE_ENFORCE_BLOCKS              32U
1149
1150 /** configuration_spec::feature_flags: Allow to block or redirect CGI requests. */
1151 #define RUNTIME_FEATURE_CGI_CRUNCHING               64U
1152
1153 /** configuration_spec::feature_flags: Try to keep the connection to the server alive. */
1154 #define RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE      128U
1155
1156 /** configuration_spec::feature_flags: Share outgoing connections between different client connections. */
1157 #define RUNTIME_FEATURE_CONNECTION_SHARING         256U
1158
1159 /** configuration_spec::feature_flags: Pages blocked with +handle-as-empty-doc get a return status of 200 OK. */
1160 #define RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK       512U
1161
1162 /**
1163  * Data loaded from the configuration file.
1164  *
1165  * (Anomaly: toggle is still handled through a global, not this structure)
1166  */
1167 struct configuration_spec
1168 {
1169    /** What to log */
1170    int debug;
1171    
1172    /** Nonzero to enable multithreading. */
1173    int multi_threaded;
1174
1175    /**
1176     * Bitmask of features that can be enabled/disabled through the config
1177     * file.  Currently defined bits:
1178     *
1179     * - RUNTIME_FEATURE_CGI_EDIT_ACTIONS
1180     * - RUNTIME_FEATURE_CGI_TOGGLE
1181     * - RUNTIME_FEATURE_HTTP_TOGGLE
1182     * - RUNTIME_FEATURE_SPLIT_LARGE_FORMS
1183     * - RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS
1184     * - RUNTIME_FEATURE_ENFORCE_BLOCKS
1185     * - RUNTIME_FEATURE_CGI_CRUNCHING
1186     * - RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE
1187     * - RUNTIME_FEATURE_CONNECTION_SHARING
1188     * - RUNTIME_FEATURE_EMPTY_DOC_RETURNS_OK
1189     */
1190    unsigned feature_flags;
1191
1192    /** The log file name. */
1193    const char *logfile;
1194
1195    /** The config file directory. */
1196    const char *confdir;
1197
1198    /** The directory for customized CGI templates. */
1199    const char *templdir;
1200
1201    /** The log file directory. */
1202    const char *logdir;
1203
1204    /** The full paths to the actions files. */
1205    const char *actions_file[MAX_AF_FILES];
1206
1207    /** The short names of the actions files. */
1208    const char *actions_file_short[MAX_AF_FILES];
1209
1210    /** The administrator's email address */
1211    char *admin_address;
1212
1213    /** A URL with info on this proxy */
1214    char *proxy_info_url;
1215
1216    /** URL to the user manual (on our website or local copy) */
1217    char *usermanual;
1218
1219    /** The file names of the pcre filter files. */
1220    const char *re_filterfile[MAX_AF_FILES];
1221
1222    /** The short names of the pcre filter files. */
1223    const char *re_filterfile_short[MAX_AF_FILES];
1224
1225    /** The hostname to show on CGI pages, or NULL to use the real one. */
1226    const char *hostname;
1227
1228    /** IP address to bind to.  Defaults to HADDR_DEFAULT == 127.0.0.1. */
1229    const char *haddr;
1230
1231    /** Port to bind to.  Defaults to HADDR_PORT == 8118. */
1232    int         hport;
1233
1234    /** Size limit for IOB */
1235    size_t buffer_limit;
1236
1237 #ifdef FEATURE_TRUST
1238
1239    /** The file name of the trust file. */
1240    const char * trustfile;
1241
1242    /** FIXME: DOCME: Document this. */
1243    struct list trust_info[1];
1244
1245    /** FIXME: DOCME: Document this. */
1246    struct url_spec *trust_list[MAX_TRUSTED_REFERRERS];
1247
1248 #endif /* def FEATURE_TRUST */
1249
1250 #ifdef FEATURE_ACL
1251
1252    /** The access control list (ACL). */
1253    struct access_control_list *acl;
1254
1255 #endif /* def FEATURE_ACL */
1256
1257    /** Information about parent proxies (forwarding). */
1258    struct forward_spec *forward;
1259
1260    /** Number of retries in case a forwarded connection attempt fails */
1261    int forwarded_connect_retries;
1262
1263    /** Maximum number of client connections. */
1264    int max_client_connections;
1265
1266    /* Timeout when waiting on sockets for data to become available. */
1267    int socket_timeout;
1268
1269 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1270    /* Maximum number of seconds after which an open connection will no longer be reused. */
1271    unsigned int keep_alive_timeout;
1272
1273    /* Assumed server-side keep alive timeout if none is specified. */
1274    unsigned int default_server_timeout;
1275 #endif
1276
1277    /** All options from the config file, HTML-formatted. */
1278    char *proxy_args;
1279
1280    /** The configuration file object. */
1281    struct file_list *config_file_list;
1282
1283    /** List of loaders */
1284    int (*loaders[NLOADERS])(struct client_state *);
1285
1286    /** Nonzero if we need to bind() to the new port. */
1287    int need_bind;
1288 };
1289
1290 /** Calculates the number of elements in an array, using sizeof. */
1291 #define SZ(X)  (sizeof(X) / sizeof(*X))
1292
1293 #ifdef FEATURE_FORCE_LOAD
1294 /** The force load URL prefix. */
1295 #define FORCE_PREFIX "/PRIVOXY-FORCE"
1296 #endif /* def FEATURE_FORCE_LOAD */
1297
1298 #ifdef FEATURE_NO_GIFS
1299 /** The MIME type for images ("image/png" or "image/gif"). */
1300 #define BUILTIN_IMAGE_MIMETYPE "image/png"
1301 #else
1302 #define BUILTIN_IMAGE_MIMETYPE "image/gif"
1303 #endif /* def FEATURE_NO_GIFS */
1304
1305
1306 /* 
1307  * Hardwired URLs
1308  */
1309
1310 /** URL for the Privoxy home page. */
1311 #define HOME_PAGE_URL     "http://www.privoxy.org/"
1312
1313 /** URL for the Privoxy user manual. */
1314 #define USER_MANUAL_URL   HOME_PAGE_URL VERSION "/user-manual/"
1315
1316 /** Prefix for actions help links  (append to USER_MANUAL_URL). */
1317 #define ACTIONS_HELP_PREFIX "actions-file.html#"
1318
1319 /** Prefix for config option help links (append to USER_MANUAL_URL). */
1320 #define CONFIG_HELP_PREFIX  "config.html#"
1321
1322 /*
1323  * The "hosts" to intercept and display CGI pages.
1324  * First one is a hostname only, second one can specify host and path.
1325  *
1326  * Notes:
1327  * 1) Do not specify the http: prefix
1328  * 2) CGI_SITE_2_PATH must not end with /, one will be added automatically.
1329  * 3) CGI_SITE_2_PATH must start with /, unless it is the empty string.
1330  */
1331 #define CGI_SITE_1_HOST "p.p"
1332 #define CGI_SITE_2_HOST "config.privoxy.org"
1333 #define CGI_SITE_2_PATH ""
1334
1335 /**
1336  * The prefix for CGI pages.  Written out in generated HTML.
1337  * INCLUDES the trailing slash.
1338  */
1339 #define CGI_PREFIX  "http://" CGI_SITE_2_HOST CGI_SITE_2_PATH "/"
1340
1341 #ifdef __cplusplus
1342 } /* extern "C" */
1343 #endif
1344
1345 #endif /* ndef PROJECT_H_INCLUDED */
1346
1347 /*
1348   Local Variables:
1349   tab-width: 3
1350   end:
1351 */