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