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