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