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