* cpp stuff
[m6w6/ext-http] / http_api.c
1 /*
2 +----------------------------------------------------------------------+
3 | PECL :: http |
4 +----------------------------------------------------------------------+
5 | This source file is subject to version 3.0 of the PHP license, that |
6 | is bundled with this package in the file LICENSE, and is available |
7 | through the world-wide-web at http://www.php.net/license/3_0.txt. |
8 | If you did not receive a copy of the PHP license and are unable to |
9 | obtain it through the world-wide-web, please send a note to |
10 | license@php.net so we can mail you a copy immediately. |
11 +----------------------------------------------------------------------+
12 | Copyright (c) 2004-2005 Michael Wallner <mike@php.net> |
13 +----------------------------------------------------------------------+
14 */
15
16 /* $Id$ */
17
18 #ifdef HAVE_CONFIG_H
19 # include "config.h"
20 #endif
21
22 #include <ctype.h>
23
24 #ifdef PHP_WIN32
25 # define _WINSOCKAPI_
26 # include <winsock2.h>
27 #elif defined(HAVE_NETDB_H)
28 # include <netdb.h>
29 #endif
30
31 #include "php.h"
32 #include "php_version.h"
33 #include "php_streams.h"
34 #include "snprintf.h"
35 #include "ext/standard/md5.h"
36 #include "ext/standard/url.h"
37 #include "ext/standard/base64.h"
38 #include "ext/standard/php_string.h"
39 #include "ext/standard/php_smart_str.h"
40 #include "ext/standard/php_lcg.h"
41
42 #include "SAPI.h"
43
44 #ifdef ZEND_ENGINE_2
45 # include "ext/standard/php_http.h"
46 #endif
47
48 #include "php_http.h"
49 #include "php_http_api.h"
50 #include "php_http_std_defs.h"
51
52 ZEND_DECLARE_MODULE_GLOBALS(http)
53
54 /* {{{ day/month names */
55 static const char *days[] = {
56 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
57 };
58 static const char *wkdays[] = {
59 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
60 };
61 static const char *weekdays[] = {
62 "Monday", "Tuesday", "Wednesday",
63 "Thursday", "Friday", "Saturday", "Sunday"
64 };
65 static const char *months[] = {
66 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
67 "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"
68 };
69 enum assume_next {
70 DATE_MDAY,
71 DATE_YEAR,
72 DATE_TIME
73 };
74 static const struct time_zone {
75 const char *name;
76 const int offset;
77 } time_zones[] = {
78 {"GMT", 0}, /* Greenwich Mean */
79 {"UTC", 0}, /* Universal (Coordinated) */
80 {"WET", 0}, /* Western European */
81 {"BST", 0}, /* British Summer */
82 {"WAT", 60}, /* West Africa */
83 {"AST", 240}, /* Atlantic Standard */
84 {"ADT", 240}, /* Atlantic Daylight */
85 {"EST", 300}, /* Eastern Standard */
86 {"EDT", 300}, /* Eastern Daylight */
87 {"CST", 360}, /* Central Standard */
88 {"CDT", 360}, /* Central Daylight */
89 {"MST", 420}, /* Mountain Standard */
90 {"MDT", 420}, /* Mountain Daylight */
91 {"PST", 480}, /* Pacific Standard */
92 {"PDT", 480}, /* Pacific Daylight */
93 {"YST", 540}, /* Yukon Standard */
94 {"YDT", 540}, /* Yukon Daylight */
95 {"HST", 600}, /* Hawaii Standard */
96 {"HDT", 600}, /* Hawaii Daylight */
97 {"CAT", 600}, /* Central Alaska */
98 {"AHST", 600}, /* Alaska-Hawaii Standard */
99 {"NT", 660}, /* Nome */
100 {"IDLW", 720}, /* International Date Line West */
101 {"CET", -60}, /* Central European */
102 {"MET", -60}, /* Middle European */
103 {"MEWT", -60}, /* Middle European Winter */
104 {"MEST", -120}, /* Middle European Summer */
105 {"CEST", -120}, /* Central European Summer */
106 {"MESZ", -60}, /* Middle European Summer */
107 {"FWT", -60}, /* French Winter */
108 {"FST", -60}, /* French Summer */
109 {"EET", -120}, /* Eastern Europe, USSR Zone 1 */
110 {"WAST", -420}, /* West Australian Standard */
111 {"WADT", -420}, /* West Australian Daylight */
112 {"CCT", -480}, /* China Coast, USSR Zone 7 */
113 {"JST", -540}, /* Japan Standard, USSR Zone 8 */
114 {"EAST", -600}, /* Eastern Australian Standard */
115 {"EADT", -600}, /* Eastern Australian Daylight */
116 {"GST", -600}, /* Guam Standard, USSR Zone 9 */
117 {"NZT", -720}, /* New Zealand */
118 {"NZST", -720}, /* New Zealand Standard */
119 {"NZDT", -720}, /* New Zealand Daylight */
120 {"IDLE", -720}, /* International Date Line East */
121 };
122 /* }}} */
123
124 /* {{{ internals */
125
126 static int http_sort_q(const void *a, const void *b TSRMLS_DC);
127 #define http_send_chunk(d, b, e, m) _http_send_chunk((d), (b), (e), (m) TSRMLS_CC)
128 static STATUS _http_send_chunk(const void *data, const size_t begin, const size_t end, const http_send_mode mode TSRMLS_DC);
129
130 static int check_day(char *day, size_t len);
131 static int check_month(char *month);
132 static int check_tzone(char *tzone);
133
134 static int http_ob_stack_get(php_ob_buffer *, php_ob_buffer **);
135
136 /* {{{ static int http_sort_q(const void *, const void *) */
137 static int http_sort_q(const void *a, const void *b TSRMLS_DC)
138 {
139 Bucket *f, *s;
140 zval result, *first, *second;
141
142 f = *((Bucket **) a);
143 s = *((Bucket **) b);
144
145 first = *((zval **) f->pData);
146 second= *((zval **) s->pData);
147
148 if (numeric_compare_function(&result, first, second TSRMLS_CC) != SUCCESS) {
149 return 0;
150 }
151 return (Z_LVAL(result) > 0 ? -1 : (Z_LVAL(result) < 0 ? 1 : 0));
152 }
153 /* }}} */
154
155 /* {{{ static STATUS http_send_chunk(const void *, size_t, size_t,
156 http_send_mode) */
157 static STATUS _http_send_chunk(const void *data, const size_t begin,
158 const size_t end, const http_send_mode mode TSRMLS_DC)
159 {
160 char *buf;
161 size_t read = 0;
162 long len = end - begin;
163 php_stream *s;
164
165 switch (mode)
166 {
167 case SEND_RSRC:
168 s = (php_stream *) data;
169 if (php_stream_seek(s, begin, SEEK_SET)) {
170 return FAILURE;
171 }
172 buf = (char *) ecalloc(1, HTTP_SENDBUF_SIZE);
173 /* read into buf and write out */
174 while ((len -= HTTP_SENDBUF_SIZE) >= 0) {
175 if (!(read = php_stream_read(s, buf, HTTP_SENDBUF_SIZE))) {
176 efree(buf);
177 return FAILURE;
178 }
179 if (read - php_body_write(buf, read TSRMLS_CC)) {
180 efree(buf);
181 return FAILURE;
182 }
183 }
184
185 /* read & write left over */
186 if (len) {
187 if (read = php_stream_read(s, buf, HTTP_SENDBUF_SIZE + len)) {
188 if (read - php_body_write(buf, read TSRMLS_CC)) {
189 efree(buf);
190 return FAILURE;
191 }
192 } else {
193 efree(buf);
194 return FAILURE;
195 }
196 }
197 efree(buf);
198 return SUCCESS;
199 break;
200
201 case SEND_DATA:
202 return len == php_body_write(((char *)data) + begin, len TSRMLS_CC)
203 ? SUCCESS : FAILURE;
204 break;
205
206 default:
207 return FAILURE;
208 break;
209 }
210 }
211 /* }}} */
212
213 /* {{{ Day/Month/TZ checks for http_parse_date()
214 Originally by libcurl, Copyright (C) 1998 - 2004, Daniel Stenberg, <daniel@haxx.se>, et al. */
215 static int check_day(char *day, size_t len)
216 {
217 int i;
218 const char * const *check = (len > 3) ? &weekdays[0] : &wkdays[0];
219 for (i = 0; i < 7; i++) {
220 if (!strcmp(day, check[0])) {
221 return i;
222 }
223 check++;
224 }
225 return -1;
226 }
227
228 static int check_month(char *month)
229 {
230 int i;
231 const char * const *check = &months[0];
232 for (i = 0; i < 12; i++) {
233 if (!strcmp(month, check[0])) {
234 return i;
235 }
236 check++;
237 }
238 return -1;
239 }
240
241 /* return the time zone offset between GMT and the input one, in number
242 of seconds or -1 if the timezone wasn't found/legal */
243
244 static int check_tzone(char *tzone)
245 {
246 int i;
247 const struct time_zone *check = time_zones;
248 for (i = 0; i < sizeof(time_zones) / sizeof(time_zones[0]); i++) {
249 if (!strcmp(tzone, check->name)) {
250 return check->offset * 60;
251 }
252 check++;
253 }
254 return -1;
255 }
256 /* }}} */
257
258 /* char *pretty_key(char *, int, int, int) */
259 char *pretty_key(char *key, int key_len, int uctitle, int xhyphen)
260 {
261 if (key && key_len) {
262 int i, wasalpha;
263 if (wasalpha = isalpha(key[0])) {
264 key[0] = uctitle ? toupper(key[0]) : tolower(key[0]);
265 }
266 for (i = 1; i < key_len; i++) {
267 if (isalpha(key[i])) {
268 key[i] = ((!wasalpha) && uctitle) ? toupper(key[i]) : tolower(key[i]);
269 wasalpha = 1;
270 } else {
271 if (xhyphen && (key[i] == '_')) {
272 key[i] = '-';
273 }
274 wasalpha = 0;
275 }
276 }
277 }
278 return key;
279 }
280 /* }}} */
281
282 /* {{{ static STATUS http_ob_stack_get(php_ob_buffer *, php_ob_buffer **) */
283 static STATUS http_ob_stack_get(php_ob_buffer *o, php_ob_buffer **s)
284 {
285 static int i = 0;
286 php_ob_buffer *b = emalloc(sizeof(php_ob_buffer));
287 b->handler_name = estrdup(o->handler_name);
288 b->buffer = estrndup(o->buffer, o->text_length);
289 b->text_length = o->text_length;
290 b->chunk_size = o->chunk_size;
291 b->erase = o->erase;
292 s[i++] = b;
293 return SUCCESS;
294 }
295 /* }}} */
296
297 /* }}} internals */
298
299 /* {{{ public API */
300
301 /* {{{ char *http_date(time_t) */
302 PHP_HTTP_API char *_http_date(time_t t TSRMLS_DC)
303 {
304 struct tm *gmtime, tmbuf;
305
306 if (gmtime = php_gmtime_r(&t, &tmbuf)) {
307 char *date = ecalloc(1, 31);
308 snprintf(date, 30,
309 "%s, %02d %s %04d %02d:%02d:%02d GMT",
310 days[gmtime->tm_wday], gmtime->tm_mday,
311 months[gmtime->tm_mon], gmtime->tm_year + 1900,
312 gmtime->tm_hour, gmtime->tm_min, gmtime->tm_sec
313 );
314 return date;
315 }
316
317 return NULL;
318 }
319 /* }}} */
320
321 /* {{{ time_t http_parse_date(char *)
322 Originally by libcurl, Copyright (C) 1998 - 2004, Daniel Stenberg, <daniel@haxx.se>, et al. */
323 PHP_HTTP_API time_t _http_parse_date(const char *date)
324 {
325 time_t t = 0;
326 int tz_offset = -1, year = -1, month = -1, monthday = -1, weekday = -1,
327 hours = -1, minutes = -1, seconds = -1;
328 struct tm tm;
329 enum assume_next dignext = DATE_MDAY;
330 const char *indate = date;
331
332 int found = 0, part = 0; /* max 6 parts */
333
334 while (*date && (part < 6)) {
335 int found = 0;
336
337 while (*date && !isalnum(*date)) {
338 date++;
339 }
340
341 if (isalpha(*date)) {
342 /* a name coming up */
343 char buf[32] = "";
344 size_t len;
345 sscanf(date, "%31[A-Za-z]", buf);
346 len = strlen(buf);
347
348 if (weekday == -1) {
349 weekday = check_day(buf, len);
350 if (weekday != -1) {
351 found = 1;
352 }
353 }
354
355 if (!found && (month == -1)) {
356 month = check_month(buf);
357 if (month != -1) {
358 found = 1;
359 }
360 }
361
362 if (!found && (tz_offset == -1)) {
363 /* this just must be a time zone string */
364 tz_offset = check_tzone(buf);
365 if (tz_offset != -1) {
366 found = 1;
367 }
368 }
369
370 if (!found) {
371 return -1; /* bad string */
372 }
373 date += len;
374 }
375 else if (isdigit(*date)) {
376 /* a digit */
377 int val;
378 char *end;
379 if ((seconds == -1) &&
380 (3 == sscanf(date, "%02d:%02d:%02d", &hours, &minutes, &seconds))) {
381 /* time stamp! */
382 date += 8;
383 found = 1;
384 }
385 else {
386 val = (int) strtol(date, &end, 10);
387
388 if ((tz_offset == -1) && ((end - date) == 4) && (val < 1300) &&
389 (indate < date) && ((date[-1] == '+' || date[-1] == '-'))) {
390 /* four digits and a value less than 1300 and it is preceeded with
391 a plus or minus. This is a time zone indication. */
392 found = 1;
393 tz_offset = (val / 100 * 60 + val % 100) * 60;
394
395 /* the + and - prefix indicates the local time compared to GMT,
396 this we need ther reversed math to get what we want */
397 tz_offset = date[-1] == '+' ? -tz_offset : tz_offset;
398 }
399
400 if (((end - date) == 8) && (year == -1) && (month == -1) && (monthday == -1)) {
401 /* 8 digits, no year, month or day yet. This is YYYYMMDD */
402 found = 1;
403 year = val / 10000;
404 month = (val % 10000) / 100 - 1; /* month is 0 - 11 */
405 monthday = val % 100;
406 }
407
408 if (!found && (dignext == DATE_MDAY) && (monthday == -1)) {
409 if ((val > 0) && (val < 32)) {
410 monthday = val;
411 found = 1;
412 }
413 dignext = DATE_YEAR;
414 }
415
416 if (!found && (dignext == DATE_YEAR) && (year == -1)) {
417 year = val;
418 found = 1;
419 if (year < 1900) {
420 year += year > 70 ? 1900 : 2000;
421 }
422 if(monthday == -1) {
423 dignext = DATE_MDAY;
424 }
425 }
426
427 if (!found) {
428 return -1;
429 }
430
431 date = end;
432 }
433 }
434
435 part++;
436 }
437
438 if (-1 == seconds) {
439 seconds = minutes = hours = 0; /* no time, make it zero */
440 }
441
442 if ((-1 == monthday) || (-1 == month) || (-1 == year)) {
443 /* lacks vital info, fail */
444 return -1;
445 }
446
447 if (sizeof(time_t) < 5) {
448 /* 32 bit time_t can only hold dates to the beginning of 2038 */
449 if (year > 2037) {
450 return 0x7fffffff;
451 }
452 }
453
454 tm.tm_sec = seconds;
455 tm.tm_min = minutes;
456 tm.tm_hour = hours;
457 tm.tm_mday = monthday;
458 tm.tm_mon = month;
459 tm.tm_year = year - 1900;
460 tm.tm_wday = 0;
461 tm.tm_yday = 0;
462 tm.tm_isdst = 0;
463
464 t = mktime(&tm);
465
466 /* time zone adjust */
467 {
468 struct tm *gmt, keeptime2;
469 long delta;
470 time_t t2;
471
472 if(!(gmt = php_gmtime_r(&t, &keeptime2))) {
473 return -1; /* illegal date/time */
474 }
475
476 t2 = mktime(gmt);
477
478 /* Add the time zone diff (between the given timezone and GMT) and the
479 diff between the local time zone and GMT. */
480 delta = (tz_offset != -1 ? tz_offset : 0) + (t - t2);
481
482 if((delta > 0) && (t + delta < t)) {
483 return -1; /* time_t overflow */
484 }
485
486 t += delta;
487 }
488
489 return t;
490 }
491 /* }}} */
492
493 /* {{{ char *http_etag(void *, size_t, http_send_mode) */
494 PHP_HTTP_API char *_http_etag(const void *data_ptr, const size_t data_len,
495 const http_send_mode data_mode TSRMLS_DC)
496 {
497 char ssb_buf[128] = {0};
498 unsigned char digest[16];
499 PHP_MD5_CTX ctx;
500 char *new_etag = ecalloc(1, 33);
501
502 PHP_MD5Init(&ctx);
503
504 switch (data_mode)
505 {
506 case SEND_DATA:
507 PHP_MD5Update(&ctx, data_ptr, data_len);
508 break;
509
510 case SEND_RSRC:
511 if (!HTTP_G(ssb).sb.st_ino) {
512 if (php_stream_stat((php_stream *) data_ptr, &HTTP_G(ssb))) {
513 return NULL;
514 }
515 }
516 snprintf(ssb_buf, 127, "%ld=%ld=%ld",
517 HTTP_G(ssb).sb.st_mtime,
518 HTTP_G(ssb).sb.st_ino,
519 HTTP_G(ssb).sb.st_size
520 );
521 PHP_MD5Update(&ctx, ssb_buf, strlen(ssb_buf));
522 break;
523
524 default:
525 efree(new_etag);
526 return NULL;
527 break;
528 }
529
530 PHP_MD5Final(digest, &ctx);
531 make_digest(new_etag, digest);
532
533 return new_etag;
534 }
535 /* }}} */
536
537 /* {{{ time_t http_lmod(void *, http_send_mode) */
538 PHP_HTTP_API time_t _http_lmod(const void *data_ptr, const http_send_mode data_mode TSRMLS_DC)
539 {
540 switch (data_mode)
541 {
542 case SEND_DATA:
543 {
544 return time(NULL);
545 }
546
547 case SEND_RSRC:
548 {
549 if (!HTTP_G(ssb).sb.st_mtime) {
550 if (php_stream_stat((php_stream *) data_ptr, &HTTP_G(ssb))) {
551 return 0;
552 }
553 }
554 return HTTP_G(ssb).sb.st_mtime;
555 }
556
557 default:
558 {
559 if (!HTTP_G(ssb).sb.st_mtime) {
560 if(php_stream_stat_path(Z_STRVAL_P((zval *) data_ptr), &HTTP_G(ssb))) {
561 return 0;
562 }
563 }
564 return HTTP_G(ssb).sb.st_mtime;
565 }
566 }
567 }
568 /* }}} */
569
570 /* {{{ STATUS http_send_status_header(int, char *) */
571 PHP_HTTP_API STATUS _http_send_status_header(const int status, const char *header TSRMLS_DC)
572 {
573 sapi_header_line h = {(char *) header, strlen(header), status};
574 return sapi_header_op(SAPI_HEADER_REPLACE, &h TSRMLS_CC);
575 }
576 /* }}} */
577
578 /* {{{ zval *http_get_server_var(char *) */
579 PHP_HTTP_API zval *_http_get_server_var(const char *key TSRMLS_DC)
580 {
581 zval **var;
582 if (SUCCESS == zend_hash_find(
583 HTTP_SERVER_VARS,
584 (char *) key, strlen(key) + 1, (void **) &var)) {
585 return *var;
586 }
587 return NULL;
588 }
589 /* }}} */
590
591 /* {{{ void http_ob_etaghandler(char *, uint, char **, uint *, int) */
592 PHP_HTTP_API void _http_ob_etaghandler(char *output, uint output_len,
593 char **handled_output, uint *handled_output_len, int mode TSRMLS_DC)
594 {
595 char etag[33] = { 0 };
596 unsigned char digest[16];
597
598 if (mode & PHP_OUTPUT_HANDLER_START) {
599 PHP_MD5Init(&HTTP_G(etag_md5));
600 }
601
602 PHP_MD5Update(&HTTP_G(etag_md5), output, output_len);
603
604 if (mode & PHP_OUTPUT_HANDLER_END) {
605 PHP_MD5Final(digest, &HTTP_G(etag_md5));
606
607 /* just do that if desired */
608 if (HTTP_G(etag_started)) {
609 make_digest(etag, digest);
610
611 if (http_etag_match("HTTP_IF_NONE_MATCH", etag)) {
612 http_send_status(304);
613 } else {
614 http_send_etag(etag, 32);
615 }
616 }
617 }
618
619 *handled_output_len = output_len;
620 *handled_output = estrndup(output, output_len);
621 }
622 /* }}} */
623
624 /* {{{ STATUS http_start_ob_handler(php_output_handler_func_t, char *, uint, zend_bool) */
625 PHP_HTTP_API STATUS _http_start_ob_handler(php_output_handler_func_t handler_func,
626 char *handler_name, uint chunk_size, zend_bool erase TSRMLS_DC)
627 {
628 php_ob_buffer **stack;
629 int count, i;
630
631 if (count = OG(ob_nesting_level)) {
632 stack = ecalloc(count, sizeof(php_ob_buffer *));
633
634 if (count > 1) {
635 zend_stack_apply_with_argument(&OG(ob_buffers), ZEND_STACK_APPLY_BOTTOMUP,
636 (int (*)(void *elem, void *)) http_ob_stack_get, stack);
637 }
638
639 if (count > 0) {
640 http_ob_stack_get(&OG(active_ob_buffer), stack);
641 }
642
643 while (OG(ob_nesting_level)) {
644 php_end_ob_buffer(0, 0 TSRMLS_CC);
645 }
646 }
647
648 php_ob_set_internal_handler(handler_func, chunk_size, handler_name, erase TSRMLS_CC);
649
650 for (i = 0; i < count; i++) {
651 php_ob_buffer *s = stack[i];
652 if (strcmp(s->handler_name, "default output handler")) {
653 php_start_ob_buffer_named(s->handler_name, s->chunk_size, s->erase TSRMLS_CC);
654 }
655 php_body_write(s->buffer, s->text_length TSRMLS_CC);
656 efree(s->handler_name);
657 efree(s->buffer);
658 efree(s);
659 }
660 if (count) {
661 efree(stack);
662 }
663
664 return SUCCESS;
665 }
666 /* }}} */
667
668 /* {{{ int http_modified_match(char *, int) */
669 PHP_HTTP_API int _http_modified_match(const char *entry, const time_t t TSRMLS_DC)
670 {
671 int retval;
672 zval *zmodified;
673 char *modified, *chr_ptr;
674
675 HTTP_GSC(zmodified, entry, 0);
676
677 modified = estrndup(Z_STRVAL_P(zmodified), Z_STRLEN_P(zmodified));
678 if (chr_ptr = strrchr(modified, ';')) {
679 chr_ptr = 0;
680 }
681 retval = (t <= http_parse_date(modified));
682 efree(modified);
683 return retval;
684 }
685 /* }}} */
686
687 /* {{{ int http_etag_match(char *, char *) */
688 PHP_HTTP_API int _http_etag_match(const char *entry, const char *etag TSRMLS_DC)
689 {
690 zval *zetag;
691 char *quoted_etag;
692 STATUS result;
693
694 HTTP_GSC(zetag, entry, 0);
695
696 if (NULL != strchr(Z_STRVAL_P(zetag), '*')) {
697 return 1;
698 }
699
700 quoted_etag = (char *) emalloc(strlen(etag) + 3);
701 sprintf(quoted_etag, "\"%s\"", etag);
702
703 if (!strchr(Z_STRVAL_P(zetag), ',')) {
704 result = !strcmp(Z_STRVAL_P(zetag), quoted_etag);
705 } else {
706 result = (NULL != strstr(Z_STRVAL_P(zetag), quoted_etag));
707 }
708 efree(quoted_etag);
709 return result;
710 }
711 /* }}} */
712
713 /* {{{ STATUS http_send_last_modified(int) */
714 PHP_HTTP_API STATUS _http_send_last_modified(const time_t t TSRMLS_DC)
715 {
716 char *date = NULL;
717 if (date = http_date(t)) {
718 char modified[96] = "Last-Modified: ";
719 strcat(modified, date);
720 efree(date);
721
722 /* remember */
723 HTTP_G(lmod) = t;
724
725 return http_send_header(modified);
726 }
727 return FAILURE;
728 }
729 /* }}} */
730
731 /* {{{ static STATUS http_send_etag(char *, int) */
732 PHP_HTTP_API STATUS _http_send_etag(const char *etag,
733 const int etag_len TSRMLS_DC)
734 {
735 STATUS status;
736 char *etag_header;
737
738 if (!etag_len){
739 php_error_docref(NULL TSRMLS_CC,E_ERROR,
740 "Attempt to send empty ETag (previous: %s)\n", HTTP_G(etag));
741 return FAILURE;
742 }
743
744 /* remember */
745 if (HTTP_G(etag)) {
746 efree(HTTP_G(etag));
747 }
748 HTTP_G(etag) = estrdup(etag);
749
750 etag_header = ecalloc(1, sizeof("ETag: \"\"") + etag_len);
751 sprintf(etag_header, "ETag: \"%s\"", etag);
752 if (SUCCESS != (status = http_send_header(etag_header))) {
753 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't send '%s' header", etag_header);
754 }
755 efree(etag_header);
756 return status;
757 }
758 /* }}} */
759
760 /* {{{ STATUS http_send_cache_control(char *, size_t) */
761 PHP_HTTP_API STATUS _http_send_cache_control(const char *cache_control,
762 const size_t cc_len TSRMLS_DC)
763 {
764 STATUS status;
765 char *cc_header = ecalloc(1, sizeof("Cache-Control: ") + cc_len);
766
767 sprintf(cc_header, "Cache-Control: %s", cache_control);
768 if (SUCCESS != (status = http_send_header(cc_header))) {
769 php_error_docref(NULL TSRMLS_CC, E_NOTICE,
770 "Could not send '%s' header", cc_header);
771 }
772 efree(cc_header);
773 return status;
774 }
775 /* }}} */
776
777 /* {{{ STATUS http_send_content_type(char *, size_t) */
778 PHP_HTTP_API STATUS _http_send_content_type(const char *content_type,
779 const size_t ct_len TSRMLS_DC)
780 {
781 STATUS status;
782 char *ct_header;
783
784 if (!strchr(content_type, '/')) {
785 php_error_docref(NULL TSRMLS_CC, E_WARNING,
786 "Content-Type '%s' doesn't seem to consist of a primary and a secondary part",
787 content_type);
788 return FAILURE;
789 }
790
791 /* remember for multiple ranges */
792 if (HTTP_G(ctype)) {
793 efree(HTTP_G(ctype));
794 }
795 HTTP_G(ctype) = estrndup(content_type, ct_len);
796
797 ct_header = ecalloc(1, sizeof("Content-Type: ") + ct_len);
798 sprintf(ct_header, "Content-Type: %s", content_type);
799
800 if (SUCCESS != (status = http_send_header(ct_header))) {
801 php_error_docref(NULL TSRMLS_CC, E_WARNING,
802 "Couldn't send '%s' header", ct_header);
803 }
804 efree(ct_header);
805 return status;
806 }
807 /* }}} */
808
809 /* {{{ STATUS http_send_content_disposition(char *, size_t, zend_bool) */
810 PHP_HTTP_API STATUS _http_send_content_disposition(const char *filename,
811 const size_t f_len, const int send_inline TSRMLS_DC)
812 {
813 STATUS status;
814 char *cd_header;
815
816 if (send_inline) {
817 cd_header = ecalloc(1, sizeof("Content-Disposition: inline; filename=\"\"") + f_len);
818 sprintf(cd_header, "Content-Disposition: inline; filename=\"%s\"", filename);
819 } else {
820 cd_header = ecalloc(1, sizeof("Content-Disposition: attachment; filename=\"\"") + f_len);
821 sprintf(cd_header, "Content-Disposition: attachment; filename=\"%s\"", filename);
822 }
823
824 if (SUCCESS != (status = http_send_header(cd_header))) {
825 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't send '%s' header", cd_header);
826 }
827 efree(cd_header);
828 return status;
829 }
830 /* }}} */
831
832 /* {{{ STATUS http_cache_last_modified(time_t, time_t, char *, size_t) */
833 PHP_HTTP_API STATUS _http_cache_last_modified(const time_t last_modified,
834 const time_t send_modified, const char *cache_control, const size_t cc_len TSRMLS_DC)
835 {
836 if (cc_len) {
837 http_send_cache_control(cache_control, cc_len);
838 }
839
840 if (http_modified_match("HTTP_IF_MODIFIED_SINCE", last_modified)) {
841 if (SUCCESS == http_send_status(304)) {
842 zend_bailout();
843 } else {
844 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not send 304 Not Modified");
845 return FAILURE;
846 }
847 }
848 return http_send_last_modified(send_modified);
849 }
850 /* }}} */
851
852 /* {{{ STATUS http_cache_etag(char *, size_t, char *, size_t) */
853 PHP_HTTP_API STATUS _http_cache_etag(const char *etag, const size_t etag_len,
854 const char *cache_control, const size_t cc_len TSRMLS_DC)
855 {
856 if (cc_len) {
857 http_send_cache_control(cache_control, cc_len);
858 }
859
860 if (etag_len) {
861 http_send_etag(etag, etag_len);
862 if (http_etag_match("HTTP_IF_NONE_MATCH", etag)) {
863 if (SUCCESS == http_send_status(304)) {
864 zend_bailout();
865 } else {
866 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not send 304 Not Modified");
867 return FAILURE;
868 }
869 }
870 }
871
872 /* if no etag is given and we didn't already start ob_etaghandler -- start it */
873 if (!HTTP_G(etag_started)) {
874 if (SUCCESS == http_start_ob_handler(_http_ob_etaghandler, "ob_etaghandler", 4096, 1)) {
875 HTTP_G(etag_started) = 1;
876 return SUCCESS;
877 } else {
878 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not start ob_etaghandler");
879 return FAILURE;
880 }
881 }
882 return SUCCESS;
883 }
884 /* }}} */
885
886 /* {{{ char *http_absolute_uri(char *) */
887 PHP_HTTP_API char *_http_absolute_uri_ex(
888 const char *url, size_t url_len,
889 const char *proto, size_t proto_len,
890 const char *host, size_t host_len,
891 unsigned port TSRMLS_DC)
892 {
893 #if defined(PHP_WIN32) || defined(HAVE_NETDB_H)
894 struct servent *se;
895 #endif
896 php_url *purl, furl = {NULL};
897 size_t full_len = 0;
898 zval *zhost = NULL;
899 char *scheme = NULL, *URL = ecalloc(1, HTTP_URI_MAXLEN + 1);
900
901 if ((!url || !url_len) && (
902 (!(url = SG(request_info).request_uri)) ||
903 (!(url_len = strlen(SG(request_info).request_uri))))) {
904 php_error_docref(NULL TSRMLS_CC, E_WARNING,
905 "Cannot build an absolute URI if supplied URL and REQUEST_URI is empty");
906 return NULL;
907 }
908
909 if (!(purl = php_url_parse(url))) {
910 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not parse supplied URL");
911 return NULL;
912 }
913
914 furl.user = purl->user;
915 furl.pass = purl->pass;
916 furl.path = purl->path;
917 furl.query = purl->query;
918 furl.fragment = purl->fragment;
919
920 if (proto) {
921 furl.scheme = scheme = estrdup(proto);
922 } else if (purl->scheme) {
923 furl.scheme = purl->scheme;
924 #if defined(PHP_WIN32) || defined(HAVE_NETDB_H)
925 } else if (port && (se = getservbyport(port, "tcp"))) {
926 furl.scheme = (scheme = estrdup(se->s_name));
927 #endif
928 } else {
929 furl.scheme = "http";
930 }
931
932 if (port) {
933 furl.port = port;
934 } else if (purl->port) {
935 furl.port = purl->port;
936 } else if (strncmp(furl.scheme, "http", 4)) {
937 #if defined(PHP_WIN32) || defined(HAVE_NETDB_H)
938 if (se = getservbyname(furl.scheme, "tcp")) {
939 furl.port = se->s_port;
940 } else
941 #endif
942 furl.port = 80;
943 } else {
944 furl.port = (furl.scheme[5] == 's') ? 443 : 80;
945 }
946
947 if (host) {
948 furl.host = (char *) host;
949 } else if (purl->host) {
950 furl.host = purl->host;
951 } else if ( (zhost = http_get_server_var("HTTP_HOST")) ||
952 (zhost = http_get_server_var("SERVER_NAME"))) {
953 furl.host = Z_STRVAL_P(zhost);
954 } else {
955 furl.host = "localhost";
956 }
957
958 #define HTTP_URI_STRLCATS(URL, full_len, add_string) HTTP_URI_STRLCAT(URL, full_len, add_string, sizeof(add_string)-1)
959 #define HTTP_URI_STRLCATL(URL, full_len, add_string) HTTP_URI_STRLCAT(URL, full_len, add_string, strlen(add_string))
960 #define HTTP_URI_STRLCAT(URL, full_len, add_string, add_len) \
961 if ((full_len += add_len) > HTTP_URI_MAXLEN) { \
962 php_error_docref(NULL TSRMLS_CC, E_NOTICE, \
963 "Absolute URI would have exceeded max URI length (%d bytes) - " \
964 "tried to add %d bytes ('%s')", \
965 HTTP_URI_MAXLEN, add_len, add_string); \
966 if (scheme) { \
967 efree(scheme); \
968 } \
969 php_url_free(purl); \
970 return URL; \
971 } else { \
972 strcat(URL, add_string); \
973 }
974
975 HTTP_URI_STRLCATL(URL, full_len, furl.scheme);
976 HTTP_URI_STRLCATS(URL, full_len, "://");
977
978 if (furl.user) {
979 HTTP_URI_STRLCATL(URL, full_len, furl.user);
980 if (furl.pass) {
981 HTTP_URI_STRLCATS(URL, full_len, ":");
982 HTTP_URI_STRLCATL(URL, full_len, furl.pass);
983 }
984 HTTP_URI_STRLCATS(URL, full_len, "@");
985 }
986
987 HTTP_URI_STRLCATL(URL, full_len, furl.host);
988
989 if ( (!strcmp(furl.scheme, "http") && (furl.port != 80)) ||
990 (!strcmp(furl.scheme, "https") && (furl.port != 443))) {
991 char port_string[8] = {0};
992 snprintf(port_string, 7, ":%u", furl.port);
993 HTTP_URI_STRLCATL(URL, full_len, port_string);
994 }
995
996 if (furl.path) {
997 if (furl.path[0] != '/') {
998 HTTP_URI_STRLCATS(URL, full_len, "/");
999 }
1000 HTTP_URI_STRLCATL(URL, full_len, furl.path);
1001 } else {
1002 HTTP_URI_STRLCATS(URL, full_len, "/");
1003 }
1004
1005 if (furl.query) {
1006 HTTP_URI_STRLCATS(URL, full_len, "?");
1007 HTTP_URI_STRLCATL(URL, full_len, furl.query);
1008 }
1009
1010 if (furl.fragment) {
1011 HTTP_URI_STRLCATS(URL, full_len, "#");
1012 HTTP_URI_STRLCATL(URL, full_len, furl.fragment);
1013 }
1014
1015 if (scheme) {
1016 efree(scheme);
1017 }
1018 php_url_free(purl);
1019
1020 return URL;
1021 }
1022 /* }}} */
1023
1024 /* {{{ char *http_negotiate_q(char *, zval *, char *, hash_entry_type) */
1025 PHP_HTTP_API char *_http_negotiate_q(const char *entry, const zval *supported,
1026 const char *def TSRMLS_DC)
1027 {
1028 zval *zaccept, *zarray, *zdelim, **zentry, *zentries, **zsupp;
1029 char *q_ptr, *result;
1030 int i, c;
1031 double qual;
1032
1033 HTTP_GSC(zaccept, entry, estrdup(def));
1034
1035 MAKE_STD_ZVAL(zarray);
1036 array_init(zarray);
1037
1038 MAKE_STD_ZVAL(zdelim);
1039 ZVAL_STRING(zdelim, ",", 0);
1040 php_explode(zdelim, zaccept, zarray, -1);
1041 efree(zdelim);
1042
1043 MAKE_STD_ZVAL(zentries);
1044 array_init(zentries);
1045
1046 c = zend_hash_num_elements(Z_ARRVAL_P(zarray));
1047 for (i = 0; i < c; i++, zend_hash_move_forward(Z_ARRVAL_P(zarray))) {
1048
1049 if (SUCCESS != zend_hash_get_current_data(
1050 Z_ARRVAL_P(zarray), (void **) &zentry)) {
1051 php_error_docref(NULL TSRMLS_CC, E_WARNING,
1052 "Cannot parse %s header: %s", entry, Z_STRVAL_P(zaccept));
1053 break;
1054 }
1055
1056 /* check for qualifier */
1057 if (NULL != (q_ptr = strrchr(Z_STRVAL_PP(zentry), ';'))) {
1058 qual = strtod(q_ptr + 3, NULL);
1059 } else {
1060 qual = 1000.0 - i;
1061 }
1062
1063 /* walk through the supported array */
1064 FOREACH_VAL(supported, zsupp) {
1065 if (!strcasecmp(Z_STRVAL_PP(zsupp), Z_STRVAL_PP(zentry))) {
1066 add_assoc_double(zentries, Z_STRVAL_PP(zsupp), qual);
1067 break;
1068 }
1069 }
1070 }
1071
1072 zval_dtor(zarray);
1073 efree(zarray);
1074
1075 zend_hash_internal_pointer_reset(Z_ARRVAL_P(zentries));
1076
1077 if ( (SUCCESS != zend_hash_sort(Z_ARRVAL_P(zentries), zend_qsort,
1078 http_sort_q, 0 TSRMLS_CC)) ||
1079 (HASH_KEY_NON_EXISTANT == zend_hash_get_current_key(
1080 Z_ARRVAL_P(zentries), &result, 0, 1))) {
1081 result = estrdup(def);
1082 }
1083
1084 zval_dtor(zentries);
1085 efree(zentries);
1086
1087 return result;
1088 }
1089 /* }}} */
1090
1091 /* {{{ http_range_status http_get_request_ranges(HashTable *ranges, size_t) */
1092 PHP_HTTP_API http_range_status _http_get_request_ranges(HashTable *ranges,
1093 const size_t length TSRMLS_DC)
1094 {
1095 zval *zrange;
1096 char *range, c;
1097 long begin = -1, end = -1, *ptr;
1098
1099 HTTP_GSC(zrange, "HTTP_RANGE", RANGE_NO);
1100 range = Z_STRVAL_P(zrange);
1101
1102 if (strncmp(range, "bytes=", sizeof("bytes=") - 1)) {
1103 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Range header misses bytes=");
1104 return RANGE_NO;
1105 }
1106
1107 ptr = &begin;
1108 range += sizeof("bytes=") - 1;
1109
1110 do {
1111 switch (c = *(range++))
1112 {
1113 case '0':
1114 *ptr *= 10;
1115 break;
1116
1117 case '1': case '2': case '3':
1118 case '4': case '5': case '6':
1119 case '7': case '8': case '9':
1120 /*
1121 * If the value of the pointer is already set (non-negative)
1122 * then multiply its value by ten and add the current value,
1123 * else initialise the pointers value with the current value
1124 * --
1125 * This let us recognize empty fields when validating the
1126 * ranges, i.e. a "-10" for begin and "12345" for the end
1127 * was the following range request: "Range: bytes=0-12345";
1128 * While a "-1" for begin and "12345" for the end would
1129 * have been: "Range: bytes=-12345".
1130 */
1131 if (*ptr > 0) {
1132 *ptr *= 10;
1133 *ptr += c - '0';
1134 } else {
1135 *ptr = c - '0';
1136 }
1137 break;
1138
1139 case '-':
1140 ptr = &end;
1141 break;
1142
1143 case ' ':
1144 /* IE - ignore for now */
1145 break;
1146
1147 case 0:
1148 case ',':
1149
1150 if (length) {
1151 /* validate ranges */
1152 switch (begin)
1153 {
1154 /* "0-12345" */
1155 case -10:
1156 if ((length - end) < 1) {
1157 return RANGE_ERR;
1158 }
1159 begin = 0;
1160 break;
1161
1162 /* "-12345" */
1163 case -1:
1164 if ((length - end) < 1) {
1165 return RANGE_ERR;
1166 }
1167 begin = length - end;
1168 end = length;
1169 break;
1170
1171 /* "12345-(xxx)" */
1172 default:
1173 switch (end)
1174 {
1175 /* "12345-" */
1176 case -1:
1177 if ((length - begin) < 1) {
1178 return RANGE_ERR;
1179 }
1180 end = length - 1;
1181 break;
1182
1183 /* "12345-67890" */
1184 default:
1185 if ( ((length - begin) < 1) ||
1186 ((length - end) < 1) ||
1187 ((begin - end) >= 0)) {
1188 return RANGE_ERR;
1189 }
1190 break;
1191 }
1192 break;
1193 }
1194 }
1195 {
1196 zval *zentry;
1197 MAKE_STD_ZVAL(zentry);
1198 array_init(zentry);
1199 add_index_long(zentry, 0, begin);
1200 add_index_long(zentry, 1, end);
1201 zend_hash_next_index_insert(ranges, &zentry, sizeof(zval *), NULL);
1202
1203 begin = -1;
1204 end = -1;
1205 ptr = &begin;
1206 }
1207 break;
1208
1209 default:
1210 return RANGE_NO;
1211 break;
1212 }
1213 } while (c != 0);
1214
1215 return RANGE_OK;
1216 }
1217 /* }}} */
1218
1219 /* {{{ STATUS http_send_ranges(HashTable *, void *, size_t, http_send_mode) */
1220 PHP_HTTP_API STATUS _http_send_ranges(HashTable *ranges, const void *data, const size_t size, const http_send_mode mode TSRMLS_DC)
1221 {
1222 long **begin, **end;
1223 zval **zrange;
1224
1225 /* single range */
1226 if (zend_hash_num_elements(ranges) == 1) {
1227 char range_header[256] = {0};
1228
1229 if (SUCCESS != zend_hash_index_find(ranges, 0, (void **) &zrange) ||
1230 SUCCESS != zend_hash_index_find(Z_ARRVAL_PP(zrange), 0, (void **) &begin) ||
1231 SUCCESS != zend_hash_index_find(Z_ARRVAL_PP(zrange), 1, (void **) &end)) {
1232 return FAILURE;
1233 }
1234
1235 /* Send HTTP 206 Partial Content */
1236 http_send_status(206);
1237
1238 /* send content range header */
1239 snprintf(range_header, 255, "Content-Range: bytes %d-%d/%d", **begin, **end, size);
1240 http_send_header(range_header);
1241
1242 /* send requested chunk */
1243 return http_send_chunk(data, **begin, **end + 1, mode);
1244 }
1245
1246 /* multi range */
1247 else {
1248 char bound[23] = {0}, preface[1024] = {0},
1249 multi_header[68] = "Content-Type: multipart/byteranges; boundary=";
1250
1251 /* Send HTTP 206 Partial Content */
1252 http_send_status(206);
1253
1254 /* send multipart/byteranges header */
1255 snprintf(bound, 22, "--%d%0.9f", time(NULL), php_combined_lcg(TSRMLS_C));
1256 strncat(multi_header, bound + 2, 21);
1257 http_send_header(multi_header);
1258
1259 /* send each requested chunk */
1260 FOREACH_HASH_VAL(ranges, zrange) {
1261 if (SUCCESS != zend_hash_index_find(Z_ARRVAL_PP(zrange), 0, (void **) &begin) ||
1262 SUCCESS != zend_hash_index_find(Z_ARRVAL_PP(zrange), 1, (void **) &end)) {
1263 break;
1264 }
1265
1266 snprintf(preface, 1023,
1267 HTTP_CRLF "%s"
1268 HTTP_CRLF "Content-Type: %s"
1269 HTTP_CRLF "Content-Range: bytes %ld-%ld/%ld"
1270 HTTP_CRLF
1271 HTTP_CRLF,
1272
1273 bound,
1274 HTTP_G(ctype) ? HTTP_G(ctype) : "application/x-octetstream",
1275 **begin,
1276 **end,
1277 size
1278 );
1279
1280 php_body_write(preface, strlen(preface) TSRMLS_CC);
1281 http_send_chunk(data, **begin, **end + 1, mode);
1282 }
1283
1284 /* write boundary once more */
1285 php_body_write(HTTP_CRLF, sizeof(HTTP_CRLF) - 1 TSRMLS_CC);
1286 php_body_write(bound, strlen(bound) TSRMLS_CC);
1287 php_body_write("--", 2 TSRMLS_CC);
1288
1289 return SUCCESS;
1290 }
1291 }
1292 /* }}} */
1293
1294 /* {{{ STATUS http_send(void *, size_t, http_send_mode) */
1295 PHP_HTTP_API STATUS _http_send(const void *data_ptr, const size_t data_size,
1296 const http_send_mode data_mode TSRMLS_DC)
1297 {
1298 int is_range_request = http_is_range_request();
1299
1300 if (!data_ptr) {
1301 return FAILURE;
1302 }
1303 if (!data_size) {
1304 return SUCCESS;
1305 }
1306
1307 /* etag handling */
1308 if (HTTP_G(etag_started)) {
1309 char *etag;
1310 /* interrupt */
1311 HTTP_G(etag_started) = 0;
1312 /* never ever use the output to compute the ETag if http_send() is used */
1313 php_end_ob_buffer(0, 0 TSRMLS_CC);
1314 if (!(etag = http_etag(data_ptr, data_size, data_mode))) {
1315 return FAILURE;
1316 }
1317
1318 /* send 304 Not Modified if etag matches */
1319 if ((!is_range_request) && http_etag_match("HTTP_IF_NONE_MATCH", etag)) {
1320 efree(etag);
1321 return http_send_status(304);
1322 }
1323
1324 http_send_etag(etag, 32);
1325 efree(etag);
1326 }
1327
1328 /* send 304 Not Modified if last-modified matches*/
1329 if ((!is_range_request) && http_modified_match("HTTP_IF_MODIFIED_SINCE", HTTP_G(lmod))) {
1330 return http_send_status(304);
1331 }
1332
1333 if (is_range_request) {
1334
1335 /* only send ranges if entity hasn't changed */
1336 if (
1337 ((!zend_hash_exists(HTTP_SERVER_VARS, "HTTP_IF_MATCH", 13)) ||
1338 http_etag_match("HTTP_IF_MATCH", HTTP_G(etag)))
1339 &&
1340 ((!zend_hash_exists(HTTP_SERVER_VARS, "HTTP_IF_UNMODIFIED_SINCE", 25)) ||
1341 http_modified_match("HTTP_IF_UNMODIFIED_SINCE", HTTP_G(lmod)))
1342 ) {
1343
1344 STATUS result = FAILURE;
1345 HashTable ranges;
1346 zend_hash_init(&ranges, 0, NULL, ZVAL_PTR_DTOR, 0);
1347
1348 switch (http_get_request_ranges(&ranges, data_size))
1349 {
1350 case RANGE_NO:
1351 zend_hash_destroy(&ranges);
1352 /* go ahead and send all */
1353 break;
1354
1355 case RANGE_OK:
1356 result = http_send_ranges(&ranges, data_ptr, data_size, data_mode);
1357 zend_hash_destroy(&ranges);
1358 return result;
1359 break;
1360
1361 case RANGE_ERR:
1362 zend_hash_destroy(&ranges);
1363 http_send_status(416);
1364 return FAILURE;
1365 break;
1366
1367 default:
1368 return FAILURE;
1369 break;
1370 }
1371 }
1372 }
1373 /* send all */
1374 return http_send_chunk(data_ptr, 0, data_size, data_mode);
1375 }
1376 /* }}} */
1377
1378 /* {{{ STATUS http_send_stream(php_stream *) */
1379 PHP_HTTP_API STATUS _http_send_stream_ex(php_stream *file,
1380 zend_bool close_stream TSRMLS_DC)
1381 {
1382 STATUS status;
1383
1384 if ((!file) || php_stream_stat(file, &HTTP_G(ssb))) {
1385 return FAILURE;
1386 }
1387
1388 status = http_send(file, HTTP_G(ssb).sb.st_size, SEND_RSRC);
1389
1390 if (close_stream) {
1391 php_stream_close(file);
1392 }
1393
1394 return status;
1395 }
1396 /* }}} */
1397
1398 /* {{{ STATUS http_chunked_decode(char *, size_t, char **, size_t *) */
1399 PHP_HTTP_API STATUS _http_chunked_decode(const char *encoded,
1400 const size_t encoded_len, char **decoded, size_t *decoded_len TSRMLS_DC)
1401 {
1402 const char *e_ptr;
1403 char *d_ptr;
1404
1405 *decoded_len = 0;
1406 *decoded = ecalloc(1, encoded_len);
1407 d_ptr = *decoded;
1408 e_ptr = encoded;
1409
1410 while (((e_ptr - encoded) - encoded_len) > 0) {
1411 char hex_len[9] = {0};
1412 size_t chunk_len = 0;
1413 int i = 0;
1414
1415 /* read in chunk size */
1416 while (isxdigit(*e_ptr)) {
1417 if (i == 9) {
1418 php_error_docref(NULL TSRMLS_CC, E_WARNING,
1419 "Chunk size is too long: 0x%s...", hex_len);
1420 efree(*decoded);
1421 return FAILURE;
1422 }
1423 hex_len[i++] = *e_ptr++;
1424 }
1425
1426 /* reached the end */
1427 if (!strcmp(hex_len, "0")) {
1428 break;
1429 }
1430
1431 /* new line */
1432 if (strncmp(e_ptr, HTTP_CRLF, 2)) {
1433 php_error_docref(NULL TSRMLS_CC, E_WARNING,
1434 "Invalid character (expected 0x0D 0x0A; got: %x %x)",
1435 *e_ptr, *(e_ptr + 1));
1436 efree(*decoded);
1437 return FAILURE;
1438 }
1439
1440 /* hex to long */
1441 {
1442 char *error = NULL;
1443 chunk_len = strtol(hex_len, &error, 16);
1444 if (error == hex_len) {
1445 php_error_docref(NULL TSRMLS_CC, E_WARNING,
1446 "Invalid chunk size string: '%s'", hex_len);
1447 efree(*decoded);
1448 return FAILURE;
1449 }
1450 }
1451
1452 memcpy(d_ptr, e_ptr += 2, chunk_len);
1453 d_ptr += chunk_len;
1454 e_ptr += chunk_len + 2;
1455 *decoded_len += chunk_len;
1456 }
1457
1458 return SUCCESS;
1459 }
1460 /* }}} */
1461
1462 /* {{{ STATUS http_split_response(zval *, zval *, zval *) */
1463 PHP_HTTP_API STATUS _http_split_response(zval *response, zval *headers, zval *body TSRMLS_DC)
1464 {
1465 char *b = NULL;
1466 size_t l = 0;
1467 STATUS status = http_split_response_ex(Z_STRVAL_P(response), Z_STRLEN_P(response), Z_ARRVAL_P(headers), &b, &l);
1468 ZVAL_STRINGL(body, b, l, 0);
1469 return status;
1470 }
1471 /* }}} */
1472
1473 /* {{{ STATUS http_split_response(char *, size_t, HashTable *, char **, size_t *) */
1474 PHP_HTTP_API STATUS _http_split_response_ex(char *response,
1475 size_t response_len, HashTable *headers, char **body, size_t *body_len TSRMLS_DC)
1476 {
1477 char *header = response, *real_body = NULL;
1478
1479 while (0 < (response_len - (response - header + 4))) {
1480 if ( (*response++ == '\r') &&
1481 (*response++ == '\n') &&
1482 (*response++ == '\r') &&
1483 (*response++ == '\n')) {
1484 real_body = response;
1485 break;
1486 }
1487 }
1488
1489 if (real_body && (*body_len = (response_len - (real_body - header)))) {
1490 *body = ecalloc(1, *body_len + 1);
1491 memcpy(*body, real_body, *body_len);
1492 }
1493
1494 return http_parse_headers_ex(header, real_body ? response_len - *body_len : response_len, headers, 1);
1495 }
1496 /* }}} */
1497
1498 /* {{{ STATUS http_parse_headers(char *, long, zval *) */
1499 PHP_HTTP_API STATUS _http_parse_headers_ex(char *header, int header_len,
1500 HashTable *headers, zend_bool prettify TSRMLS_DC)
1501 {
1502 char *colon = NULL, *line = NULL, *begin = header;
1503 zval array;
1504
1505 Z_ARRVAL(array) = headers;
1506
1507 if (header_len < 2) {
1508 return FAILURE;
1509 }
1510
1511 /* status code */
1512 if (!strncmp(header, "HTTP/1.", 7)) {
1513 char *end = strstr(header, HTTP_CRLF);
1514 add_assoc_stringl(&array, "Status",
1515 header + sizeof("HTTP/1.x ") - 1,
1516 end - (header + sizeof("HTTP/1.x ") - 1), 1);
1517 header = end + 2;
1518 }
1519
1520 line = header;
1521
1522 while (header_len >= (line - begin)) {
1523 int value_len = 0;
1524
1525 switch (*line++)
1526 {
1527 case 0:
1528 --value_len; /* we don't have CR so value length is one char less */
1529 case '\n':
1530 if (colon && ((!(*line - 1)) || ((*line != ' ') && (*line != '\t')))) {
1531
1532 /* skip empty key */
1533 if (header != colon) {
1534 char *key = estrndup(header, colon - header);
1535
1536 if (prettify) {
1537 key = pretty_key(key, colon - header, 1, 1);
1538 }
1539
1540 value_len += line - colon - 1;
1541
1542 /* skip leading ws */
1543 while (isspace(*(++colon))) --value_len;
1544 /* skip trailing ws */
1545 while (isspace(colon[value_len - 1])) --value_len;
1546
1547 if (value_len < 1) {
1548 /* hm, empty header? */
1549 add_assoc_stringl(&array, key, "", 0, 1);
1550 } else {
1551 add_assoc_stringl(&array, key, colon, value_len, 1);
1552 }
1553 efree(key);
1554 }
1555
1556 colon = NULL;
1557 value_len = 0;
1558 header += line - header;
1559 }
1560 break;
1561
1562 case ':':
1563 if (!colon) {
1564 colon = line - 1;
1565 }
1566 break;
1567 }
1568 }
1569 return SUCCESS;
1570 }
1571 /* }}} */
1572
1573 /* {{{ void http_get_request_headers_ex(HashTable *, zend_bool) */
1574 PHP_HTTP_API void _http_get_request_headers_ex(HashTable *headers, zend_bool prettify TSRMLS_DC)
1575 {
1576 char *key = NULL;
1577 long idx = 0;
1578 zval array;
1579
1580 Z_ARRVAL(array) = headers;
1581
1582 FOREACH_HASH_KEY(HTTP_SERVER_VARS, key, idx) {
1583 if (key && !strncmp(key, "HTTP_", 5)) {
1584 zval **header;
1585
1586 if (prettify) {
1587 key = pretty_key(key + 5, strlen(key) - 5, 1, 1);
1588 }
1589
1590 zend_hash_get_current_data(HTTP_SERVER_VARS, (void **) &header);
1591 add_assoc_stringl(&array, key, Z_STRVAL_PP(header), Z_STRLEN_PP(header), 1);
1592 key = NULL;
1593 }
1594 }
1595 }
1596 /* }}} */
1597
1598 /* {{{ STATUS http_urlencode_hash_ex(HashTable *, int, char **, size_t *) */
1599 PHP_HTTP_API STATUS _http_urlencode_hash_ex(HashTable *hash, int override_argsep,
1600 char *pre_encoded_data, size_t pre_encoded_len,
1601 char **encoded_data, size_t *encoded_len TSRMLS_DC)
1602 {
1603 smart_str qstr = {0};
1604
1605 if (override_argsep) {
1606 HTTP_URL_ARGSEP_OVERRIDE;
1607 }
1608
1609 if (pre_encoded_len && pre_encoded_data) {
1610 smart_str_appendl(&qstr, pre_encoded_data, pre_encoded_len);
1611 }
1612
1613 if (SUCCESS != php_url_encode_hash_ex(hash, &qstr, NULL, 0, NULL, 0, NULL, 0, NULL TSRMLS_CC)) {
1614 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't encode query data");
1615 if (qstr.c) {
1616 efree(qstr.c);
1617 }
1618 if (override_argsep) {
1619 HTTP_URL_ARGSEP_RESTORE;
1620 }
1621 return FAILURE;
1622 }
1623
1624 if (override_argsep) {
1625 HTTP_URL_ARGSEP_RESTORE;
1626 }
1627
1628 smart_str_0(&qstr);
1629
1630 *encoded_data = qstr.c;
1631 if (encoded_len) {
1632 *encoded_len = qstr.len;
1633 }
1634
1635 return SUCCESS;
1636 }
1637 /* }}} */
1638
1639 /* {{{ STATUS http_auth_header(char *, char*) */
1640 PHP_HTTP_API STATUS _http_auth_header(const char *type, const char *realm TSRMLS_DC)
1641 {
1642 char realm_header[1024] = {0};
1643 snprintf(realm_header, 1023, "WWW-Authenticate: %s realm=\"%s\"", type, realm);
1644 return http_send_status_header(401, realm_header);
1645 }
1646 /* }}} */
1647
1648 /* {{{ STATUS http_auth_credentials(char **, char **) */
1649 PHP_HTTP_API STATUS _http_auth_credentials(char **user, char **pass TSRMLS_DC)
1650 {
1651 if (strncmp(sapi_module.name, "isapi", 5)) {
1652 zval *zuser, *zpass;
1653
1654 HTTP_GSC(zuser, "PHP_AUTH_USER", FAILURE);
1655 HTTP_GSC(zpass, "PHP_AUTH_PW", FAILURE);
1656
1657 *user = estrndup(Z_STRVAL_P(zuser), Z_STRLEN_P(zuser));
1658 *pass = estrndup(Z_STRVAL_P(zpass), Z_STRLEN_P(zpass));
1659
1660 return SUCCESS;
1661 } else {
1662 zval *zauth = NULL;
1663 HTTP_GSC(zauth, "HTTP_AUTHORIZATION", FAILURE);
1664 {
1665 char *decoded, *colon;
1666 int decoded_len;
1667 decoded = php_base64_decode(Z_STRVAL_P(zauth), Z_STRLEN_P(zauth),
1668 &decoded_len);
1669
1670 if (colon = strchr(decoded + 6, ':')) {
1671 *user = estrndup(decoded + 6, colon - decoded - 6);
1672 *pass = estrndup(colon + 1, decoded + decoded_len - colon - 6 - 1);
1673
1674 return SUCCESS;
1675 } else {
1676 return FAILURE;
1677 }
1678 }
1679 }
1680 }
1681 /* }}} */
1682
1683 #ifndef ZEND_ENGINE_2
1684 /* {{{ php_url_encode_hash
1685 Author: Sara Golemon <pollita@php.net> */
1686 PHP_HTTP_API STATUS php_url_encode_hash_ex(HashTable *ht, smart_str *formstr,
1687 const char *num_prefix, int num_prefix_len,
1688 const char *key_prefix, int key_prefix_len,
1689 const char *key_suffix, int key_suffix_len,
1690 zval *type TSRMLS_DC)
1691 {
1692 char *arg_sep = NULL, *key = NULL, *ekey, *newprefix, *p;
1693 int arg_sep_len, key_len, ekey_len, key_type, newprefix_len;
1694 ulong idx;
1695 zval **zdata = NULL, *copyzval;
1696
1697 if (!ht) {
1698 return FAILURE;
1699 }
1700
1701 if (ht->nApplyCount > 0) {
1702 /* Prevent recursion */
1703 return SUCCESS;
1704 }
1705
1706 arg_sep = INI_STR("arg_separator.output");
1707 if (!arg_sep || !strlen(arg_sep)) {
1708 arg_sep = HTTP_URL_ARGSEP_DEFAULT;
1709 }
1710 arg_sep_len = strlen(arg_sep);
1711
1712 for (zend_hash_internal_pointer_reset(ht);
1713 (key_type = zend_hash_get_current_key_ex(ht, &key, &key_len, &idx, 0, NULL)) != HASH_KEY_NON_EXISTANT;
1714 zend_hash_move_forward(ht)
1715 ) {
1716 if (key_type == HASH_KEY_IS_STRING && key_len && key[key_len-1] == '\0') {
1717 /* We don't want that trailing NULL */
1718 key_len -= 1;
1719 }
1720
1721 #ifdef ZEND_ENGINE_2
1722 /* handling for private & protected object properties */
1723 if (key && *key == '\0' && type != NULL) {
1724 char *tmp;
1725
1726 zend_object *zobj = zend_objects_get_address(type TSRMLS_CC);
1727 if (zend_check_property_access(zobj, key TSRMLS_CC) != SUCCESS) {
1728 /* private or protected property access outside of the class */
1729 continue;
1730 }
1731 zend_unmangle_property_name(key, &tmp, &key);
1732 key_len = strlen(key);
1733 }
1734 #endif
1735
1736 if (zend_hash_get_current_data_ex(ht, (void **)&zdata, NULL) == FAILURE || !zdata || !(*zdata)) {
1737 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error traversing form data array.");
1738 return FAILURE;
1739 }
1740 if (Z_TYPE_PP(zdata) == IS_ARRAY || Z_TYPE_PP(zdata) == IS_OBJECT) {
1741 if (key_type == HASH_KEY_IS_STRING) {
1742 ekey = php_url_encode(key, key_len, &ekey_len);
1743 newprefix_len = key_suffix_len + ekey_len + key_prefix_len + 1;
1744 newprefix = emalloc(newprefix_len + 1);
1745 p = newprefix;
1746
1747 if (key_prefix) {
1748 memcpy(p, key_prefix, key_prefix_len);
1749 p += key_prefix_len;
1750 }
1751
1752 memcpy(p, ekey, ekey_len);
1753 p += ekey_len;
1754 efree(ekey);
1755
1756 if (key_suffix) {
1757 memcpy(p, key_suffix, key_suffix_len);
1758 p += key_suffix_len;
1759 }
1760
1761 *(p++) = '[';
1762 *p = '\0';
1763 } else {
1764 /* Is an integer key */
1765 ekey_len = spprintf(&ekey, 12, "%ld", idx);
1766 newprefix_len = key_prefix_len + num_prefix_len + ekey_len + key_suffix_len + 1;
1767 newprefix = emalloc(newprefix_len + 1);
1768 p = newprefix;
1769
1770 if (key_prefix) {
1771 memcpy(p, key_prefix, key_prefix_len);
1772 p += key_prefix_len;
1773 }
1774
1775 memcpy(p, num_prefix, num_prefix_len);
1776 p += num_prefix_len;
1777
1778 memcpy(p, ekey, ekey_len);
1779 p += ekey_len;
1780 efree(ekey);
1781
1782 if (key_suffix) {
1783 memcpy(p, key_suffix, key_suffix_len);
1784 p += key_suffix_len;
1785 }
1786 *(p++) = '[';
1787 *p = '\0';
1788 }
1789 ht->nApplyCount++;
1790 php_url_encode_hash_ex(HASH_OF(*zdata), formstr, NULL, 0, newprefix, newprefix_len, "]", 1, (Z_TYPE_PP(zdata) == IS_OBJECT ? *zdata : NULL) TSRMLS_CC);
1791 ht->nApplyCount--;
1792 efree(newprefix);
1793 } else if (Z_TYPE_PP(zdata) == IS_NULL || Z_TYPE_PP(zdata) == IS_RESOURCE) {
1794 /* Skip these types */
1795 continue;
1796 } else {
1797 if (formstr->len) {
1798 smart_str_appendl(formstr, arg_sep, arg_sep_len);
1799 }
1800 /* Simple key=value */
1801 smart_str_appendl(formstr, key_prefix, key_prefix_len);
1802 if (key_type == HASH_KEY_IS_STRING) {
1803 ekey = php_url_encode(key, key_len, &ekey_len);
1804 smart_str_appendl(formstr, ekey, ekey_len);
1805 efree(ekey);
1806 } else {
1807 /* Numeric key */
1808 if (num_prefix) {
1809 smart_str_appendl(formstr, num_prefix, num_prefix_len);
1810 }
1811 ekey_len = spprintf(&ekey, 12, "%ld", idx);
1812 smart_str_appendl(formstr, ekey, ekey_len);
1813 efree(ekey);
1814 }
1815 smart_str_appendl(formstr, key_suffix, key_suffix_len);
1816 smart_str_appendl(formstr, "=", 1);
1817 switch (Z_TYPE_PP(zdata)) {
1818 case IS_STRING:
1819 ekey = php_url_encode(Z_STRVAL_PP(zdata), Z_STRLEN_PP(zdata), &ekey_len);
1820 break;
1821 case IS_LONG:
1822 case IS_BOOL:
1823 ekey_len = spprintf(&ekey, 12, "%ld", Z_LVAL_PP(zdata));
1824 break;
1825 case IS_DOUBLE:
1826 ekey_len = spprintf(&ekey, 48, "%.*G", (int) EG(precision), Z_DVAL_PP(zdata));
1827 break;
1828 default:
1829 /* fall back on convert to string */
1830 MAKE_STD_ZVAL(copyzval);
1831 *copyzval = **zdata;
1832 zval_copy_ctor(copyzval);
1833 convert_to_string_ex(&copyzval);
1834 ekey = php_url_encode(Z_STRVAL_P(copyzval), Z_STRLEN_P(copyzval), &ekey_len);
1835 zval_ptr_dtor(&copyzval);
1836 }
1837 smart_str_appendl(formstr, ekey, ekey_len);
1838 efree(ekey);
1839 }
1840 }
1841
1842 return SUCCESS;
1843 }
1844 /* }}} */
1845 #endif /* !ZEND_ENDGINE_2 */
1846
1847 /* }}} public API */
1848
1849 /*
1850 * Local variables:
1851 * tab-width: 4
1852 * c-basic-offset: 4
1853 * End:
1854 * vim600: noet sw=4 ts=4 fdm=marker
1855 * vim<600: noet sw=4 ts=4
1856 */
1857