-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparsers.c
5296 lines (4737 loc) · 162 KB
/
parsers.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
/*********************************************************************
*
* File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
*
* Purpose : Declares functions to parse/crunch headers and pages.
*
* Copyright : Written by and Copyright (C) 2001-2021 the
* Privoxy team. https://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"
#ifndef _WIN32
#include <stdio.h>
#include <sys/types.h>
#endif
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
#include <string.h>
#ifdef __GLIBC__
/*
* Convince GNU's libc to provide a strptime prototype.
*/
#define __USE_XOPEN
#endif /*__GLIBC__ */
#include <time.h>
#ifdef FEATURE_ZLIB
#include <zlib.h>
#define GZIP_IDENTIFIER_1 0x1f
#define GZIP_IDENTIFIER_2 0x8b
#define GZIP_FLAG_CHECKSUM 0x02
#define GZIP_FLAG_EXTRA_FIELDS 0x04
#define GZIP_FLAG_FILE_NAME 0x08
#define GZIP_FLAG_COMMENT 0x10
#define GZIP_FLAG_RESERVED_BITS 0xe0
#endif
#ifdef FEATURE_BROTLI
#include <brotli/decode.h>
#endif
#if !defined(_WIN32)
#include <unistd.h>
#endif
#include "project.h"
#if defined(FEATURE_PTHREAD) || defined(_WIN32)
#include "jcc.h"
/* jcc.h is for mutex semapores only */
#endif /* def FEATURE_PTHREAD */
#include "list.h"
#include "parsers.h"
#include "ssplit.h"
#include "errlog.h"
#include "jbsockets.h"
#include "miscutil.h"
#include "list.h"
#include "actions.h"
#include "filters.h"
#ifdef FEATURE_HTTPS_INSPECTION
#include "ssl.h"
#endif
#ifndef HAVE_STRPTIME
#include "strptime.h"
#endif
static char *get_header_line(struct iob *iob);
static jb_err scan_headers(struct client_state *csp);
static jb_err header_tagger(struct client_state *csp, char *header);
static jb_err parse_header_time(const char *header_time, time_t *result);
static jb_err parse_time_header(const char *header, time_t *result);
static jb_err crumble (struct client_state *csp, char **header);
static jb_err filter_header (struct client_state *csp, char **header);
static jb_err client_connection (struct client_state *csp, char **header);
static jb_err client_referrer (struct client_state *csp, char **header);
static jb_err client_uagent (struct client_state *csp, char **header);
static jb_err client_ua (struct client_state *csp, char **header);
static jb_err client_from (struct client_state *csp, char **header);
static jb_err client_send_cookie (struct client_state *csp, char **header);
static jb_err client_x_forwarded (struct client_state *csp, char **header);
static jb_err client_accept_encoding (struct client_state *csp, char **header);
static jb_err client_te (struct client_state *csp, char **header);
static jb_err client_max_forwards (struct client_state *csp, char **header);
static jb_err client_host (struct client_state *csp, char **header);
static jb_err client_if_modified_since (struct client_state *csp, char **header);
static jb_err client_accept_language (struct client_state *csp, char **header);
static jb_err client_if_none_match (struct client_state *csp, char **header);
static jb_err crunch_client_header (struct client_state *csp, char **header);
static jb_err client_x_filter (struct client_state *csp, char **header);
static jb_err client_range (struct client_state *csp, char **header);
static jb_err client_expect (struct client_state *csp, char **header);
static jb_err server_set_cookie (struct client_state *csp, char **header);
static jb_err server_connection (struct client_state *csp, char **header);
static jb_err server_content_type (struct client_state *csp, char **header);
static jb_err server_adjust_content_length(struct client_state *csp, char **header);
static jb_err server_content_md5 (struct client_state *csp, char **header);
static jb_err server_content_encoding (struct client_state *csp, char **header);
static jb_err server_transfer_coding (struct client_state *csp, char **header);
static jb_err server_http (struct client_state *csp, char **header);
static jb_err crunch_server_header (struct client_state *csp, char **header);
static jb_err server_last_modified (struct client_state *csp, char **header);
static jb_err server_content_disposition(struct client_state *csp, char **header);
#ifdef FEATURE_ZLIB
static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
#endif
#ifdef FEATURE_CONNECTION_KEEP_ALIVE
static jb_err server_save_content_length(struct client_state *csp, char **header);
static jb_err server_keep_alive(struct client_state *csp, char **header);
static jb_err server_proxy_connection(struct client_state *csp, char **header);
static jb_err client_keep_alive(struct client_state *csp, char **header);
static jb_err client_proxy_connection(struct client_state *csp, char **header);
#endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
static jb_err client_save_content_length(struct client_state *csp, char **header);
static jb_err client_host_adder (struct client_state *csp);
static jb_err client_xtra_adder (struct client_state *csp);
static jb_err client_x_forwarded_for_adder(struct client_state *csp);
static jb_err client_connection_header_adder(struct client_state *csp);
static jb_err server_connection_adder(struct client_state *csp);
#ifdef FEATURE_CONNECTION_KEEP_ALIVE
static jb_err server_proxy_connection_adder(struct client_state *csp);
#endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
static jb_err proxy_authentication(struct client_state *csp, char **header);
#ifdef FEATURE_ADD_REFERER
static jb_err client_referrer_adder (struct client_state *csp);
#endif /* def FEATURE_ADD_REFERER */
static jb_err create_forged_referrer(char **header, const char *hostport, int is_add);
static jb_err create_fake_referrer(char **header, const char *fake_referrer, int is_add);
static jb_err handle_conditional_hide_referrer_parameter(char **header,
const char *host, const int parameter_conditional_block);
#ifdef FEATURE_ADD_REFERER
static jb_err create_forged_referrer2(char **header, const char *url, int is_index, int is_add);
static jb_err create_filtered_referrer(char **header, const char *url, const char *regex, int is_add);
#endif
static void create_content_length_header(unsigned long long content_length,
char *header, size_t buffer_length);
/*
* List of functions to run on a list of headers.
*/
struct parsers
{
/** The header prefix to match */
const char *str;
/** The length of the prefix to match */
const size_t len;
/** The function to apply to this line */
const parser_func_ptr parser;
};
static const struct parsers client_patterns[] = {
{ "referer:", 8, client_referrer },
{ "user-agent:", 11, client_uagent },
{ "ua-", 3, client_ua },
{ "from:", 5, client_from },
{ "cookie:", 7, client_send_cookie },
{ "x-forwarded-for:", 16, client_x_forwarded },
{ "Accept-Encoding:", 16, client_accept_encoding },
{ "TE:", 3, client_te },
{ "Host:", 5, client_host },
{ "if-modified-since:", 18, client_if_modified_since },
{ "Content-Length:", 15, client_save_content_length },
#ifdef FEATURE_CONNECTION_KEEP_ALIVE
{ "Keep-Alive:", 11, client_keep_alive },
{ "Proxy-Connection:", 17, client_proxy_connection },
#else
{ "Keep-Alive:", 11, crumble },
{ "Proxy-Connection:", 17, crumble },
#endif
{ "connection:", 11, client_connection },
{ "max-forwards:", 13, client_max_forwards },
{ "Accept-Language:", 16, client_accept_language },
{ "if-none-match:", 14, client_if_none_match },
{ "Range:", 6, client_range },
{ "Request-Range:", 14, client_range },
{ "If-Range:", 9, client_range },
{ "X-Filter:", 9, client_x_filter },
{ "Proxy-Authorization:", 20, proxy_authentication },
#if 0
{ "Transfer-Encoding:", 18, client_transfer_encoding },
#endif
{ "Expect:", 7, client_expect },
{ "*", 0, crunch_client_header },
{ "*", 0, filter_header },
{ NULL, 0, NULL }
};
static const struct parsers server_patterns[] = {
{ "HTTP/", 5, server_http },
{ "set-cookie:", 11, server_set_cookie },
{ "connection:", 11, server_connection },
{ "Content-Type:", 13, server_content_type },
{ "Content-MD5:", 12, server_content_md5 },
{ "Content-Encoding:", 17, server_content_encoding },
#ifdef FEATURE_CONNECTION_KEEP_ALIVE
{ "Content-Length:", 15, server_save_content_length },
{ "Keep-Alive:", 11, server_keep_alive },
{ "Proxy-Connection:", 17, server_proxy_connection },
#else
{ "Keep-Alive:", 11, crumble },
#endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
{ "Transfer-Encoding:", 18, server_transfer_coding },
{ "content-disposition:", 20, server_content_disposition },
{ "Last-Modified:", 14, server_last_modified },
{ "Proxy-Authenticate:", 19, proxy_authentication },
{ "*", 0, crunch_server_header },
{ "*", 0, filter_header },
{ NULL, 0, NULL }
};
static const add_header_func_ptr add_client_headers[] = {
client_host_adder,
client_x_forwarded_for_adder,
#ifdef FEATURE_ADD_REFERER
client_referrer_adder,
#endif
client_xtra_adder,
client_connection_header_adder,
NULL
};
static const add_header_func_ptr add_server_headers[] = {
server_connection_adder,
#ifdef FEATURE_CONNECTION_KEEP_ALIVE
server_proxy_connection_adder,
#endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
NULL
};
/*********************************************************************
*
* Function : flush_iob
*
* Description : Write any pending "buffered" content.
*
* Parameters :
* 1 : fd = file descriptor of the socket to read
* 2 : iob = The I/O buffer to flush, usually csp->iob.
* 3 : delay = Number of milliseconds to delay the writes
*
* Returns : On success, the number of bytes written are returned (zero
* indicates nothing was written). On error, -1 is returned,
* and errno is set appropriately. If count is zero and the
* file descriptor refers to a regular file, 0 will be
* returned without causing any other effect. For a special
* file, the results are not portable.
*
*********************************************************************/
long flush_iob(jb_socket fd, struct iob *iob, unsigned int delay)
{
long len = iob->eod - iob->cur;
if (len <= 0)
{
return(0);
}
if (write_socket_delayed(fd, iob->cur, (size_t)len, delay))
{
return(-1);
}
iob->eod = iob->cur = iob->buf;
return(len);
}
/*********************************************************************
*
* Function : can_add_to_iob
*
* Description : Checks if the given number of bytes can be added to the given iob
* without exceeding the given buffer limit.
*
* Parameters :
* 1 : iob = Destination buffer.
* 2 : buffer_limit = Limit to which the destination may grow
* 3 : n = number of bytes to be added
*
* Returns : TRUE if the given iob can handle given number of bytes
* FALSE buffer limit will be exceeded
*
*********************************************************************/
int can_add_to_iob(const struct iob *iob, const size_t buffer_limit, size_t n)
{
return ((size_t)(iob->eod - iob->buf) + n + 1) > buffer_limit ? FALSE : TRUE;
}
/*********************************************************************
*
* Function : add_to_iob
*
* Description : Add content to the buffer, expanding the
* buffer if necessary.
*
* Parameters :
* 1 : iob = Destination buffer.
* 2 : buffer_limit = Limit to which the destination may grow
* 3 : src = holds the content to be added
* 4 : n = number of bytes to be added
*
* Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
* or buffer limit reached.
*
*********************************************************************/
jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, const char *src, long n)
{
size_t used, offset, need;
char *p;
if (n <= 0) return JB_ERR_OK;
used = (size_t)(iob->eod - iob->buf);
offset = (size_t)(iob->cur - iob->buf);
need = used + (size_t)n + 1;
/*
* If the buffer can't hold the new data, extend it first.
* Use the next power of two if possible, else use the actual need.
*/
if (need > buffer_limit)
{
log_error(LOG_LEVEL_INFO,
"Buffer limit reached while extending the buffer (iob). Needed: %lu. Limit: %lu",
need, buffer_limit);
return JB_ERR_MEMORY;
}
if (need > iob->size)
{
size_t want = iob->size ? iob->size : 512;
while (want <= need)
{
want *= 2;
}
if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
{
iob->size = want;
}
else if (NULL != (p = (char *)realloc(iob->buf, need)))
{
iob->size = need;
}
else
{
log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
return JB_ERR_MEMORY;
}
/* Update the iob pointers */
iob->cur = p + offset;
iob->eod = p + used;
iob->buf = p;
}
/* copy the new data into the iob buffer */
memcpy(iob->eod, src, (size_t)n);
/* point to the end of the data */
iob->eod += n;
/* null terminate == cheap insurance */
*iob->eod = '\0';
return JB_ERR_OK;
}
/*********************************************************************
*
* Function : clear_iob
*
* Description : Frees the memory allocated for an I/O buffer and
* resets the structure.
*
* Parameters :
* 1 : iob = I/O buffer to clear.
*
* Returns : N/A
*
*********************************************************************/
void clear_iob(struct iob *iob)
{
free(iob->buf);
memset(iob, '\0', sizeof(*iob));
}
#ifdef FEATURE_ZLIB
#ifdef FEATURE_BROTLI
/*********************************************************************
*
* Function : decompress_iob_with_brotli
*
* Description : Decompress buffered page using Brotli.
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
*
* Returns : JB_ERR_OK on success,
* JB_ERR_MEMORY if out-of-memory limit reached, and
* JB_ERR_COMPRESS if error decompressing buffer.
*
*********************************************************************/
static jb_err decompress_iob_with_brotli(struct client_state *csp)
{
BrotliDecoderResult result;
char *decoded_buffer;
size_t decoded_size;
size_t decoded_buffer_size;
size_t encoded_size;
enum { MAX_COMPRESSION_FACTOR = 15 };
encoded_size = (size_t)(csp->iob->eod - csp->iob->cur);
/*
* The BrotliDecoderDecompress() api is a bit unfortunate
* and requires the caller to reserve enough memory for
* the decompressed content. Hopefully reserving
* MAX_COMPRESSION_FACTOR times the original size is
* sufficient. If not, BrotliDecoderDecompress() will fail.
*/
decoded_buffer_size = encoded_size * MAX_COMPRESSION_FACTOR;
if (decoded_buffer_size > csp->config->buffer_limit)
{
log_error(LOG_LEVEL_ERROR,
"Buffer limit reached before decompressing iob with Brotli");
return JB_ERR_MEMORY;
}
decoded_buffer = malloc(decoded_buffer_size);
if (decoded_buffer == NULL)
{
log_error(LOG_LEVEL_ERROR,
"Failed to allocate %lu bytes for Brotli decompression",
decoded_buffer_size);
return JB_ERR_MEMORY;
}
decoded_size = decoded_buffer_size;
result = BrotliDecoderDecompress(encoded_size,
(const uint8_t *)csp->iob->cur, &decoded_size,
(uint8_t *)decoded_buffer);
if (result == BROTLI_DECODER_RESULT_SUCCESS)
{
/*
* Update the iob, since the decompression was successful.
*/
freez(csp->iob->buf);
csp->iob->buf = decoded_buffer;
csp->iob->cur = csp->iob->buf;
csp->iob->eod = csp->iob->cur + decoded_size;
csp->iob->size = decoded_buffer_size;
log_error(LOG_LEVEL_RE_FILTER,
"Decompression successful. Old size: %lu, new size: %lu.",
encoded_size, decoded_size);
return JB_ERR_OK;
}
else
{
log_error(LOG_LEVEL_ERROR, "Failed to decompress buffer with Brotli");
freez(decoded_buffer);
return JB_ERR_COMPRESS;
}
}
#endif
/*********************************************************************
*
* Function : decompress_iob
*
* Description : Decompress buffered page, expanding the
* buffer as necessary. csp->iob->cur
* should point to the the beginning of the
* compressed data block.
*
* Parameters :
* 1 : csp = Current client state (buffers, headers, etc...)
*
* Returns : JB_ERR_OK on success,
* JB_ERR_MEMORY if out-of-memory limit reached, and
* JB_ERR_COMPRESS if error decompressing buffer.
*
*********************************************************************/
jb_err decompress_iob(struct client_state *csp)
{
char *buf; /* new, uncompressed buffer */
char *cur; /* Current iob position (to keep the original
* iob->cur unmodified if we return early) */
size_t bufsize; /* allocated size of the new buffer */
size_t old_size; /* Content size before decompression */
size_t skip_size; /* Number of bytes at the beginning of the iob
that we should NOT decompress. */
int status; /* return status of the inflate() call */
z_stream zstr; /* used by calls to zlib */
#ifdef FUZZ
assert(csp->iob->cur - csp->iob->buf >= 0);
assert(csp->iob->eod - csp->iob->cur >= 0);
#else
assert(csp->iob->cur - csp->iob->buf > 0);
assert(csp->iob->eod - csp->iob->cur > 0);
#endif
bufsize = csp->iob->size;
skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
old_size = (size_t)(csp->iob->eod - csp->iob->cur);
cur = csp->iob->cur;
if (old_size < (size_t)10)
{
/*
* This is to protect the parsing of gzipped data,
* but it should(?) be valid for deflated data also.
*/
log_error(LOG_LEVEL_ERROR,
"Insufficient data to start decompression. Bytes in buffer: %ld",
csp->iob->eod - csp->iob->cur);
return JB_ERR_COMPRESS;
}
#ifdef FEATURE_BROTLI
if (csp->content_type & CT_BROTLI)
{
return decompress_iob_with_brotli(csp);
}
#endif
if (csp->content_type & CT_GZIP)
{
/*
* Our task is slightly complicated by the facts that data
* compressed by gzip does not include a zlib header, and
* that there is no easily accessible interface in zlib to
* handle a gzip header. We strip off the gzip header by
* hand, and later inform zlib not to expect a header.
*/
/*
* Strip off the gzip header. Please see RFC 1952 for more
* explanation of the appropriate fields.
*/
if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
|| ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
|| (*cur++ != Z_DEFLATED))
{
log_error(LOG_LEVEL_ERROR,
"Invalid gzip header when decompressing.");
return JB_ERR_COMPRESS;
}
else
{
int flags = *cur++;
if (flags & GZIP_FLAG_RESERVED_BITS)
{
/* The gzip header has reserved bits set; bail out. */
log_error(LOG_LEVEL_ERROR,
"Invalid gzip header flags when decompressing.");
return JB_ERR_COMPRESS;
}
/*
* Skip mtime (4 bytes), extra flags (1 byte)
* and OS type (1 byte).
*/
cur += 6;
/* Skip extra fields if necessary. */
if (flags & GZIP_FLAG_EXTRA_FIELDS)
{
/*
* Skip a given number of bytes, specified
* as a 16-bit little-endian value.
*
* XXX: this code is untested and should probably be removed.
*/
int skip_bytes;
if (cur + 2 >= csp->iob->eod)
{
log_error(LOG_LEVEL_ERROR,
"gzip extra field flag set but insufficient data available.");
return JB_ERR_COMPRESS;
}
skip_bytes = *cur++;
skip_bytes += (unsigned char)*cur++ << 8;
/*
* The number of bytes to skip should be positive
* and we'd like to stay in the buffer.
*/
if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
{
log_error(LOG_LEVEL_ERROR,
"Unreasonable amount of bytes to skip (%d). "
"Stopping decompression.",
skip_bytes);
return JB_ERR_COMPRESS;
}
log_error(LOG_LEVEL_INFO,
"Skipping %d bytes for gzip compression. "
"Does this sound right?",
skip_bytes);
cur += skip_bytes;
}
/* Skip the filename if necessary. */
if (flags & GZIP_FLAG_FILE_NAME)
{
/* A null-terminated string is supposed to follow. */
while ((cur < csp->iob->eod) && *cur++);
}
/* Skip the comment if necessary. */
if (flags & GZIP_FLAG_COMMENT)
{
/* A null-terminated string is supposed to follow. */
while ((cur < csp->iob->eod) && *cur++);
}
/* Skip the CRC if necessary. */
if (flags & GZIP_FLAG_CHECKSUM)
{
cur += 2;
}
if (cur >= csp->iob->eod)
{
/*
* If the current position pointer reached or passed
* the buffer end, we were obviously tricked to skip
* too much.
*/
log_error(LOG_LEVEL_ERROR,
"Malformed gzip header detected. Aborting decompression.");
return JB_ERR_COMPRESS;
}
}
}
else if (csp->content_type & CT_DEFLATE)
{
/*
* In theory (that is, according to RFC 1950), deflate-compressed
* data should begin with a two-byte zlib header and have an
* adler32 checksum at the end. It seems that in practice only
* the raw compressed data is sent. Note that this means that
* we are not RFC 1950-compliant here, but the advantage is that
* this actually works. :)
*
* We add a dummy null byte to tell zlib where the data ends,
* and later inform it not to expect a header.
*
* Fortunately, add_to_iob() has thoughtfully null-terminated
* the buffer; we can just increment the end pointer to include
* the dummy byte.
*/
csp->iob->eod++;
}
else
{
log_error(LOG_LEVEL_ERROR,
"Unable to determine compression format for decompression.");
return JB_ERR_COMPRESS;
}
/* Set up the fields required by zlib. */
zstr.next_in = (Bytef *)cur;
zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
zstr.zalloc = Z_NULL;
zstr.zfree = Z_NULL;
zstr.opaque = Z_NULL;
/*
* Passing -MAX_WBITS to inflateInit2 tells the library
* that there is no zlib header.
*/
if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
{
log_error(LOG_LEVEL_ERROR, "Error initializing decompression.");
return JB_ERR_COMPRESS;
}
/*
* Next, we allocate new storage for the inflated data.
* We don't modify the existing iob yet, so in case there
* is an error in decompression we can recover gracefully.
*/
buf = zalloc(bufsize);
if (NULL == buf)
{
log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob.");
return JB_ERR_MEMORY;
}
assert(bufsize >= skip_size);
memcpy(buf, csp->iob->buf, skip_size);
zstr.avail_out = (uInt)(bufsize - skip_size);
zstr.next_out = (Bytef *)buf + skip_size;
/* Try to decompress the whole stream in one shot. */
while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
{
/* We need to allocate more memory for the output buffer. */
char *tmpbuf; /* used for realloc'ing the buffer */
size_t oldbufsize = bufsize; /* keep track of the old bufsize */
if (0 == zstr.avail_in)
{
/*
* If zlib wants more data then there's a problem, because
* the complete compressed file should have been buffered.
*/
log_error(LOG_LEVEL_ERROR,
"Unexpected end of compressed iob. Using what we got so far.");
break;
}
/*
* If we reached the buffer limit and still didn't have enough
* memory, just give up. Due to the ceiling enforced by the next
* if block we could actually check for equality here, but as it
* can be easily mistaken for a bug we don't.
*/
if (bufsize >= csp->config->buffer_limit)
{
log_error(LOG_LEVEL_ERROR,
"Buffer limit reached while decompressing iob.");
freez(buf);
inflateEnd(&zstr);
return JB_ERR_MEMORY;
}
/* Try doubling the buffer size each time. */
bufsize *= 2;
/* Don't exceed the buffer limit. */
if (bufsize > csp->config->buffer_limit)
{
bufsize = csp->config->buffer_limit;
}
/* Try to allocate the new buffer. */
tmpbuf = realloc(buf, bufsize);
if (NULL == tmpbuf)
{
log_error(LOG_LEVEL_ERROR,
"Out of memory decompressing iob.");
freez(buf);
inflateEnd(&zstr);
return JB_ERR_MEMORY;
}
else
{
#ifndef NDEBUG
char *oldnext_out = (char *)zstr.next_out;
#endif
/*
* Update the fields for inflate() to use the new
* buffer, which may be in a location different from
* the old one.
*/
zstr.avail_out += (uInt)(bufsize - oldbufsize);
zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
/*
* Compare with an uglier method of calculating these values
* that doesn't require the extra oldbufsize variable.
*/
assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
buf = tmpbuf;
}
}
if (Z_STREAM_ERROR == inflateEnd(&zstr))
{
log_error(LOG_LEVEL_ERROR,
"Inconsistent stream state after decompression: %s", zstr.msg);
/*
* XXX: Intentionally no return.
*
* According to zlib.h, Z_STREAM_ERROR is returned
* "if the stream state was inconsistent".
*
* I assume in this case inflate()'s status
* would also be something different than Z_STREAM_END
* so this check should be redundant, but lets see.
*/
}
if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
{
/*
* We failed to decompress the stream and it's
* not simply because of missing data.
*/
log_error(LOG_LEVEL_ERROR,
"Unexpected error while decompressing to the buffer (iob): %s",
zstr.msg);
freez(buf);
return JB_ERR_COMPRESS;
}
/*
* Finally, we can actually update the iob, since the
* decompression was successful. First, free the old
* buffer.
*/
freez(csp->iob->buf);
/* Now, update the iob to use the new buffer. */
csp->iob->buf = buf;
csp->iob->cur = csp->iob->buf + skip_size;
csp->iob->eod = (char *)zstr.next_out;
csp->iob->size = bufsize;
/*
* Make sure the new uncompressed iob obeys some minimal
* consistency conditions.
*/
if ((csp->iob->buf <= csp->iob->cur)
&& (csp->iob->cur <= csp->iob->eod)
&& (csp->iob->eod <= csp->iob->buf + csp->iob->size))
{
const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
if (new_size > (size_t)0)
{
log_error(LOG_LEVEL_RE_FILTER,
"Decompression successful. Old size: %lu, new size: %lu.",
old_size, new_size);
}
else
{
/* zlib thinks this is OK, so let's do the same. */
log_error(LOG_LEVEL_RE_FILTER,
"Decompression didn't result in any content.");
}
}
else
{
/* It seems that zlib did something weird. */
log_error(LOG_LEVEL_ERROR,
"Inconsistent buffer after decompression.");
return JB_ERR_COMPRESS;
}
return JB_ERR_OK;
}
#endif /* defined(FEATURE_ZLIB) */
/*********************************************************************
*
* Function : normalize_lws
*
* Description : Reduces unquoted linear whitespace in headers to
* a single space in accordance with RFC 7230 3.2.4.
* This simplifies parsing and filtering later on.
*
* Parameters :
* 1 : header = A header with linear whitespace to reduce.
*
* Returns : N/A
*
*********************************************************************/
static void normalize_lws(char *header)
{
char *p = header;
while (*p != '\0')
{
if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
{
char *q = p+1;
while (privoxy_isspace(*q))
{
q++;
}
log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
string_move(p+1, q);
}
if (*p == '\t')
{
log_error(LOG_LEVEL_HEADER,
"Converting tab to space in '%s'", header);
*p = ' ';
}
else if (*p == '"')
{
char *end_of_token = strstr(p+1, "\"");
if (NULL != end_of_token)
{
/* Don't mess with quoted text. */
p = end_of_token;
}
else
{
log_error(LOG_LEVEL_HEADER,
"Ignoring single quote in '%s'", header);
}
}
p++;
}
p = strchr(header, ':');
if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
{
/*
* There's still space before the colon.
* We don't want it.
*/
string_move(p-1, p);
}
}
/*********************************************************************
*
* Function : get_header
*
* Description : This (odd) routine will parse the csp->iob
* to get the next complete header.
*
* Parameters :
* 1 : iob = The I/O buffer to parse, usually csp->iob.
*
* Returns : Any one of the following:
*
* 1) a pointer to a dynamically allocated string that contains a header line
* 2) NULL indicating that the end of the header was reached
* 3) "" indicating that the end of the iob was reached before finding
* a complete header line.
*
*********************************************************************/
char *get_header(struct iob *iob)
{
char *header;
header = get_header_line(iob);
if ((header == NULL) || (*header == '\0'))
{
/*
* No complete header read yet, tell the client.
*/
return header;
}
while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
{