-
Notifications
You must be signed in to change notification settings - Fork 0
/
jcc.c~
4056 lines (3605 loc) · 120 KB
/
jcc.c~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const char jcc_rcs[] = "$Id: jcc.c,v 1.375 2011/12/10 17:26:11 fabiankeil Exp $";
/*********************************************************************
*
* File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
*
* Purpose : Main file. Contains main() method, main loop, and
* the main connection-handling function.
*
* Copyright : Written by and Copyright (C) 2001-2010 the
* Privoxy team. http://www.privoxy.org/
*
* Based on the Internet Junkbuster originally written
* by and Copyright (C) 1997 Anonymous Coders and
* Junkbusters Corporation. http://www.junkbusters.com
*
* This program is free software; you can redistribute it
* and/or modify it under the terms of the GNU General
* Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public
* License for more details.
*
* The GNU General Public License should be included with
* this file. If not, you can view it at
* http://www.gnu.org/copyleft/gpl.html
* or write to the Free Software Foundation, Inc., 59
* Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*********************************************************************/
#include "config.h"
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>
#include <assert.h>
#ifdef _WIN32
# ifndef FEATURE_PTHREAD
# ifndef STRICT
# define STRICT
# endif
# include <windows.h>
# include <process.h>
# endif /* ndef FEATURE_PTHREAD */
# include "win32.h"
# ifndef _WIN_CONSOLE
# include "w32log.h"
# endif /* ndef _WIN_CONSOLE */
# include "w32svrapi.h"
#else /* ifndef _WIN32 */
# if !defined (__OS2__)
# include <unistd.h>
# include <sys/wait.h>
# endif /* ndef __OS2__ */
# include <sys/time.h>
# include <sys/stat.h>
# include <sys/ioctl.h>
#ifdef sun
#include <sys/termios.h>
#endif /* sun */
#ifdef unix
#include <pwd.h>
#include <grp.h>
#endif
# include <signal.h>
# ifdef __BEOS__
# include <socket.h> /* BeOS has select() for sockets only. */
# include <OS.h> /* declarations for threads and stuff. */
# endif
# if defined(__EMX__) || defined(__OS2__)
# include <sys/select.h> /* OS/2/EMX needs a little help with select */
# endif
# ifdef __OS2__
#define INCL_DOS
# include <os2.h>
#define bzero(B,N) memset(B,0x00,n)
# endif
# ifndef FD_ZERO
# include <select.h>
# endif
#endif
#include "project.h"
#include "list.h"
#include "jcc.h"
#include "filters.h"
#include "loaders.h"
#include "parsers.h"
#include "miscutil.h"
#include "errlog.h"
#include "jbsockets.h"
#include "gateway.h"
#include "actions.h"
#include "cgi.h"
#include "loadcfg.h"
#include "urlmatch.h"
#include "replace.h"
const char jcc_h_rcs[] = JCC_H_VERSION;
const char project_h_rcs[] = PROJECT_H_VERSION;
int daemon_mode = 1;
struct client_states clients[1];
struct file_list files[1];
#ifdef FEATURE_STATISTICS
int urls_read = 0; /* total nr of urls read inc rejected */
int urls_rejected = 0; /* total nr of urls rejected */
#endif /* def FEATURE_STATISTICS */
#ifdef FEATURE_GRACEFUL_TERMINATION
int g_terminate = 0;
#endif
#if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
static void sig_handler(int the_signal);
#endif
static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
static jb_err get_server_headers(struct client_state *csp);
static const char *crunch_reason(const struct http_response *rsp);
static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
static char *get_request_line(struct client_state *csp);
static jb_err receive_client_request(struct client_state *csp);
static jb_err parse_client_request(struct client_state *csp);
static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
static jb_err change_request_destination(struct client_state *csp);
static void chat(struct client_state *csp);
static void serve(struct client_state *csp);
#if !defined(_WIN32) || defined(_WIN_CONSOLE)
static void usage(const char *myname);
#endif
static void initialize_mutexes(void);
static jb_socket bind_port_helper(const char *haddr, int hport);
static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
static void close_ports_helper(jb_socket sockets[]);
static void listen_loop(void);
#ifdef AMIGA
void serve(struct client_state *csp);
#else /* ifndef AMIGA */
static void serve(struct client_state *csp);
#endif /* def AMIGA */
#ifdef __BEOS__
static int32 server_thread(void *data);
#endif /* def __BEOS__ */
#ifdef _WIN32
#define sleep(N) Sleep(((N) * 1000))
#endif
#ifdef __OS2__
#define sleep(N) DosSleep(((N) * 100))
#endif
#ifdef MUTEX_LOCKS_AVAILABLE
/*
* XXX: Does the locking stuff really belong in this file?
*/
privoxy_mutex_t log_mutex;
privoxy_mutex_t log_init_mutex;
privoxy_mutex_t connection_reuse_mutex;
#if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
privoxy_mutex_t resolver_mutex;
#endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
#ifndef HAVE_GMTIME_R
privoxy_mutex_t gmtime_mutex;
#endif /* ndef HAVE_GMTIME_R */
#ifndef HAVE_LOCALTIME_R
privoxy_mutex_t localtime_mutex;
#endif /* ndef HAVE_GMTIME_R */
#ifndef HAVE_RANDOM
privoxy_mutex_t rand_mutex;
#endif /* ndef HAVE_RANDOM */
#endif /* def MUTEX_LOCKS_AVAILABLE */
#if defined(unix)
const char *basedir = NULL;
const char *pidfile = NULL;
static int received_hup_signal = 0;
#endif /* defined unix */
/* HTTP snipplets. */
static const char CSUCCEED[] =
"HTTP/1.1 200 Connection established\r\n"
"Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
static const char CHEADER[] =
"HTTP/1.1 400 Invalid header received from client\r\n"
"Proxy-Agent: Privoxy " VERSION "\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"
"Invalid header received from client.\r\n";
static const char FTP_RESPONSE[] =
"HTTP/1.1 400 Invalid request received from client\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"
"Invalid request. Privoxy doesn't support FTP.\r\n";
static const char GOPHER_RESPONSE[] =
"HTTP/1.1 400 Invalid request received from client\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"
"Invalid request. Privoxy doesn't support gopher.\r\n";
/* XXX: should be a template */
static const char MISSING_DESTINATION_RESPONSE[] =
"HTTP/1.1 400 Bad request received from client\r\n"
"Proxy-Agent: Privoxy " VERSION "\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"
"Bad request. Privoxy was unable to extract the destination.\r\n";
/* XXX: should be a template */
static const char INVALID_SERVER_HEADERS_RESPONSE[] =
"HTTP/1.1 502 Server or forwarder response invalid\r\n"
"Proxy-Agent: Privoxy " VERSION "\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"
"Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
/* XXX: should be a template */
static const char MESSED_UP_REQUEST_RESPONSE[] =
"HTTP/1.1 400 Malformed request after rewriting\r\n"
"Proxy-Agent: Privoxy " VERSION "\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"
"Bad request. Messed up with header filters.\r\n";
static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
"HTTP/1.1 503 Too many open connections\r\n"
"Proxy-Agent: Privoxy " VERSION "\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"
"Maximum number of open connections reached.\r\n";
static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
"HTTP/1.1 504 Connection timeout\r\n"
"Proxy-Agent: Privoxy " VERSION "\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"
"The connection timed out because the client request didn't arrive in time.\r\n";
/* A function to crunch a response */
typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
/* Crunch function flags */
#define CF_NO_FLAGS 0
/* Cruncher applies to forced requests as well */
#define CF_IGNORE_FORCE 1
/* Crunched requests are counted for the block statistics */
#define CF_COUNT_AS_REJECT 2
/* A crunch function and its flags */
struct cruncher
{
const crunch_func_ptr cruncher;
const int flags;
};
static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
/* Complete list of cruncher functions */
static const struct cruncher crunchers_all[] = {
{ direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
{ block_url, CF_COUNT_AS_REJECT },
#ifdef FEATURE_TRUST
{ trust_url, CF_COUNT_AS_REJECT },
#endif /* def FEATURE_TRUST */
{ redirect_url, CF_NO_FLAGS },
{ dispatch_cgi, CF_IGNORE_FORCE},
{ NULL, 0 }
};
/* Light version, used after tags are applied */
static const struct cruncher crunchers_light[] = {
{ block_url, CF_COUNT_AS_REJECT },
{ redirect_url, CF_NO_FLAGS },
{ NULL, 0 }
};
/*
* XXX: Don't we really mean
*
* #if defined(unix)
*
* here?
*/
#if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
/*********************************************************************
*
* Function : sig_handler
*
* Description : Signal handler for different signals.
* Exit gracefully on TERM and INT
* or set a flag that will cause the errlog
* to be reopened by the main thread on HUP.
*
* Parameters :
* 1 : the_signal = the signal cause this function to call
*
* Returns : -
*
*********************************************************************/
static void sig_handler(int the_signal)
{
switch(the_signal)
{
case SIGTERM:
case SIGINT:
log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
#if defined(unix)
if(pidfile)
{
unlink(pidfile);
}
#endif /* unix */
exit(the_signal);
break;
case SIGHUP:
#if defined(unix)
received_hup_signal = 1;
#endif
break;
default:
/*
* We shouldn't be here, unless we catch signals
* in main() that we can't handle here!
*/
log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
}
return;
}
#endif
/*********************************************************************
*
* Function : client_protocol_is_unsupported
*
* Description : Checks if the client used a known unsupported
* protocol and deals with it by sending an error
* response.
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
* 2 : req = the first request line send by the client
*
* Returns : TRUE if an error response has been generated, or
* FALSE if the request doesn't look invalid.
*
*********************************************************************/
static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
{
/*
* If it's a FTP or gopher request, we don't support it.
*
* These checks are better than nothing, but they might
* not work in all configurations and some clients might
* have problems digesting the answer.
*
* They should, however, never cause more problems than
* Privoxy's old behaviour (returning the misleading HTML
* error message:
*
* "Could not resolve http://(ftp|gopher)://example.org").
*/
if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
{
const char *response = NULL;
const char *protocol = NULL;
if (!strncmpic(req, "GET ftp://", 10))
{
response = FTP_RESPONSE;
protocol = "FTP";
}
else
{
response = GOPHER_RESPONSE;
protocol = "GOPHER";
}
log_error(LOG_LEVEL_ERROR,
"%s tried to use Privoxy as %s proxy: %s",
csp->ip_addr_str, protocol, req);
log_error(LOG_LEVEL_CLF,
"%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
freez(req);
write_socket(csp->cfd, response, strlen(response));
return TRUE;
}
return FALSE;
}
/*********************************************************************
*
* Function : get_request_destination_elsewhere
*
* Description : If the client's request was redirected into
* Privoxy without the client's knowledge,
* the request line lacks the destination host.
*
* This function tries to get it elsewhere,
* provided accept-intercepted-requests is enabled.
*
* "Elsewhere" currently only means "Host: header",
* but in the future we may ask the redirecting
* packet filter to look the destination up.
*
* If the destination stays unknown, an error
* response is send to the client and headers
* are freed so that chat() can return directly.
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
* 2 : headers = a header list
*
* Returns : JB_ERR_OK if the destination is now known, or
* JB_ERR_PARSE if it isn't.
*
*********************************************************************/
static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
{
char *req;
if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
{
log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
" Privoxy isn't configured to accept intercepted requests.",
csp->ip_addr_str, csp->http->cmd);
/* XXX: Use correct size */
log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
csp->ip_addr_str, csp->http->cmd);
write_socket(csp->cfd, CHEADER, strlen(CHEADER));
destroy_list(headers);
return JB_ERR_PARSE;
}
else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
{
#ifndef FEATURE_EXTENDED_HOST_PATTERNS
/* Split the domain we just got for pattern matching */
init_domain_components(csp->http);
#endif
return JB_ERR_OK;
}
else
{
/* We can't work without destination. Go spread the news.*/
req = list_to_text(headers);
chomp(req);
/* XXX: Use correct size */
log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
csp->ip_addr_str, csp->http->cmd);
log_error(LOG_LEVEL_ERROR,
"Privoxy was unable to get the destination for %s's request:\n%s\n%s",
csp->ip_addr_str, csp->http->cmd, req);
freez(req);
write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
destroy_list(headers);
return JB_ERR_PARSE;
}
/*
* TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
* to get the destination IP address, use it as host directly
* or do a reverse DNS lookup first.
*/
}
/*********************************************************************
*
* Function : get_server_headers
*
* Description : Parses server headers in iob and fills them
* into csp->headers so that they can later be
* handled by sed().
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
*
* Returns : JB_ERR_OK if everything went fine, or
* JB_ERR_PARSE if the headers were incomplete.
*
*********************************************************************/
static jb_err get_server_headers(struct client_state *csp)
{
int continue_hack_in_da_house = 0;
char * header;
while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
{
if (header == NULL)
{
/*
* continue hack in da house. Ignore the ending of
* this head and continue enlisting header lines.
* The reason is described below.
*/
enlist(csp->headers, "");
continue_hack_in_da_house = 0;
continue;
}
else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
{
/*
* It's a bodyless continue response, don't
* stop header parsing after reaching its end.
*
* As a result Privoxy will concatenate the
* next response's head and parse and deliver
* the headers as if they belonged to one request.
*
* The client will separate them because of the
* empty line between them.
*
* XXX: What we're doing here is clearly against
* the intended purpose of the continue header,
* and under some conditions (HTTP/1.0 client request)
* it's a standard violation.
*
* Anyway, "sort of against the spec" is preferable
* to "always getting confused by Continue responses"
* (Privoxy's behaviour before this hack was added)
*/
log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
continue_hack_in_da_house = 1;
}
else if (*header == '\0')
{
/*
* If the header is empty, but the Continue hack
* isn't active, we can assume that we reached the
* end of the buffer before we hit the end of the
* head.
*
* Inform the caller an let it decide how to handle it.
*/
return JB_ERR_PARSE;
}
if (JB_ERR_MEMORY == enlist(csp->headers, header))
{
/*
* XXX: Should we quit the request and return a
* out of memory error page instead?
*/
log_error(LOG_LEVEL_ERROR,
"Out of memory while enlisting server headers. %s lost.",
header);
}
freez(header);
}
return JB_ERR_OK;
}
/*********************************************************************
*
* Function : crunch_reason
*
* Description : Translates the crunch reason code into a string.
*
* Parameters :
* 1 : rsp = a http_response
*
* Returns : A string with the crunch reason or an error description.
*
*********************************************************************/
static const char *crunch_reason(const struct http_response *rsp)
{
char * reason = NULL;
assert(rsp != NULL);
if (rsp == NULL)
{
return "Internal error while searching for crunch reason";
}
switch (rsp->crunch_reason)
{
case UNSUPPORTED:
reason = "Unsupported HTTP feature";
break;
case BLOCKED:
reason = "Blocked";
break;
case UNTRUSTED:
reason = "Untrusted";
break;
case REDIRECTED:
reason = "Redirected";
break;
case CGI_CALL:
reason = "CGI Call";
break;
case NO_SUCH_DOMAIN:
reason = "DNS failure";
break;
case FORWARDING_FAILED:
reason = "Forwarding failed";
break;
case CONNECT_FAILED:
reason = "Connection failure";
break;
case OUT_OF_MEMORY:
reason = "Out of memory (may mask other reasons)";
break;
case CONNECTION_TIMEOUT:
reason = "Connection timeout";
break;
case NO_SERVER_DATA:
reason = "No server data received";
break;
default:
reason = "No reason recorded";
break;
}
return reason;
}
/*********************************************************************
*
* Function : send_crunch_response
*
* Description : Delivers already prepared response for
* intercepted requests, logs the interception
* and frees the response.
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
* 1 : rsp = Fully prepared response. Will be freed on exit.
*
* Returns : Nothing.
*
*********************************************************************/
static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
{
const struct http_request *http = csp->http;
char status_code[4];
assert(rsp != NULL);
assert(rsp->head != NULL);
if (rsp == NULL)
{
log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
}
/*
* Extract the status code from the actual head
* that will be send to the client. It is the only
* way to get it right for all requests, including
* the fixed ones for out-of-memory problems.
*
* A head starts like this: 'HTTP/1.1 200...'
* 0123456789|11
* 10
*/
status_code[0] = rsp->head[9];
status_code[1] = rsp->head[10];
status_code[2] = rsp->head[11];
status_code[3] = '\0';
/* Log that the request was crunched and why. */
log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
/* Write the answer to the client */
if (write_socket(csp->cfd, rsp->head, rsp->head_length)
|| write_socket(csp->cfd, rsp->body, rsp->content_length))
{
/* There is nothing we can do about it. */
log_error(LOG_LEVEL_ERROR,
"Couldn't deliver the error message through client socket %d: %E",
csp->cfd);
}
/* Clean up and return */
if (cgi_error_memory() != rsp)
{
free_http_response(rsp);
}
return;
}
/*********************************************************************
*
* Function : crunch_response_triggered
*
* Description : Checks if the request has to be crunched,
* and delivers the crunch response if necessary.
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
* 2 : crunchers = list of cruncher functions to run
*
* Returns : TRUE if the request was answered with a crunch response
* FALSE otherwise.
*
*********************************************************************/
static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
{
struct http_response *rsp = NULL;
const struct cruncher *c;
/*
* If CGI request crunching is disabled,
* check the CGI dispatcher out of order to
* prevent unintentional blocks or redirects.
*/
if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
&& (NULL != (rsp = dispatch_cgi(csp))))
{
/* Deliver, log and free the interception response. */
send_crunch_response(csp, rsp);
csp->flags |= CSP_FLAG_CRUNCHED;
return TRUE;
}
for (c = crunchers; c->cruncher != NULL; c++)
{
/*
* Check the cruncher if either Privoxy is toggled
* on and the request isn't forced, or if the cruncher
* applies to forced requests as well.
*/
if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
!(csp->flags & CSP_FLAG_FORCED)) ||
(c->flags & CF_IGNORE_FORCE))
{
rsp = c->cruncher(csp);
if (NULL != rsp)
{
/* Deliver, log and free the interception response. */
send_crunch_response(csp, rsp);
csp->flags |= CSP_FLAG_CRUNCHED;
#ifdef FEATURE_STATISTICS
if (c->flags & CF_COUNT_AS_REJECT)
{
csp->flags |= CSP_FLAG_REJECTED;
}
#endif /* def FEATURE_STATISTICS */
return TRUE;
}
}
}
return FALSE;
}
/*********************************************************************
*
* Function : build_request_line
*
* Description : Builds the HTTP request line.
*
* If a HTTP forwarder is used it expects the whole URL,
* web servers only get the path.
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
* 2 : fwd = The forwarding spec used for the request
* XXX: Should use http->fwd instead.
* 3 : request_line = The old request line which will be replaced.
*
* Returns : Nothing. Terminates in case of memory problems.
*
*********************************************************************/
static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
{
struct http_request *http = csp->http;
assert(http->ssl == 0);
/*
* Downgrade http version from 1.1 to 1.0
* if +downgrade action applies.
*/
if ( (csp->action->flags & ACTION_DOWNGRADE)
&& (!strcmpic(http->ver, "HTTP/1.1")))
{
freez(http->ver);
http->ver = strdup("HTTP/1.0");
if (http->ver == NULL)
{
log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
}
}
/*
* Rebuild the request line.
*/
freez(*request_line);
*request_line = strdup(http->gpc);
string_append(request_line, " ");
if (fwd->forward_host)
{
string_append(request_line, http->url);
}
else
{
string_append(request_line, http->path);
}
string_append(request_line, " ");
string_append(request_line, http->ver);
if (*request_line == NULL)
{
log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
}
log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
}
/*********************************************************************
*
* Function : change_request_destination
*
* Description : Parse a (rewritten) request line and regenerate
* the http request data.
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
*
* Returns : Forwards the parse_http_request() return code.
* Terminates in case of memory problems.
*
*********************************************************************/
static jb_err change_request_destination(struct client_state *csp)
{
struct http_request *http = csp->http;
jb_err err;
log_error(LOG_LEVEL_INFO, "Rewrite detected: %s", csp->headers->first->str);
free_http_request(http);
err = parse_http_request(csp->headers->first->str, http);
if (JB_ERR_OK != err)
{
log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
jb_err_to_string(err));
}
else
{
/* XXX: ocmd is a misleading name */
http->ocmd = strdup(http->cmd);
if (http->ocmd == NULL)
{
log_error(LOG_LEVEL_FATAL,
"Out of memory copying rewritten HTTP request line");
}
}
return err;
}
#ifdef FEATURE_CONNECTION_KEEP_ALIVE
/*********************************************************************
*
* Function : server_response_is_complete
*
* Description : Determines whether we should stop reading
* from the server socket.
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
* 2 : content_length = Length of content received so far.
*
* Returns : TRUE if the response is complete,
* FALSE otherwise.
*
*********************************************************************/
static int server_response_is_complete(struct client_state *csp,
unsigned long long content_length)
{
int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
if (!strcmpic(csp->http->gpc, "HEAD"))
{
/*
* "HEAD" implies no body, we are thus expecting
* no content. XXX: incomplete "list" of methods?
*/
csp->expected_content_length = 0;
content_length_known = TRUE;
}
if (csp->http->status == 204 || csp->http->status == 304)
{
/*
* Expect no body. XXX: incomplete "list" of status codes?
*/
csp->expected_content_length = 0;
content_length_known = TRUE;
}
return (content_length_known && ((0 == csp->expected_content_length)
|| (csp->expected_content_length <= content_length)));
}
#ifdef FEATURE_CONNECTION_SHARING
/*********************************************************************
*
* Function : wait_for_alive_connections
*
* Description : Waits for alive connections to timeout.
*
* Parameters : N/A
*
* Returns : N/A
*
*********************************************************************/
static void wait_for_alive_connections(void)
{
int connections_alive = close_unusable_connections();
while (0 < connections_alive)
{
log_error(LOG_LEVEL_CONNECT,
"Waiting for %d connections to timeout.",
connections_alive);
sleep(60);
connections_alive = close_unusable_connections();
}
log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
}
#endif /* def FEATURE_CONNECTION_SHARING */
/*********************************************************************
*
* Function : save_connection_destination
*
* Description : Remembers a connection for reuse later on.
*
* Parameters :
* 1 : sfd = Open socket to remember.
* 2 : http = The destination for the connection.
* 3 : fwd = The forwarder settings used.
* 3 : server_connection = storage.
*
* Returns : void
*
*********************************************************************/
void save_connection_destination(jb_socket sfd,
const struct http_request *http,