File: php_http_encoding.c

package info (click to toggle)
php-pecl-http 2.0.4-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,436 kB
  • ctags: 1,839
  • sloc: ansic: 15,322; php: 726; xml: 254; makefile: 10; pascal: 3
file content (1228 lines) | stat: -rw-r--r-- 37,243 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
/*
    +--------------------------------------------------------------------+
    | PECL :: http                                                       |
    +--------------------------------------------------------------------+
    | Redistribution and use in source and binary forms, with or without |
    | modification, are permitted provided that the conditions mentioned |
    | in the accompanying LICENSE file are met.                          |
    +--------------------------------------------------------------------+
    | Copyright (c) 2004-2014, Michael Wallner <mike@php.net>            |
    +--------------------------------------------------------------------+
*/

#include "php_http_api.h"

#include <zlib.h>

static inline int eol_match(char **line, int *eol_len)
{
	char *ptr = *line;
	
	while (' ' == *ptr) ++ptr;

	if (ptr == php_http_locate_eol(*line, eol_len)) {
		*line = ptr;
		return 1;
	} else {
		return 0;
	}
}

const char *php_http_encoding_dechunk(const char *encoded, size_t encoded_len, char **decoded, size_t *decoded_len TSRMLS_DC)
{
	int eol_len = 0;
	char *n_ptr = NULL;
	const char *e_ptr = encoded;
	
	*decoded_len = 0;
	*decoded = ecalloc(1, encoded_len + 1);

	while ((encoded + encoded_len - e_ptr) > 0) {
		ulong chunk_len = 0, rest;

		chunk_len = strtoul(e_ptr, &n_ptr, 16);

		/* we could not read in chunk size */
		if (n_ptr == e_ptr) {
			/*
			 * if this is the first turn and there doesn't seem to be a chunk
			 * size at the begining of the body, do not fail on apparently
			 * not encoded data and return a copy
			 */
			if (e_ptr == encoded) {
				php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Data does not seem to be chunked encoded");
				memcpy(*decoded, encoded, encoded_len);
				*decoded_len = encoded_len;
				decoded[*decoded_len] = '\0';
				return encoded + encoded_len;
			} else {
				efree(*decoded);
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expected chunk size at pos %tu of %zu but got trash", n_ptr - encoded, encoded_len);
				return NULL;
			}
		}
		
		/* reached the end */
		if (!chunk_len) {
			/* move over '0' chunked encoding terminator and any new lines */
			do {
				switch (*e_ptr) {
					case '0':
					case '\r':
					case '\n':
						++e_ptr;
						continue;
				}
			} while (0);
			break;
		}

		/* there should be CRLF after the chunk size, but we'll ignore SP+ too */
		if (*n_ptr && !eol_match(&n_ptr, &eol_len)) {
			if (eol_len == 2) {
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expected CRLF at pos %tu of %zu but got 0x%02X 0x%02X", n_ptr - encoded, encoded_len, *n_ptr, *(n_ptr + 1));
			} else {
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expected LF at pos %tu of %zu but got 0x%02X", n_ptr - encoded, encoded_len, *n_ptr);
			}
		}
		n_ptr += eol_len;
		
		/* chunk size pretends more data than we actually got, so it's probably a truncated message */
		if (chunk_len > (rest = encoded + encoded_len - n_ptr)) {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "Truncated message: chunk size %lu exceeds remaining data size %lu at pos %tu of %zu", chunk_len, rest, n_ptr - encoded, encoded_len);
			chunk_len = rest;
		}

		/* copy the chunk */
		memcpy(*decoded + *decoded_len, n_ptr, chunk_len);
		*decoded_len += chunk_len;
		
		if (chunk_len == rest) {
			e_ptr = n_ptr + chunk_len;
			break;
		} else {
			/* advance to next chunk */
			e_ptr = n_ptr + chunk_len + eol_len;
		}
	}

	return e_ptr;
}

static inline int php_http_inflate_rounds(z_stream *Z, int flush, char **buf, size_t *len)
{
	int status = 0, round = 0;
	php_http_buffer_t buffer;
	
	*buf = NULL;
	*len = 0;
	
	php_http_buffer_init_ex(&buffer, Z->avail_in, PHP_HTTP_BUFFER_INIT_PREALLOC);
	
	do {
		if (PHP_HTTP_BUFFER_NOMEM == php_http_buffer_resize_ex(&buffer, buffer.size, 0, 1)) {
			status = Z_MEM_ERROR;
		} else {
			Z->avail_out = buffer.free;
			Z->next_out = (Bytef *) buffer.data + buffer.used;
#if 0
			fprintf(stderr, "\n%3d: %3d PRIOR: size=%7lu,\tfree=%7lu,\tused=%7lu,\tavail_in=%7lu,\tavail_out=%7lu\n", round, status, buffer.size, buffer.free, buffer.used, Z->avail_in, Z->avail_out);
#endif
			status = inflate(Z, flush);
			php_http_buffer_account(&buffer, buffer.free - Z->avail_out);
#if 0
			fprintf(stderr, "%3d: %3d AFTER: size=%7lu,\tfree=%7lu,\tused=%7lu,\tavail_in=%7lu,\tavail_out=%7lu\n", round, status, buffer.size, buffer.free, buffer.used, Z->avail_in, Z->avail_out);
#endif
			PHP_HTTP_INFLATE_BUFFER_SIZE_ALIGN(buffer.size);
		}
	} while ((Z_BUF_ERROR == status || (Z_OK == status && Z->avail_in)) && ++round < PHP_HTTP_INFLATE_ROUNDS);
	
	if (status == Z_OK || status == Z_STREAM_END) {
		php_http_buffer_shrink(&buffer);
		php_http_buffer_fix(&buffer);
		*buf = buffer.data;
		*len = buffer.used;
	} else {
		php_http_buffer_dtor(&buffer);
	}
	
	return status;
}

STATUS php_http_encoding_deflate(int flags, const char *data, size_t data_len, char **encoded, size_t *encoded_len TSRMLS_DC)
{
	int status, level, wbits, strategy;
	z_stream Z;
	
	PHP_HTTP_DEFLATE_LEVEL_SET(flags, level);
	PHP_HTTP_DEFLATE_WBITS_SET(flags, wbits);
	PHP_HTTP_DEFLATE_STRATEGY_SET(flags, strategy);
	
	memset(&Z, 0, sizeof(z_stream));
	*encoded = NULL;
	*encoded_len = 0;
	
	status = deflateInit2(&Z, level, Z_DEFLATED, wbits, MAX_MEM_LEVEL, strategy);
	if (Z_OK == status) {
		*encoded_len = PHP_HTTP_DEFLATE_BUFFER_SIZE_GUESS(data_len);
		*encoded = emalloc(*encoded_len);
		
		Z.next_in = (Bytef *) data;
		Z.next_out = (Bytef *) *encoded;
		Z.avail_in = data_len;
		Z.avail_out = *encoded_len;
		
		status = deflate(&Z, Z_FINISH);
		deflateEnd(&Z);
		
		if (Z_STREAM_END == status) {
			/* size buffer down to actual length */
			*encoded = erealloc(*encoded, Z.total_out + 1);
			(*encoded)[*encoded_len = Z.total_out] = '\0';
			return SUCCESS;
		} else {
			STR_SET(*encoded, NULL);
			*encoded_len = 0;
		}
	}
	
	php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not deflate data: %s", zError(status));
	return FAILURE;
}

STATUS php_http_encoding_inflate(const char *data, size_t data_len, char **decoded, size_t *decoded_len TSRMLS_DC)
{
	z_stream Z;
	int status, wbits = PHP_HTTP_WINDOW_BITS_ANY;
	
	memset(&Z, 0, sizeof(z_stream));
	
retry_raw_inflate:
	status = inflateInit2(&Z, wbits);
	if (Z_OK == status) {
		Z.next_in = (Bytef *) data;
		Z.avail_in = data_len + 1; /* include the terminating NULL, see #61287 */
		
		switch (status = php_http_inflate_rounds(&Z, Z_NO_FLUSH, decoded, decoded_len)) {
			case Z_STREAM_END:
				inflateEnd(&Z);
				return SUCCESS;

			case Z_OK:
				status = Z_DATA_ERROR;
				break;
			
			case Z_DATA_ERROR:
				/* raw deflated data? */
				if (PHP_HTTP_WINDOW_BITS_ANY == wbits) {
					inflateEnd(&Z);
					wbits = PHP_HTTP_WINDOW_BITS_RAW;
					goto retry_raw_inflate;
				}
				break;
		}
		inflateEnd(&Z);

		if (decoded_len && *decoded) {
			efree(*decoded);
		}
	}
	
	php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not inflate data: %s", zError(status));
	return FAILURE;
}

php_http_encoding_stream_t *php_http_encoding_stream_init(php_http_encoding_stream_t *s, php_http_encoding_stream_ops_t *ops, unsigned flags TSRMLS_DC)
{
	int freeme;

	if ((freeme = !s)) {
		s = pemalloc(sizeof(*s), (flags & PHP_HTTP_ENCODING_STREAM_PERSISTENT));
	}
	memset(s, 0, sizeof(*s));

	s->flags = flags;
	TSRMLS_SET_CTX(s->ts);

	if ((s->ops = ops)) {
		php_http_encoding_stream_t *ss = s->ops->init(s);

		if (ss) {
			return ss;
		}
	} else {
		return s;
	}

	if (freeme) {
		pefree(s, (flags & PHP_HTTP_ENCODING_STREAM_PERSISTENT));
	}
	return NULL;
}

php_http_encoding_stream_t *php_http_encoding_stream_copy(php_http_encoding_stream_t *from, php_http_encoding_stream_t *to)
{
	TSRMLS_FETCH_FROM_CTX(from->ts);

	if (from->ops->copy) {
		int freeme;
		php_http_encoding_stream_t *ns;

		if ((freeme = !to)) {
			to = pemalloc(sizeof(*to), (from->flags & PHP_HTTP_ENCODING_STREAM_PERSISTENT));
		}
		memset(to, 0, sizeof(*to));

		to->flags = from->flags;
		to->ops = from->ops;
		TSRMLS_SET_CTX(to->ts);

		if ((ns = to->ops->copy(from, to))) {
			return ns;
		} else {
			return to;
		}

		if (freeme) {
			pefree(to, (to->flags & PHP_HTTP_ENCODING_STREAM_PERSISTENT));
		}
	}

	return NULL;
}

STATUS php_http_encoding_stream_reset(php_http_encoding_stream_t **s)
{
	php_http_encoding_stream_t *ss;
	if ((*s)->ops->dtor) {
		(*s)->ops->dtor(*s);
	}
	if ((ss = (*s)->ops->init(*s))) {
		*s = ss;
		return SUCCESS;
	}
	return FAILURE;
}

STATUS php_http_encoding_stream_update(php_http_encoding_stream_t *s, const char *in_str, size_t in_len, char **out_str, size_t *out_len)
{
	if (!s->ops->update) {
		return FAILURE;
	}
	return s->ops->update(s, in_str, in_len, out_str, out_len);
}

STATUS php_http_encoding_stream_flush(php_http_encoding_stream_t *s, char **out_str, size_t *out_len)
{
	if (!s->ops->flush) {
		*out_str = NULL;
		*out_len = 0;
		return SUCCESS;
	}
	return s->ops->flush(s, out_str, out_len);
}

zend_bool php_http_encoding_stream_done(php_http_encoding_stream_t *s)
{
	if (!s->ops->done) {
		return 0;
	}
	return s->ops->done(s);
}

STATUS php_http_encoding_stream_finish(php_http_encoding_stream_t *s, char **out_str, size_t *out_len)
{
	if (!s->ops->finish) {
		*out_str = NULL;
		*out_len = 0;
		return SUCCESS;
	}
	return s->ops->finish(s, out_str, out_len);
}

void php_http_encoding_stream_dtor(php_http_encoding_stream_t *s)
{
	if (s->ops->dtor) {
		s->ops->dtor(s);
	}
}

void php_http_encoding_stream_free(php_http_encoding_stream_t **s)
{
	if (*s) {
		if ((*s)->ops->dtor) {
			(*s)->ops->dtor(*s);
		}
		pefree(*s, ((*s)->flags & PHP_HTTP_ENCODING_STREAM_PERSISTENT));
		*s = NULL;
	}
}

struct dechunk_ctx {
	php_http_buffer_t buffer;
	ulong hexlen;
	unsigned zeroed:1;
};

static php_http_encoding_stream_t *deflate_init(php_http_encoding_stream_t *s)
{
	int status, level, wbits, strategy, p = (s->flags & PHP_HTTP_ENCODING_STREAM_PERSISTENT);
	z_streamp ctx = pecalloc(1, sizeof(z_stream), p);
	TSRMLS_FETCH_FROM_CTX(s->ts);
	
	PHP_HTTP_DEFLATE_LEVEL_SET(s->flags, level);
	PHP_HTTP_DEFLATE_WBITS_SET(s->flags, wbits);
	PHP_HTTP_DEFLATE_STRATEGY_SET(s->flags, strategy);
	
	if (Z_OK == (status = deflateInit2(ctx, level, Z_DEFLATED, wbits, MAX_MEM_LEVEL, strategy))) {
		if ((ctx->opaque = php_http_buffer_init_ex(NULL, PHP_HTTP_DEFLATE_BUFFER_SIZE, p ? PHP_HTTP_BUFFER_INIT_PERSISTENT : 0))) {
			s->ctx = ctx;
			return s;
		}
		deflateEnd(ctx);
		status = Z_MEM_ERROR;
	}
	pefree(ctx, p);
	php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to initialize deflate encoding stream: %s", zError(status));
	return NULL;
}

static php_http_encoding_stream_t *inflate_init(php_http_encoding_stream_t *s)
{
	int status, wbits, p = (s->flags & PHP_HTTP_ENCODING_STREAM_PERSISTENT);
	z_streamp ctx = pecalloc(1, sizeof(z_stream), p);
	TSRMLS_FETCH_FROM_CTX(s->ts);
	
	PHP_HTTP_INFLATE_WBITS_SET(s->flags, wbits);
	
	if (Z_OK == (status = inflateInit2(ctx, wbits))) {
		if ((ctx->opaque = php_http_buffer_init_ex(NULL, PHP_HTTP_DEFLATE_BUFFER_SIZE, p ? PHP_HTTP_BUFFER_INIT_PERSISTENT : 0))) {
			s->ctx = ctx;
			return s;
		}
		inflateEnd(ctx);
		status = Z_MEM_ERROR;
	}
	pefree(ctx, p);
	php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to initialize inflate stream: %s", zError(status));
	return NULL;
}

static php_http_encoding_stream_t *dechunk_init(php_http_encoding_stream_t *s)
{
	struct dechunk_ctx *ctx = pecalloc(1, sizeof(*ctx), (s->flags & PHP_HTTP_ENCODING_STREAM_PERSISTENT));

	if (!php_http_buffer_init_ex(&ctx->buffer, PHP_HTTP_BUFFER_DEFAULT_SIZE, (s->flags & PHP_HTTP_ENCODING_STREAM_PERSISTENT) ? PHP_HTTP_BUFFER_INIT_PERSISTENT : 0)) {
		return NULL;
	}

	ctx->hexlen = 0;
	ctx->zeroed = 0;
	s->ctx = ctx;

	return s;
}

static php_http_encoding_stream_t *deflate_copy(php_http_encoding_stream_t *from, php_http_encoding_stream_t *to)
{
	int status, p = to->flags & PHP_HTTP_ENCODING_STREAM_PERSISTENT;
	z_streamp from_ctx = from->ctx, to_ctx = pecalloc(1, sizeof(*to_ctx), p);
	TSRMLS_FETCH_FROM_CTX(from->ts);

	if (Z_OK == (status = deflateCopy(to_ctx, from_ctx))) {
		if ((to_ctx->opaque = php_http_buffer_init_ex(NULL, PHP_HTTP_DEFLATE_BUFFER_SIZE, p ? PHP_HTTP_BUFFER_INIT_PERSISTENT : 0))) {
			php_http_buffer_append(to_ctx->opaque, PHP_HTTP_BUFFER(from_ctx->opaque)->data, PHP_HTTP_BUFFER(from_ctx->opaque)->used);
			to->ctx = to_ctx;
			return to;
		}
		deflateEnd(to_ctx);
		status = Z_MEM_ERROR;
	}
	php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to copy deflate encoding stream: %s", zError(status));
	return NULL;
}

static php_http_encoding_stream_t *inflate_copy(php_http_encoding_stream_t *from, php_http_encoding_stream_t *to)
{
	int status, p = from->flags & PHP_HTTP_ENCODING_STREAM_PERSISTENT;
	z_streamp from_ctx = from->ctx, to_ctx = pecalloc(1, sizeof(*to_ctx), p);
	TSRMLS_FETCH_FROM_CTX(from->ts);

	if (Z_OK == (status = inflateCopy(to_ctx, from_ctx))) {
		if ((to_ctx->opaque = php_http_buffer_init_ex(NULL, PHP_HTTP_DEFLATE_BUFFER_SIZE, p ? PHP_HTTP_BUFFER_INIT_PERSISTENT : 0))) {
			php_http_buffer_append(to_ctx->opaque, PHP_HTTP_BUFFER(from_ctx->opaque)->data, PHP_HTTP_BUFFER(from_ctx->opaque)->used);
			to->ctx = to_ctx;
			return to;
		}
		inflateEnd(to_ctx);
		status = Z_MEM_ERROR;
	}
	php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to copy inflate encoding stream: %s", zError(status));
	return NULL;
}

static php_http_encoding_stream_t *dechunk_copy(php_http_encoding_stream_t *from, php_http_encoding_stream_t *to)
{
	int p = from->flags & PHP_HTTP_ENCODING_STREAM_PERSISTENT;
	struct dechunk_ctx *from_ctx = from->ctx, *to_ctx = pemalloc(sizeof(*to_ctx), p);
	TSRMLS_FETCH_FROM_CTX(from->ts);

	if (php_http_buffer_init_ex(&to_ctx->buffer, PHP_HTTP_BUFFER_DEFAULT_SIZE, p ? PHP_HTTP_BUFFER_INIT_PERSISTENT : 0)) {
		to_ctx->hexlen = from_ctx->hexlen;
		to_ctx->zeroed = from_ctx->zeroed;
		php_http_buffer_append(&to_ctx->buffer, from_ctx->buffer.data, from_ctx->buffer.used);
		to->ctx = to_ctx;
		return to;
	}
	pefree(to_ctx, p);
	php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to copy inflate encoding stream: out of memory");
	return NULL;
}

static STATUS deflate_update(php_http_encoding_stream_t *s, const char *data, size_t data_len, char **encoded, size_t *encoded_len)
{
	int status;
	z_streamp ctx = s->ctx;
	TSRMLS_FETCH_FROM_CTX(s->ts);
	
	/* append input to our buffer */
	php_http_buffer_append(PHP_HTTP_BUFFER(ctx->opaque), data, data_len);
	
	ctx->next_in = (Bytef *) PHP_HTTP_BUFFER(ctx->opaque)->data;
	ctx->avail_in = PHP_HTTP_BUFFER(ctx->opaque)->used;
	
	/* deflate */
	*encoded_len = PHP_HTTP_DEFLATE_BUFFER_SIZE_GUESS(data_len);
	*encoded = emalloc(*encoded_len);
	ctx->avail_out = *encoded_len;
	ctx->next_out = (Bytef *) *encoded;
	
	switch (status = deflate(ctx, PHP_HTTP_ENCODING_STREAM_FLUSH_FLAG(s->flags))) {
		case Z_OK:
		case Z_STREAM_END:
			/* cut processed chunk off the buffer */
			if (ctx->avail_in) {
				php_http_buffer_cut(PHP_HTTP_BUFFER(ctx->opaque), 0, PHP_HTTP_BUFFER(ctx->opaque)->used - ctx->avail_in);
			} else {
				php_http_buffer_reset(PHP_HTTP_BUFFER(ctx->opaque));
			}
			
			/* size buffer down to actual size */
			*encoded_len -= ctx->avail_out;
			*encoded = erealloc(*encoded, *encoded_len + 1);
			(*encoded)[*encoded_len] = '\0';
			return SUCCESS;
	}
	
	STR_SET(*encoded, NULL);
	*encoded_len = 0;
	php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to update deflate stream: %s", zError(status));
	return FAILURE;
}

static STATUS inflate_update(php_http_encoding_stream_t *s, const char *data, size_t data_len, char **decoded, size_t *decoded_len)
{
	int status;
	z_streamp ctx = s->ctx;
	TSRMLS_FETCH_FROM_CTX(s->ts);
	
	/* append input to buffer */
	php_http_buffer_append(PHP_HTTP_BUFFER(ctx->opaque), data, data_len);

retry_raw_inflate:
	ctx->next_in = (Bytef *) PHP_HTTP_BUFFER(ctx->opaque)->data;
	ctx->avail_in = PHP_HTTP_BUFFER(ctx->opaque)->used;
	
	switch (status = php_http_inflate_rounds(ctx, PHP_HTTP_ENCODING_STREAM_FLUSH_FLAG(s->flags), decoded, decoded_len)) {
		case Z_OK:
		case Z_STREAM_END:
			/* cut off */
			if (ctx->avail_in) {
				php_http_buffer_cut(PHP_HTTP_BUFFER(ctx->opaque), 0, PHP_HTTP_BUFFER(ctx->opaque)->used - ctx->avail_in);
			} else {
				php_http_buffer_reset(PHP_HTTP_BUFFER(ctx->opaque));
			}
			return SUCCESS;
		
		case Z_DATA_ERROR:
			/* raw deflated data ? */
			if (!(s->flags & PHP_HTTP_INFLATE_TYPE_RAW) && !ctx->total_out) {
				inflateEnd(ctx);
				s->flags |= PHP_HTTP_INFLATE_TYPE_RAW;
				inflateInit2(ctx, PHP_HTTP_WINDOW_BITS_RAW);
				goto retry_raw_inflate;
			}
			break;
	}
	
	php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to update inflate stream: %s", zError(status));
	return FAILURE;
}

static STATUS dechunk_update(php_http_encoding_stream_t *s, const char *data, size_t data_len, char **decoded, size_t *decoded_len)
{
	php_http_buffer_t tmp;
	struct dechunk_ctx *ctx = s->ctx;
	TSRMLS_FETCH_FROM_CTX(s->ts);

	if (ctx->zeroed) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Dechunk encoding stream has already reached the end of chunked input");
		return FAILURE;
	}
	if ((PHP_HTTP_BUFFER_NOMEM == php_http_buffer_append(&ctx->buffer, data, data_len)) || !php_http_buffer_fix(&ctx->buffer)) {
		/* OOM */
		return FAILURE;
	}

	*decoded = NULL;
	*decoded_len = 0;

	php_http_buffer_init(&tmp);

	/* we have data in our buffer */
	while (ctx->buffer.used) {

		/* we already know the size of the chunk and are waiting for data */
		if (ctx->hexlen) {

			/* not enough data buffered */
			if (ctx->buffer.used < ctx->hexlen) {

				/* flush anyway? */
				if (s->flags & PHP_HTTP_ENCODING_STREAM_FLUSH_FULL) {
					/* flush all data (should only be chunk data) */
					php_http_buffer_append(&tmp, ctx->buffer.data, ctx->buffer.used);
					/* waiting for less data now */
					ctx->hexlen -= ctx->buffer.used;
					/* no more buffered data */
					php_http_buffer_reset(&ctx->buffer);
					/* break */
				}

				/* we have too less data and don't need to flush */
				else {
					break;
				}
			}

			/* we seem to have all data of the chunk */
			else {
				php_http_buffer_append(&tmp, ctx->buffer.data, ctx->hexlen);
				/* remove outgoing data from the buffer */
				php_http_buffer_cut(&ctx->buffer, 0, ctx->hexlen);
				/* reset hexlen */
				ctx->hexlen = 0;
				/* continue */
			}
		}

		/* we don't know the length of the chunk yet */
		else {
			size_t off = 0;

			/* ignore preceeding CRLFs (too loose?) */
			while (off < ctx->buffer.used && (
					ctx->buffer.data[off] == '\n' ||
					ctx->buffer.data[off] == '\r')) {
				++off;
			}
			if (off) {
				php_http_buffer_cut(&ctx->buffer, 0, off);
			}

			/* still data there? */
			if (ctx->buffer.used) {
				int eollen;
				const char *eolstr;

				/* we need eol, so we can be sure we have all hex digits */
				php_http_buffer_fix(&ctx->buffer);
				if ((eolstr = php_http_locate_bin_eol(ctx->buffer.data, ctx->buffer.used, &eollen))) {
					char *stop = NULL;

					/* read in chunk size */
					ctx->hexlen = strtoul(ctx->buffer.data, &stop, 16);

					/*	if strtoul() stops at the beginning of the buffered data
						there's something oddly wrong, i.e. bad input */
					if (stop == ctx->buffer.data) {
						php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse chunk len from '%.*s'", (int) MIN(16, ctx->buffer.used), ctx->buffer.data);
						php_http_buffer_dtor(&tmp);
						return FAILURE;
					}

					/* cut out <chunk size hex><chunk extension><eol> */
					php_http_buffer_cut(&ctx->buffer, 0, eolstr + eollen - ctx->buffer.data);
					/* buffer->hexlen is 0 now or contains the size of the next chunk */
					if (!ctx->hexlen) {
						size_t off = 0;

						/* ignore following CRLFs (too loose?) */
						while (off < ctx->buffer.used && (
								ctx->buffer.data[off] == '\n' ||
								ctx->buffer.data[off] == '\r')) {
							++off;
						}
						if (off) {
							php_http_buffer_cut(&ctx->buffer, 0, off);
						}

						ctx->zeroed = 1;
						break;
					}
					/* continue */
				} else {
					/* we have not enough data buffered to read in chunk size */
					break;
				}
			}
			/* break */
		}
	}

	php_http_buffer_fix(&tmp);
	*decoded = tmp.data;
	*decoded_len = tmp.used;

	return SUCCESS;
}

static STATUS deflate_flush(php_http_encoding_stream_t *s, char **encoded, size_t *encoded_len)
{
	int status;
	z_streamp ctx = s->ctx;
	TSRMLS_FETCH_FROM_CTX(s->ts);
	
	*encoded_len = PHP_HTTP_DEFLATE_BUFFER_SIZE;
	*encoded = emalloc(*encoded_len);
	
	ctx->avail_in = 0;
	ctx->next_in = NULL;
	ctx->avail_out = *encoded_len;
	ctx->next_out = (Bytef *) *encoded;
	
	switch (status = deflate(ctx, Z_FULL_FLUSH)) {
		case Z_OK:
		case Z_STREAM_END:
			*encoded_len = PHP_HTTP_DEFLATE_BUFFER_SIZE - ctx->avail_out;
			*encoded = erealloc(*encoded, *encoded_len + 1);
			(*encoded)[*encoded_len] = '\0';
			return SUCCESS;
	}
	
	STR_SET(*encoded, NULL);
	*encoded_len = 0;
	php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to flush deflate stream: %s", zError(status));
	return FAILURE;
}

static STATUS dechunk_flush(php_http_encoding_stream_t *s, char **decoded, size_t *decoded_len)
{
	struct dechunk_ctx *ctx = s->ctx;

	if (ctx->hexlen) {
		/* flush all data (should only be chunk data) */
		php_http_buffer_fix(&ctx->buffer);
		php_http_buffer_data(&ctx->buffer, decoded, decoded_len);
		/* waiting for less data now */
		ctx->hexlen -= ctx->buffer.used;
		/* no more buffered data */
		php_http_buffer_reset(&ctx->buffer);
	} else {
		*decoded = NULL;
		*decoded_len = 0;
	}

	return SUCCESS;
}

static STATUS deflate_finish(php_http_encoding_stream_t *s, char **encoded, size_t *encoded_len)
{
	int status;
	z_streamp ctx = s->ctx;
	TSRMLS_FETCH_FROM_CTX(s->ts);
	
	*encoded_len = PHP_HTTP_DEFLATE_BUFFER_SIZE;
	*encoded = emalloc(*encoded_len);
	
	/* deflate remaining input */
	ctx->next_in = (Bytef *) PHP_HTTP_BUFFER(ctx->opaque)->data;
	ctx->avail_in = PHP_HTTP_BUFFER(ctx->opaque)->used;
	
	ctx->avail_out = *encoded_len;
	ctx->next_out = (Bytef *) *encoded;
	
	do {
		status = deflate(ctx, Z_FINISH);
	} while (Z_OK == status);
	
	if (Z_STREAM_END == status) {
		/* cut processed input off */
		php_http_buffer_cut(PHP_HTTP_BUFFER(ctx->opaque), 0, PHP_HTTP_BUFFER(ctx->opaque)->used - ctx->avail_in);
		
		/* size down */
		*encoded_len -= ctx->avail_out;
		*encoded = erealloc(*encoded, *encoded_len + 1);
		(*encoded)[*encoded_len] = '\0';
		return SUCCESS;
	}
	
	STR_SET(*encoded, NULL);
	*encoded_len = 0;
	php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to finish deflate stream: %s", zError(status));
	return FAILURE;
}

static STATUS inflate_finish(php_http_encoding_stream_t *s, char **decoded, size_t *decoded_len)
{
	int status;
	z_streamp ctx = s->ctx;
	TSRMLS_FETCH_FROM_CTX(s->ts);
	
	if (!PHP_HTTP_BUFFER(ctx->opaque)->used) {
		*decoded = NULL;
		*decoded_len = 0;
		return SUCCESS;
	}
	
	*decoded_len = (PHP_HTTP_BUFFER(ctx->opaque)->used + 1) * PHP_HTTP_INFLATE_ROUNDS;
	*decoded = emalloc(*decoded_len);
	
	/* inflate remaining input */
	ctx->next_in = (Bytef *) PHP_HTTP_BUFFER(ctx->opaque)->data;
	ctx->avail_in = PHP_HTTP_BUFFER(ctx->opaque)->used;
	
	ctx->avail_out = *decoded_len;
	ctx->next_out = (Bytef *) *decoded;
	
	if (Z_STREAM_END == (status = inflate(ctx, Z_FINISH))) {
		/* cut processed input off */
		php_http_buffer_cut(PHP_HTTP_BUFFER(ctx->opaque), 0, PHP_HTTP_BUFFER(ctx->opaque)->used - ctx->avail_in);
		
		/* size down */
		*decoded_len -= ctx->avail_out;
		*decoded = erealloc(*decoded, *decoded_len + 1);
		(*decoded)[*decoded_len] = '\0';
		return SUCCESS;
	}
	
	STR_SET(*decoded, NULL);
	*decoded_len = 0;
	php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to finish inflate stream: %s", zError(status));
	return FAILURE;
}

static zend_bool deflate_done(php_http_encoding_stream_t *s)
{
	z_streamp ctx = s->ctx;
	return !ctx->avail_in && !PHP_HTTP_BUFFER(ctx->opaque)->used;
}

static zend_bool inflate_done(php_http_encoding_stream_t *s)
{
	z_streamp ctx = s->ctx;
	return !ctx->avail_in && !PHP_HTTP_BUFFER(ctx->opaque)->used;
}

static zend_bool dechunk_done(php_http_encoding_stream_t *s)
{
	return ((struct dechunk_ctx *) s->ctx)->zeroed;
}

static void deflate_dtor(php_http_encoding_stream_t *s)
{
	if (s->ctx) {
		z_streamp ctx = s->ctx;

		if (ctx->opaque) {
			php_http_buffer_free((php_http_buffer_t **) &ctx->opaque);
		}
		deflateEnd(ctx);
		pefree(ctx, (s->flags & PHP_HTTP_ENCODING_STREAM_PERSISTENT));
		s->ctx = NULL;
	}
}

static void inflate_dtor(php_http_encoding_stream_t *s)
{
	if (s->ctx) {
		z_streamp ctx = s->ctx;

		if (ctx->opaque) {
			php_http_buffer_free((php_http_buffer_t **) &ctx->opaque);
		}
		inflateEnd(ctx);
		pefree(ctx, (s->flags & PHP_HTTP_ENCODING_STREAM_PERSISTENT));
		s->ctx = NULL;
	}
}

static void dechunk_dtor(php_http_encoding_stream_t *s)
{
	if (s->ctx) {
		struct dechunk_ctx *ctx = s->ctx;

		php_http_buffer_dtor(&ctx->buffer);
		pefree(ctx, (s->flags & PHP_HTTP_ENCODING_STREAM_PERSISTENT));
		s->ctx = NULL;
	}
}

static php_http_encoding_stream_ops_t php_http_encoding_deflate_ops = {
	deflate_init,
	deflate_copy,
	deflate_update,
	deflate_flush,
	deflate_done,
	deflate_finish,
	deflate_dtor
};

php_http_encoding_stream_ops_t *php_http_encoding_stream_get_deflate_ops(void)
{
	return &php_http_encoding_deflate_ops;
}

static php_http_encoding_stream_ops_t php_http_encoding_inflate_ops = {
	inflate_init,
	inflate_copy,
	inflate_update,
	NULL,
	inflate_done,
	inflate_finish,
	inflate_dtor
};

php_http_encoding_stream_ops_t *php_http_encoding_stream_get_inflate_ops(void)
{
	return &php_http_encoding_inflate_ops;
}

static php_http_encoding_stream_ops_t php_http_encoding_dechunk_ops = {
	dechunk_init,
	dechunk_copy,
	dechunk_update,
	dechunk_flush,
	dechunk_done,
	NULL,
	dechunk_dtor
};

php_http_encoding_stream_ops_t *php_http_encoding_stream_get_dechunk_ops(void)
{
	return &php_http_encoding_dechunk_ops;
}

static zend_object_handlers php_http_encoding_stream_object_handlers;

zend_object_value php_http_encoding_stream_object_new(zend_class_entry *ce TSRMLS_DC)
{
	return php_http_encoding_stream_object_new_ex(ce, NULL, NULL TSRMLS_CC);
}

zend_object_value php_http_encoding_stream_object_new_ex(zend_class_entry *ce, php_http_encoding_stream_t *s, php_http_encoding_stream_object_t **ptr TSRMLS_DC)
{
	php_http_encoding_stream_object_t *o;

	o = ecalloc(1, sizeof(*o));
	zend_object_std_init((zend_object *) o, ce TSRMLS_CC);
	object_properties_init((zend_object *) o, ce);

	if (ptr) {
		*ptr = o;
	}

	if (s) {
		o->stream = s;
	}

	o->zv.handle = zend_objects_store_put((zend_object *) o, NULL, php_http_encoding_stream_object_free, NULL TSRMLS_CC);
	o->zv.handlers = &php_http_encoding_stream_object_handlers;

	return o->zv;
}

zend_object_value php_http_encoding_stream_object_clone(zval *this_ptr TSRMLS_DC)
{
	zend_object_value new_ov;
	php_http_encoding_stream_object_t *new_obj = NULL, *old_obj = zend_object_store_get_object(getThis() TSRMLS_CC);

	new_ov = php_http_encoding_stream_object_new_ex(old_obj->zo.ce, php_http_encoding_stream_copy(old_obj->stream, NULL), &new_obj TSRMLS_CC);
	zend_objects_clone_members(&new_obj->zo, new_ov, &old_obj->zo, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC);

	return new_ov;
}

void php_http_encoding_stream_object_free(void *object TSRMLS_DC)
{
	php_http_encoding_stream_object_t *o = (php_http_encoding_stream_object_t *) object;

	if (o->stream) {
		php_http_encoding_stream_free(&o->stream);
	}
	zend_object_std_dtor((zend_object *) o TSRMLS_CC);
	efree(o);
}

ZEND_BEGIN_ARG_INFO_EX(ai_HttpEncodingStream___construct, 0, 0, 0)
	ZEND_ARG_INFO(0, flags)
ZEND_END_ARG_INFO();
static PHP_METHOD(HttpEncodingStream, __construct)
{
	long flags = 0;
	php_http_encoding_stream_object_t *obj;
	php_http_encoding_stream_ops_t *ops;

	php_http_expect(SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &flags), invalid_arg, return);

	obj = zend_object_store_get_object(getThis() TSRMLS_CC);

	if (obj->stream) {
		php_http_throw(bad_method_call, "http\\Encoding\\Stream cannot be initialized twice", NULL);
		return;
	}

	if (instanceof_function(obj->zo.ce, php_http_deflate_stream_class_entry TSRMLS_CC)) {
		ops = &php_http_encoding_deflate_ops;
	} else if (instanceof_function(obj->zo.ce, php_http_inflate_stream_class_entry TSRMLS_CC)) {
		ops = &php_http_encoding_inflate_ops;
	} else if (instanceof_function(obj->zo.ce, php_http_dechunk_stream_class_entry TSRMLS_CC)) {
		ops = &php_http_encoding_dechunk_ops;
	} else {
		php_http_throw(runtime, "Unknown http\\Encoding\\Stream class '%s'", obj->zo.ce->name);
		return;
	}

	php_http_expect(obj->stream = php_http_encoding_stream_init(obj->stream, ops, flags TSRMLS_CC), runtime, return);
}

ZEND_BEGIN_ARG_INFO_EX(ai_HttpEncodingStream_update, 0, 0, 1)
	ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO();
static PHP_METHOD(HttpEncodingStream, update)
{
	int data_len;
	char *data_str;

	if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &data_str, &data_len)) {
		php_http_encoding_stream_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC);

		if (obj->stream) {
			size_t encoded_len;
			char *encoded_str;

			if (SUCCESS == php_http_encoding_stream_update(obj->stream, data_str, data_len, &encoded_str, &encoded_len)) {
				RETURN_STRINGL(encoded_str, encoded_len, 0);
			}
		}
	}
}

ZEND_BEGIN_ARG_INFO_EX(ai_HttpEncodingStream_flush, 0, 0, 0)
ZEND_END_ARG_INFO();
static PHP_METHOD(HttpEncodingStream, flush)
{
	if (SUCCESS == zend_parse_parameters_none()) {
		php_http_encoding_stream_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC);

		if (obj->stream) {
			char *encoded_str;
			size_t encoded_len;

			if (SUCCESS == php_http_encoding_stream_flush(obj->stream, &encoded_str, &encoded_len)) {
				if (encoded_str) {
					RETURN_STRINGL(encoded_str, encoded_len, 0);
				} else {
					RETURN_EMPTY_STRING();
				}
			}
		}
	}
}

ZEND_BEGIN_ARG_INFO_EX(ai_HttpEncodingStream_done, 0, 0, 0)
ZEND_END_ARG_INFO();
static PHP_METHOD(HttpEncodingStream, done)
{
	if (SUCCESS == zend_parse_parameters_none()) {
		php_http_encoding_stream_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC);

		if (obj->stream) {
			RETURN_BOOL(php_http_encoding_stream_done(obj->stream));
		}
	}
}

ZEND_BEGIN_ARG_INFO_EX(ai_HttpEncodingStream_finish, 0, 0, 0)
ZEND_END_ARG_INFO();
static PHP_METHOD(HttpEncodingStream, finish)
{
	if (SUCCESS == zend_parse_parameters_none()) {
		php_http_encoding_stream_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC);

		if (obj->stream) {
			char *encoded_str;
			size_t encoded_len;

			if (SUCCESS == php_http_encoding_stream_finish(obj->stream, &encoded_str, &encoded_len)) {
				if (SUCCESS == php_http_encoding_stream_reset(&obj->stream)) {
					if (encoded_str) {
						RETURN_STRINGL(encoded_str, encoded_len, 0);
					} else {
						RETURN_EMPTY_STRING();
					}
				} else {
					STR_FREE(encoded_str);
				}
			}
		}
	}
}

static zend_function_entry php_http_encoding_stream_methods[] = {
	PHP_ME(HttpEncodingStream, __construct,  ai_HttpEncodingStream___construct,  ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
	PHP_ME(HttpEncodingStream, update,       ai_HttpEncodingStream_update,       ZEND_ACC_PUBLIC)
	PHP_ME(HttpEncodingStream, flush,        ai_HttpEncodingStream_flush,        ZEND_ACC_PUBLIC)
	PHP_ME(HttpEncodingStream, done,         ai_HttpEncodingStream_done,         ZEND_ACC_PUBLIC)
	PHP_ME(HttpEncodingStream, finish,       ai_HttpEncodingStream_finish,       ZEND_ACC_PUBLIC)
	EMPTY_FUNCTION_ENTRY
};

ZEND_BEGIN_ARG_INFO_EX(ai_HttpDeflateStream_encode, 0, 0, 1)
	ZEND_ARG_INFO(0, data)
	ZEND_ARG_INFO(0, flags)
ZEND_END_ARG_INFO();
static PHP_METHOD(HttpDeflateStream, encode)
{
	char *str;
	int len;
	long flags = 0;

	if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &len, &flags)) {
		char *enc_str;
		size_t enc_len;

		if (SUCCESS == php_http_encoding_deflate(flags, str, len, &enc_str, &enc_len TSRMLS_CC)) {
			RETURN_STRINGL(enc_str, enc_len, 0);
		}
	}
	RETURN_FALSE;
}

static zend_function_entry php_http_deflate_stream_methods[] = {
	PHP_ME(HttpDeflateStream, encode, ai_HttpDeflateStream_encode, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
	EMPTY_FUNCTION_ENTRY
};

ZEND_BEGIN_ARG_INFO_EX(ai_HttpInflateStream_decode, 0, 0, 1)
	ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO();
static PHP_METHOD(HttpInflateStream, decode)
{
	char *str;
	int len;

	if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str, &len)) {
		char *enc_str;
		size_t enc_len;

		if (SUCCESS == php_http_encoding_inflate(str, len, &enc_str, &enc_len TSRMLS_CC)) {
			RETURN_STRINGL(enc_str, enc_len, 0);
		}
	}
	RETURN_FALSE;
}

static zend_function_entry php_http_inflate_stream_methods[] = {
	PHP_ME(HttpInflateStream, decode, ai_HttpInflateStream_decode, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
	EMPTY_FUNCTION_ENTRY
};

ZEND_BEGIN_ARG_INFO_EX(ai_HttpDechunkStream_decode, 0, 0, 1)
	ZEND_ARG_INFO(0, data)
	ZEND_ARG_INFO(1, decoded_len)
ZEND_END_ARG_INFO();
static PHP_METHOD(HttpDechunkStream, decode)
{
	char *str;
	int len;
	zval *zlen = NULL;

	if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|z!", &str, &len, &zlen)) {
		const char *end_ptr;
		char *enc_str;
		size_t enc_len;

		if ((end_ptr = php_http_encoding_dechunk(str, len, &enc_str, &enc_len TSRMLS_CC))) {
			if (zlen) {
				zval_dtor(zlen);
				ZVAL_LONG(zlen, str + len - end_ptr);
			}
			RETURN_STRINGL(enc_str, enc_len, 0);
		}
	}
	RETURN_FALSE;
}

static zend_function_entry php_http_dechunk_stream_methods[] = {
	PHP_ME(HttpDechunkStream, decode, ai_HttpDechunkStream_decode, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
	EMPTY_FUNCTION_ENTRY
};

zend_class_entry *php_http_encoding_stream_class_entry;
zend_class_entry *php_http_deflate_stream_class_entry;
zend_class_entry *php_http_inflate_stream_class_entry;
zend_class_entry *php_http_dechunk_stream_class_entry;

PHP_MINIT_FUNCTION(http_encoding)
{
	zend_class_entry ce = {0};

	INIT_NS_CLASS_ENTRY(ce, "http\\Encoding", "Stream", php_http_encoding_stream_methods);
	php_http_encoding_stream_class_entry = zend_register_internal_class(&ce TSRMLS_CC);
	php_http_encoding_stream_class_entry->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS;
	php_http_encoding_stream_class_entry->create_object = php_http_encoding_stream_object_new;
	memcpy(&php_http_encoding_stream_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
	php_http_encoding_stream_object_handlers.clone_obj = php_http_encoding_stream_object_clone;

	zend_declare_class_constant_long(php_http_encoding_stream_class_entry, ZEND_STRL("FLUSH_NONE"), PHP_HTTP_ENCODING_STREAM_FLUSH_NONE TSRMLS_CC);
	zend_declare_class_constant_long(php_http_encoding_stream_class_entry, ZEND_STRL("FLUSH_SYNC"), PHP_HTTP_ENCODING_STREAM_FLUSH_SYNC TSRMLS_CC);
	zend_declare_class_constant_long(php_http_encoding_stream_class_entry, ZEND_STRL("FLUSH_FULL"), PHP_HTTP_ENCODING_STREAM_FLUSH_FULL TSRMLS_CC);

	memset(&ce, 0, sizeof(ce));
	INIT_NS_CLASS_ENTRY(ce, "http\\Encoding\\Stream", "Deflate", php_http_deflate_stream_methods);
	php_http_deflate_stream_class_entry = zend_register_internal_class_ex(&ce, php_http_encoding_stream_class_entry, NULL TSRMLS_CC);

	zend_declare_class_constant_long(php_http_deflate_stream_class_entry, ZEND_STRL("TYPE_GZIP"), PHP_HTTP_DEFLATE_TYPE_GZIP TSRMLS_CC);
	zend_declare_class_constant_long(php_http_deflate_stream_class_entry, ZEND_STRL("TYPE_ZLIB"), PHP_HTTP_DEFLATE_TYPE_ZLIB TSRMLS_CC);
	zend_declare_class_constant_long(php_http_deflate_stream_class_entry, ZEND_STRL("TYPE_RAW"), PHP_HTTP_DEFLATE_TYPE_RAW TSRMLS_CC);
	zend_declare_class_constant_long(php_http_deflate_stream_class_entry, ZEND_STRL("LEVEL_DEF"), PHP_HTTP_DEFLATE_LEVEL_DEF TSRMLS_CC);
	zend_declare_class_constant_long(php_http_deflate_stream_class_entry, ZEND_STRL("LEVEL_MIN"), PHP_HTTP_DEFLATE_LEVEL_MIN TSRMLS_CC);
	zend_declare_class_constant_long(php_http_deflate_stream_class_entry, ZEND_STRL("LEVEL_MAX"), PHP_HTTP_DEFLATE_LEVEL_MAX TSRMLS_CC);
	zend_declare_class_constant_long(php_http_deflate_stream_class_entry, ZEND_STRL("STRATEGY_DEF"), PHP_HTTP_DEFLATE_STRATEGY_DEF TSRMLS_CC);
	zend_declare_class_constant_long(php_http_deflate_stream_class_entry, ZEND_STRL("STRATEGY_FILT"), PHP_HTTP_DEFLATE_STRATEGY_FILT TSRMLS_CC);
	zend_declare_class_constant_long(php_http_deflate_stream_class_entry, ZEND_STRL("STRATEGY_HUFF"), PHP_HTTP_DEFLATE_STRATEGY_HUFF TSRMLS_CC);
	zend_declare_class_constant_long(php_http_deflate_stream_class_entry, ZEND_STRL("STRATEGY_RLE"), PHP_HTTP_DEFLATE_STRATEGY_RLE TSRMLS_CC);
	zend_declare_class_constant_long(php_http_deflate_stream_class_entry, ZEND_STRL("STRATEGY_FIXED"), PHP_HTTP_DEFLATE_STRATEGY_FIXED TSRMLS_CC);

	memset(&ce, 0, sizeof(ce));
	INIT_NS_CLASS_ENTRY(ce, "http\\Encoding\\Stream", "Inflate", php_http_inflate_stream_methods);
	php_http_inflate_stream_class_entry = zend_register_internal_class_ex(&ce, php_http_encoding_stream_class_entry, NULL TSRMLS_CC);

	memset(&ce, 0, sizeof(ce));
	INIT_NS_CLASS_ENTRY(ce, "http\\Encoding\\Stream", "Dechunk", php_http_dechunk_stream_methods);
	php_http_dechunk_stream_class_entry = zend_register_internal_class_ex(&ce, php_http_encoding_stream_class_entry, NULL TSRMLS_CC);

	return SUCCESS;
}


/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */