1/*
2  +----------------------------------------------------------------------+
3  | PHP Version 7                                                        |
4  +----------------------------------------------------------------------+
5  | Copyright (c) 1997-2015 The PHP Group                                |
6  +----------------------------------------------------------------------+
7  | This source file is subject to version 3.01 of the PHP license,      |
8  | that is bundled with this package in the file LICENSE, and is        |
9  | available through the world-wide-web at the following url:           |
10  | http://www.php.net/license/3_01.txt                                  |
11  | If you did not receive a copy of the PHP license and are unable to   |
12  | obtain it through the world-wide-web, please send a note to          |
13  | license@php.net so we can mail you a copy immediately.               |
14  +----------------------------------------------------------------------+
15  | Authors: Wez Furlong <wez@thebrainroom.com>                          |
16  |          Sara Golemon <pollita@php.net>                              |
17  +----------------------------------------------------------------------+
18*/
19
20/* $Id$ */
21
22#include "php.h"
23#include "php_globals.h"
24#include "ext/standard/flock_compat.h"
25#include "ext/standard/file.h"
26#include "ext/standard/php_filestat.h"
27#include "php_open_temporary_file.h"
28#include "ext/standard/basic_functions.h"
29#include "php_ini.h"
30#include "streamsfuncs.h"
31#include "php_network.h"
32#include "php_string.h"
33
34#ifndef PHP_WIN32
35#define php_select(m, r, w, e, t)   select(m, r, w, e, t)
36typedef unsigned long long php_timeout_ull;
37#else
38#include "win32/select.h"
39#include "win32/sockets.h"
40typedef unsigned __int64 php_timeout_ull;
41#endif
42
43#define GET_CTX_OPT(stream, wrapper, name, val) (PHP_STREAM_CONTEXT(stream) && NULL != (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), wrapper, name)))
44
45static php_stream_context *decode_context_param(zval *contextresource);
46
47/* Streams based network functions */
48
49#if HAVE_SOCKETPAIR
50/* {{{ proto array stream_socket_pair(int domain, int type, int protocol)
51   Creates a pair of connected, indistinguishable socket streams */
52PHP_FUNCTION(stream_socket_pair)
53{
54    zend_long domain, type, protocol;
55    php_stream *s1, *s2;
56    php_socket_t pair[2];
57
58    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "lll",
59            &domain, &type, &protocol)) {
60        RETURN_FALSE;
61    }
62
63    if (0 != socketpair((int)domain, (int)type, (int)protocol, pair)) {
64        char errbuf[256];
65        php_error_docref(NULL, E_WARNING, "failed to create sockets: [%d]: %s",
66            php_socket_errno(), php_socket_strerror(php_socket_errno(), errbuf, sizeof(errbuf)));
67        RETURN_FALSE;
68    }
69
70    array_init(return_value);
71
72    s1 = php_stream_sock_open_from_socket(pair[0], 0);
73    s2 = php_stream_sock_open_from_socket(pair[1], 0);
74
75    /* set the __exposed flag.
76     * php_stream_to_zval() does, add_next_index_resource() does not */
77    php_stream_auto_cleanup(s1);
78    php_stream_auto_cleanup(s2);
79
80    add_next_index_resource(return_value, s1->res);
81    add_next_index_resource(return_value, s2->res);
82}
83/* }}} */
84#endif
85
86/* {{{ proto resource stream_socket_client(string remoteaddress [, long &errcode [, string &errstring [, double timeout [, long flags [, resource context]]]]])
87   Open a client connection to a remote address */
88PHP_FUNCTION(stream_socket_client)
89{
90    zend_string *host;
91    zval *zerrno = NULL, *zerrstr = NULL, *zcontext = NULL;
92    double timeout = (double)FG(default_socket_timeout);
93    php_timeout_ull conv;
94    struct timeval tv;
95    char *hashkey = NULL;
96    php_stream *stream = NULL;
97    int err;
98    zend_long flags = PHP_STREAM_CLIENT_CONNECT;
99    zend_string *errstr = NULL;
100    php_stream_context *context = NULL;
101
102    RETVAL_FALSE;
103
104    if (zend_parse_parameters(ZEND_NUM_ARGS(), "S|z/z/dlr", &host, &zerrno, &zerrstr, &timeout, &flags, &zcontext) == FAILURE) {
105        RETURN_FALSE;
106    }
107
108    context = php_stream_context_from_zval(zcontext, flags & PHP_FILE_NO_DEFAULT_CONTEXT);
109
110    if (flags & PHP_STREAM_CLIENT_PERSISTENT) {
111        spprintf(&hashkey, 0, "stream_socket_client__%s", ZSTR_VAL(host));
112    }
113
114    /* prepare the timeout value for use */
115    conv = (php_timeout_ull) (timeout * 1000000.0);
116#ifdef PHP_WIN32
117    tv.tv_sec = (long)(conv / 1000000);
118    tv.tv_usec =(long)(conv % 1000000);
119#else
120    tv.tv_sec = conv / 1000000;
121    tv.tv_usec = conv % 1000000;
122#endif
123    if (zerrno) {
124        zval_dtor(zerrno);
125        ZVAL_LONG(zerrno, 0);
126    }
127    if (zerrstr) {
128        zval_dtor(zerrstr);
129        ZVAL_EMPTY_STRING(zerrstr);
130    }
131
132    stream = php_stream_xport_create(ZSTR_VAL(host), ZSTR_LEN(host), REPORT_ERRORS,
133            STREAM_XPORT_CLIENT | (flags & PHP_STREAM_CLIENT_CONNECT ? STREAM_XPORT_CONNECT : 0) |
134            (flags & PHP_STREAM_CLIENT_ASYNC_CONNECT ? STREAM_XPORT_CONNECT_ASYNC : 0),
135            hashkey, &tv, context, &errstr, &err);
136
137
138    if (stream == NULL) {
139        /* host might contain binary characters */
140        zend_string *quoted_host = php_addslashes(host, 0);
141
142        php_error_docref(NULL, E_WARNING, "unable to connect to %s (%s)", ZSTR_VAL(quoted_host), errstr == NULL ? "Unknown error" : ZSTR_VAL(errstr));
143        zend_string_release(quoted_host);
144    }
145
146    if (hashkey) {
147        efree(hashkey);
148    }
149
150    if (stream == NULL) {
151        if (zerrno) {
152            zval_dtor(zerrno);
153            ZVAL_LONG(zerrno, err);
154        }
155        if (zerrstr && errstr) {
156            zval_dtor(zerrstr);
157            ZVAL_STR(zerrstr, errstr);
158        } else if (errstr) {
159            zend_string_release(errstr);
160        }
161        RETURN_FALSE;
162    }
163
164    if (errstr) {
165        zend_string_release(errstr);
166    }
167
168    php_stream_to_zval(stream, return_value);
169
170}
171/* }}} */
172
173/* {{{ proto resource stream_socket_server(string localaddress [, long &errcode [, string &errstring [, long flags [, resource context]]]])
174   Create a server socket bound to localaddress */
175PHP_FUNCTION(stream_socket_server)
176{
177    char *host;
178    size_t host_len;
179    zval *zerrno = NULL, *zerrstr = NULL, *zcontext = NULL;
180    php_stream *stream = NULL;
181    int err = 0;
182    zend_long flags = STREAM_XPORT_BIND | STREAM_XPORT_LISTEN;
183    zend_string *errstr = NULL;
184    php_stream_context *context = NULL;
185
186    RETVAL_FALSE;
187
188    if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|z/z/lr", &host, &host_len, &zerrno, &zerrstr, &flags, &zcontext) == FAILURE) {
189        RETURN_FALSE;
190    }
191
192    context = php_stream_context_from_zval(zcontext, flags & PHP_FILE_NO_DEFAULT_CONTEXT);
193
194    if (context) {
195        GC_REFCOUNT(context->res)++;
196    }
197
198    if (zerrno) {
199        zval_dtor(zerrno);
200        ZVAL_LONG(zerrno, 0);
201    }
202    if (zerrstr) {
203        zval_dtor(zerrstr);
204        ZVAL_EMPTY_STRING(zerrstr);
205    }
206
207    stream = php_stream_xport_create(host, host_len, REPORT_ERRORS,
208            STREAM_XPORT_SERVER | (int)flags,
209            NULL, NULL, context, &errstr, &err);
210
211    if (stream == NULL) {
212        php_error_docref(NULL, E_WARNING, "unable to connect to %s (%s)", host, errstr == NULL ? "Unknown error" : ZSTR_VAL(errstr));
213    }
214
215    if (stream == NULL) {
216        if (zerrno) {
217            zval_dtor(zerrno);
218            ZVAL_LONG(zerrno, err);
219        }
220        if (zerrstr && errstr) {
221            zval_dtor(zerrstr);
222            ZVAL_STR(zerrstr, errstr);
223        } else if (errstr) {
224            zend_string_release(errstr);
225        }
226        RETURN_FALSE;
227    }
228
229    if (errstr) {
230        zend_string_release(errstr);
231    }
232
233    php_stream_to_zval(stream, return_value);
234}
235/* }}} */
236
237/* {{{ proto resource stream_socket_accept(resource serverstream, [ double timeout [, string &peername ]])
238   Accept a client connection from a server socket */
239PHP_FUNCTION(stream_socket_accept)
240{
241    double timeout = (double)FG(default_socket_timeout);
242    zval *zpeername = NULL;
243    zend_string *peername = NULL;
244    php_timeout_ull conv;
245    struct timeval tv;
246    php_stream *stream = NULL, *clistream = NULL;
247    zval *zstream;
248    zend_string *errstr = NULL;
249
250    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|dz/", &zstream, &timeout, &zpeername) == FAILURE) {
251        RETURN_FALSE;
252    }
253
254    php_stream_from_zval(stream, zstream);
255
256    /* prepare the timeout value for use */
257    conv = (php_timeout_ull) (timeout * 1000000.0);
258#ifdef PHP_WIN32
259    tv.tv_sec = (long)(conv / 1000000);
260    tv.tv_usec = (long)(conv % 1000000);
261#else
262    tv.tv_sec = conv / 1000000;
263    tv.tv_usec = conv % 1000000;
264#endif
265    if (zpeername) {
266        zval_dtor(zpeername);
267        ZVAL_NULL(zpeername);
268    }
269
270    if (0 == php_stream_xport_accept(stream, &clistream,
271                zpeername ? &peername : NULL,
272                NULL, NULL,
273                &tv, &errstr
274                ) && clistream) {
275
276        if (peername) {
277            ZVAL_STR(zpeername, peername);
278        }
279        php_stream_to_zval(clistream, return_value);
280    } else {
281        php_error_docref(NULL, E_WARNING, "accept failed: %s", errstr ? ZSTR_VAL(errstr) : "Unknown error");
282        RETVAL_FALSE;
283    }
284
285    if (errstr) {
286        zend_string_release(errstr);
287    }
288}
289/* }}} */
290
291/* {{{ proto string stream_socket_get_name(resource stream, bool want_peer)
292   Returns either the locally bound or remote name for a socket stream */
293PHP_FUNCTION(stream_socket_get_name)
294{
295    php_stream *stream;
296    zval *zstream;
297    zend_bool want_peer;
298    zend_string *name = NULL;
299
300    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rb", &zstream, &want_peer) == FAILURE) {
301        RETURN_FALSE;
302    }
303
304    php_stream_from_zval(stream, zstream);
305
306    if (0 != php_stream_xport_get_name(stream, want_peer,
307                &name,
308                NULL, NULL
309                )) {
310        RETURN_FALSE;
311    }
312
313    RETVAL_STR(name);
314}
315/* }}} */
316
317/* {{{ proto long stream_socket_sendto(resouce stream, string data [, long flags [, string target_addr]])
318   Send data to a socket stream.  If target_addr is specified it must be in dotted quad (or [ipv6]) format */
319PHP_FUNCTION(stream_socket_sendto)
320{
321    php_stream *stream;
322    zval *zstream;
323    zend_long flags = 0;
324    char *data, *target_addr = NULL;
325    size_t datalen, target_addr_len = 0;
326    php_sockaddr_storage sa;
327    socklen_t sl = 0;
328
329    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs|ls", &zstream, &data, &datalen, &flags, &target_addr, &target_addr_len) == FAILURE) {
330        RETURN_FALSE;
331    }
332    php_stream_from_zval(stream, zstream);
333
334    if (target_addr_len) {
335        /* parse the address */
336        if (FAILURE == php_network_parse_network_address_with_port(target_addr, target_addr_len, (struct sockaddr*)&sa, &sl)) {
337            php_error_docref(NULL, E_WARNING, "Failed to parse `%s' into a valid network address", target_addr);
338            RETURN_FALSE;
339        }
340    }
341
342    RETURN_LONG(php_stream_xport_sendto(stream, data, datalen, (int)flags, target_addr ? &sa : NULL, sl));
343}
344/* }}} */
345
346/* {{{ proto string stream_socket_recvfrom(resource stream, long amount [, long flags [, string &remote_addr]])
347   Receives data from a socket stream */
348PHP_FUNCTION(stream_socket_recvfrom)
349{
350    php_stream *stream;
351    zval *zstream, *zremote = NULL;
352    zend_string *remote_addr = NULL;
353    zend_long to_read = 0;
354    zend_string *read_buf;
355    zend_long flags = 0;
356    int recvd;
357
358    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl|lz/", &zstream, &to_read, &flags, &zremote) == FAILURE) {
359        RETURN_FALSE;
360    }
361
362    php_stream_from_zval(stream, zstream);
363
364    if (zremote) {
365        zval_dtor(zremote);
366        ZVAL_NULL(zremote);
367    }
368
369    if (to_read <= 0) {
370        php_error_docref(NULL, E_WARNING, "Length parameter must be greater than 0");
371        RETURN_FALSE;
372    }
373
374    read_buf = zend_string_alloc(to_read, 0);
375
376    recvd = php_stream_xport_recvfrom(stream, ZSTR_VAL(read_buf), to_read, (int)flags, NULL, NULL,
377            zremote ? &remote_addr : NULL
378            );
379
380    if (recvd >= 0) {
381        if (zremote) {
382            ZVAL_STR(zremote, remote_addr);
383        }
384        ZSTR_VAL(read_buf)[recvd] = '\0';
385        ZSTR_LEN(read_buf) = recvd;
386        RETURN_NEW_STR(read_buf);
387    }
388
389    zend_string_free(read_buf);
390    RETURN_FALSE;
391}
392/* }}} */
393
394/* {{{ proto string stream_get_contents(resource source [, long maxlen [, long offset]])
395   Reads all remaining bytes (or up to maxlen bytes) from a stream and returns them as a string. */
396PHP_FUNCTION(stream_get_contents)
397{
398    php_stream  *stream;
399    zval        *zsrc;
400    zend_long       maxlen      = (ssize_t) PHP_STREAM_COPY_ALL,
401                desiredpos  = -1L;
402    zend_string *contents;
403
404    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|ll", &zsrc, &maxlen, &desiredpos) == FAILURE) {
405        RETURN_FALSE;
406    }
407
408    php_stream_from_zval(stream, zsrc);
409
410    if (desiredpos >= 0) {
411        int     seek_res = 0;
412        zend_off_t  position;
413
414        position = php_stream_tell(stream);
415        if (position >= 0 && desiredpos > position) {
416            /* use SEEK_CUR to allow emulation in streams that don't support seeking */
417            seek_res = php_stream_seek(stream, desiredpos - position, SEEK_CUR);
418        } else if (desiredpos < position)  {
419            /* desired position before position or error on tell */
420            seek_res = php_stream_seek(stream, desiredpos, SEEK_SET);
421        }
422
423        if (seek_res != 0) {
424            php_error_docref(NULL, E_WARNING,
425                "Failed to seek to position %pd in the stream", desiredpos);
426            RETURN_FALSE;
427        }
428    }
429
430    if (maxlen > INT_MAX) {
431        php_error_docref(NULL, E_WARNING, "maxlen truncated from %pd to %d bytes", maxlen, INT_MAX);
432        maxlen = INT_MAX;
433    }
434    if ((contents = php_stream_copy_to_mem(stream, maxlen, 0))) {
435        RETURN_STR(contents);
436    } else {
437        RETURN_EMPTY_STRING();
438    }
439}
440/* }}} */
441
442/* {{{ proto long stream_copy_to_stream(resource source, resource dest [, long maxlen [, long pos]])
443   Reads up to maxlen bytes from source stream and writes them to dest stream. */
444PHP_FUNCTION(stream_copy_to_stream)
445{
446    php_stream *src, *dest;
447    zval *zsrc, *zdest;
448    zend_long maxlen = PHP_STREAM_COPY_ALL, pos = 0;
449    size_t len;
450    int ret;
451
452    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr|ll", &zsrc, &zdest, &maxlen, &pos) == FAILURE) {
453        RETURN_FALSE;
454    }
455
456    php_stream_from_zval(src, zsrc);
457    php_stream_from_zval(dest, zdest);
458
459    if (pos > 0 && php_stream_seek(src, pos, SEEK_SET) < 0) {
460        php_error_docref(NULL, E_WARNING, "Failed to seek to position " ZEND_LONG_FMT " in the stream", pos);
461        RETURN_FALSE;
462    }
463
464    ret = php_stream_copy_to_stream_ex(src, dest, maxlen, &len);
465
466    if (ret != SUCCESS) {
467        RETURN_FALSE;
468    }
469    RETURN_LONG(len);
470}
471/* }}} */
472
473/* {{{ proto array stream_get_meta_data(resource fp)
474    Retrieves header/meta data from streams/file pointers */
475PHP_FUNCTION(stream_get_meta_data)
476{
477    zval *arg1;
478    php_stream *stream;
479
480    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &arg1) == FAILURE) {
481        return;
482    }
483    php_stream_from_zval(stream, arg1);
484
485    array_init(return_value);
486
487    if (!Z_ISUNDEF(stream->wrapperdata)) {
488        Z_ADDREF_P(&stream->wrapperdata);
489        add_assoc_zval(return_value, "wrapper_data", &stream->wrapperdata);
490    }
491    if (stream->wrapper) {
492        add_assoc_string(return_value, "wrapper_type", (char *)stream->wrapper->wops->label);
493    }
494    add_assoc_string(return_value, "stream_type", (char *)stream->ops->label);
495
496    add_assoc_string(return_value, "mode", stream->mode);
497
498#if 0   /* TODO: needs updating for new filter API */
499    if (stream->filterhead) {
500        php_stream_filter *filter;
501
502        MAKE_STD_ZVAL(newval);
503        array_init(newval);
504
505        for (filter = stream->filterhead; filter != NULL; filter = filter->next) {
506            add_next_index_string(newval, (char *)filter->fops->label);
507        }
508
509        add_assoc_zval(return_value, "filters", newval);
510    }
511#endif
512
513    add_assoc_long(return_value, "unread_bytes", stream->writepos - stream->readpos);
514
515    add_assoc_bool(return_value, "seekable", (stream->ops->seek) && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0);
516    if (stream->orig_path) {
517        add_assoc_string(return_value, "uri", stream->orig_path);
518    }
519
520    if (!php_stream_populate_meta_data(stream, return_value)) {
521        add_assoc_bool(return_value, "timed_out", 0);
522        add_assoc_bool(return_value, "blocked", 1);
523        add_assoc_bool(return_value, "eof", php_stream_eof(stream));
524    }
525
526}
527/* }}} */
528
529/* {{{ proto array stream_get_transports()
530   Retrieves list of registered socket transports */
531PHP_FUNCTION(stream_get_transports)
532{
533    HashTable *stream_xport_hash;
534    zend_string *stream_xport;
535
536    if (zend_parse_parameters_none() == FAILURE) {
537        return;
538    }
539
540    if ((stream_xport_hash = php_stream_xport_get_hash())) {
541        array_init(return_value);
542        ZEND_HASH_FOREACH_STR_KEY(stream_xport_hash, stream_xport) {
543            add_next_index_str(return_value, zend_string_copy(stream_xport));
544        } ZEND_HASH_FOREACH_END();
545    } else {
546        RETURN_FALSE;
547    }
548}
549/* }}} */
550
551/* {{{ proto array stream_get_wrappers()
552    Retrieves list of registered stream wrappers */
553PHP_FUNCTION(stream_get_wrappers)
554{
555    HashTable *url_stream_wrappers_hash;
556    zend_string *stream_protocol;
557
558    if (zend_parse_parameters_none() == FAILURE) {
559        return;
560    }
561
562    if ((url_stream_wrappers_hash = php_stream_get_url_stream_wrappers_hash())) {
563        array_init(return_value);
564        ZEND_HASH_FOREACH_STR_KEY(url_stream_wrappers_hash, stream_protocol) {
565            if (stream_protocol) {
566                add_next_index_str(return_value, zend_string_copy(stream_protocol));
567            }
568        } ZEND_HASH_FOREACH_END();
569    } else {
570        RETURN_FALSE;
571    }
572
573}
574/* }}} */
575
576/* {{{ stream_select related functions */
577static int stream_array_to_fd_set(zval *stream_array, fd_set *fds, php_socket_t *max_fd)
578{
579    zval *elem;
580    php_stream *stream;
581    int cnt = 0;
582
583    if (Z_TYPE_P(stream_array) != IS_ARRAY) {
584        return 0;
585    }
586
587    ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(stream_array), elem) {
588        /* Temporary int fd is needed for the STREAM data type on windows, passing this_fd directly to php_stream_cast()
589            would eventually bring a wrong result on x64. php_stream_cast() casts to int internally, and this will leave
590            the higher bits of a SOCKET variable uninitialized on systems with little endian. */
591        php_socket_t this_fd;
592
593        php_stream_from_zval_no_verify(stream, elem);
594        if (stream == NULL) {
595            continue;
596        }
597        /* get the fd.
598         * NB: Most other code will NOT use the PHP_STREAM_CAST_INTERNAL flag
599         * when casting.  It is only used here so that the buffered data warning
600         * is not displayed.
601         * */
602        if (SUCCESS == php_stream_cast(stream, PHP_STREAM_AS_FD_FOR_SELECT | PHP_STREAM_CAST_INTERNAL, (void*)&this_fd, 1) && this_fd != -1) {
603
604            PHP_SAFE_FD_SET(this_fd, fds);
605
606            if (this_fd > *max_fd) {
607                *max_fd = this_fd;
608            }
609            cnt++;
610        }
611    } ZEND_HASH_FOREACH_END();
612    return cnt ? 1 : 0;
613}
614
615static int stream_array_from_fd_set(zval *stream_array, fd_set *fds)
616{
617    zval *elem, *dest_elem, new_array;
618    php_stream *stream;
619    int ret = 0;
620    zend_string *key;
621    zend_ulong num_ind;
622
623    if (Z_TYPE_P(stream_array) != IS_ARRAY) {
624        return 0;
625    }
626    ZVAL_NEW_ARR(&new_array);
627    zend_hash_init(Z_ARRVAL(new_array), zend_hash_num_elements(Z_ARRVAL_P(stream_array)), NULL, ZVAL_PTR_DTOR, 0);
628
629    ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(stream_array), num_ind, key, elem) {
630        php_socket_t this_fd;
631
632        php_stream_from_zval_no_verify(stream, elem);
633        if (stream == NULL) {
634            continue;
635        }
636        /* get the fd
637         * NB: Most other code will NOT use the PHP_STREAM_CAST_INTERNAL flag
638         * when casting.  It is only used here so that the buffered data warning
639         * is not displayed.
640         */
641        if (SUCCESS == php_stream_cast(stream, PHP_STREAM_AS_FD_FOR_SELECT | PHP_STREAM_CAST_INTERNAL, (void*)&this_fd, 1) && this_fd != SOCK_ERR) {
642            if (PHP_SAFE_FD_ISSET(this_fd, fds)) {
643                if (!key) {
644                    dest_elem = zend_hash_index_update(Z_ARRVAL(new_array), num_ind, elem);
645                } else {
646                    dest_elem = zend_hash_update(Z_ARRVAL(new_array), key, elem);
647                }
648
649                if (dest_elem) {
650                    zval_add_ref(dest_elem);
651                }
652                ret++;
653                continue;
654            }
655        }
656    } ZEND_HASH_FOREACH_END();
657
658    /* destroy old array and add new one */
659    zend_array_destroy(Z_ARR_P(stream_array));
660    Z_ARR_P(stream_array) = Z_ARR(new_array);
661
662    return ret;
663}
664
665static int stream_array_emulate_read_fd_set(zval *stream_array)
666{
667    zval *elem, *dest_elem, new_array;
668    php_stream *stream;
669    int ret = 0;
670
671    if (Z_TYPE_P(stream_array) != IS_ARRAY) {
672        return 0;
673    }
674    ZVAL_NEW_ARR(&new_array);
675    zend_hash_init(Z_ARRVAL(new_array), zend_hash_num_elements(Z_ARRVAL_P(stream_array)), NULL, ZVAL_PTR_DTOR, 0);
676
677    ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(stream_array), elem) {
678        php_stream_from_zval_no_verify(stream, elem);
679        if (stream == NULL) {
680            continue;
681        }
682        if ((stream->writepos - stream->readpos) > 0) {
683            /* allow readable non-descriptor based streams to participate in stream_select.
684             * Non-descriptor streams will only "work" if they have previously buffered the
685             * data.  Not ideal, but better than nothing.
686             * This branch of code also allows blocking streams with buffered data to
687             * operate correctly in stream_select.
688             * */
689            dest_elem = zend_hash_next_index_insert(Z_ARRVAL(new_array), elem);
690            if (dest_elem) {
691                zval_add_ref(dest_elem);
692            }
693            ret++;
694            continue;
695        }
696    } ZEND_HASH_FOREACH_END();
697
698    if (ret > 0) {
699        /* destroy old array and add new one */
700        zend_array_destroy(Z_ARR_P(stream_array));
701        Z_ARR_P(stream_array) = Z_ARR(new_array);
702    } else {
703        zend_array_destroy(Z_ARR(new_array));
704    }
705
706    return ret;
707}
708/* }}} */
709
710/* {{{ proto int stream_select(array &read_streams, array &write_streams, array &except_streams, int tv_sec[, int tv_usec])
711   Runs the select() system call on the sets of streams with a timeout specified by tv_sec and tv_usec */
712PHP_FUNCTION(stream_select)
713{
714    zval            *r_array, *w_array, *e_array, *sec = NULL;
715    struct timeval  tv;
716    struct timeval *tv_p = NULL;
717    fd_set          rfds, wfds, efds;
718    php_socket_t    max_fd = 0;
719    int             retval, sets = 0;
720    zend_long           usec = 0;
721    int             set_count, max_set_count = 0;
722
723    if (zend_parse_parameters(ZEND_NUM_ARGS(), "a/!a/!a/!z!|l", &r_array, &w_array, &e_array, &sec, &usec) == FAILURE)
724        return;
725
726    FD_ZERO(&rfds);
727    FD_ZERO(&wfds);
728    FD_ZERO(&efds);
729
730    if (r_array != NULL) {
731        set_count = stream_array_to_fd_set(r_array, &rfds, &max_fd);
732        if (set_count > max_set_count)
733            max_set_count = set_count;
734        sets += set_count;
735    }
736
737    if (w_array != NULL) {
738        set_count = stream_array_to_fd_set(w_array, &wfds, &max_fd);
739        if (set_count > max_set_count)
740            max_set_count = set_count;
741        sets += set_count;
742    }
743
744    if (e_array != NULL) {
745        set_count = stream_array_to_fd_set(e_array, &efds, &max_fd);
746        if (set_count > max_set_count)
747            max_set_count = set_count;
748        sets += set_count;
749    }
750
751    if (!sets) {
752        php_error_docref(NULL, E_WARNING, "No stream arrays were passed");
753        RETURN_FALSE;
754    }
755
756    PHP_SAFE_MAX_FD(max_fd, max_set_count);
757
758    /* If seconds is not set to null, build the timeval, else we wait indefinitely */
759    if (sec != NULL) {
760        convert_to_long_ex(sec);
761
762        if (Z_LVAL_P(sec) < 0) {
763            php_error_docref(NULL, E_WARNING, "The seconds parameter must be greater than 0");
764            RETURN_FALSE;
765        } else if (usec < 0) {
766            php_error_docref(NULL, E_WARNING, "The microseconds parameter must be greater than 0");
767            RETURN_FALSE;
768        }
769
770#ifdef PHP_WIN32
771        tv.tv_sec = (long)(Z_LVAL_P(sec) + (usec / 1000000));
772        tv.tv_usec = (long)(usec % 1000000);
773#else
774        /* Solaris + BSD do not like microsecond values which are >= 1 sec */
775        if (usec > 999999) {
776            tv.tv_sec = Z_LVAL_P(sec) + (usec / 1000000);
777            tv.tv_usec = usec % 1000000;
778        } else {
779            tv.tv_sec = Z_LVAL_P(sec);
780            tv.tv_usec = usec;
781        }
782#endif
783        tv_p = &tv;
784    }
785
786    /* slight hack to support buffered data; if there is data sitting in the
787     * read buffer of any of the streams in the read array, let's pretend
788     * that we selected, but return only the readable sockets */
789    if (r_array != NULL) {
790
791        retval = stream_array_emulate_read_fd_set(r_array);
792        if (retval > 0) {
793            if (w_array != NULL) {
794                zend_hash_clean(Z_ARRVAL_P(w_array));
795            }
796            if (e_array != NULL) {
797                zend_hash_clean(Z_ARRVAL_P(e_array));
798            }
799            RETURN_LONG(retval);
800        }
801    }
802
803    retval = php_select(max_fd+1, &rfds, &wfds, &efds, tv_p);
804
805    if (retval == -1) {
806        php_error_docref(NULL, E_WARNING, "unable to select [%d]: %s (max_fd=%d)",
807                errno, strerror(errno), max_fd);
808        RETURN_FALSE;
809    }
810
811    if (r_array != NULL) stream_array_from_fd_set(r_array, &rfds);
812    if (w_array != NULL) stream_array_from_fd_set(w_array, &wfds);
813    if (e_array != NULL) stream_array_from_fd_set(e_array, &efds);
814
815    RETURN_LONG(retval);
816}
817/* }}} */
818
819/* {{{ stream_context related functions */
820static void user_space_stream_notifier(php_stream_context *context, int notifycode, int severity,
821        char *xmsg, int xcode, size_t bytes_sofar, size_t bytes_max, void * ptr)
822{
823    zval *callback = &context->notifier->ptr;
824    zval retval;
825    zval zvs[6];
826    int i;
827
828    ZVAL_LONG(&zvs[0], notifycode);
829    ZVAL_LONG(&zvs[1], severity);
830    if (xmsg) {
831        ZVAL_STRING(&zvs[2], xmsg);
832    } else {
833        ZVAL_NULL(&zvs[2]);
834    }
835    ZVAL_LONG(&zvs[3], xcode);
836    ZVAL_LONG(&zvs[4], bytes_sofar);
837    ZVAL_LONG(&zvs[5], bytes_max);
838
839    if (FAILURE == call_user_function_ex(EG(function_table), NULL, callback, &retval, 6, zvs, 0, NULL)) {
840        php_error_docref(NULL, E_WARNING, "failed to call user notifier");
841    }
842    for (i = 0; i < 6; i++) {
843        zval_ptr_dtor(&zvs[i]);
844    }
845    zval_ptr_dtor(&retval);
846}
847
848static void user_space_stream_notifier_dtor(php_stream_notifier *notifier)
849{
850    if (notifier && Z_TYPE(notifier->ptr) != IS_UNDEF) {
851        zval_ptr_dtor(&notifier->ptr);
852        ZVAL_UNDEF(&notifier->ptr);
853    }
854}
855
856static int parse_context_options(php_stream_context *context, zval *options)
857{
858    zval *wval, *oval;
859    zend_string *wkey, *okey;
860    int ret = SUCCESS;
861
862    ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(options), wkey, wval) {
863        if (wkey && Z_TYPE_P(wval) == IS_ARRAY) {
864
865            ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(wval), okey, oval) {
866                if (okey) {
867                    php_stream_context_set_option(context, ZSTR_VAL(wkey), ZSTR_VAL(okey), oval);
868                }
869            } ZEND_HASH_FOREACH_END();
870
871        } else {
872            php_error_docref(NULL, E_WARNING, "options should have the form [\"wrappername\"][\"optionname\"] = $value");
873        }
874    } ZEND_HASH_FOREACH_END();
875
876    return ret;
877}
878
879static int parse_context_params(php_stream_context *context, zval *params)
880{
881    int ret = SUCCESS;
882    zval *tmp;
883
884    if (NULL != (tmp = zend_hash_str_find(Z_ARRVAL_P(params), "notification", sizeof("notification")-1))) {
885
886        if (context->notifier) {
887            php_stream_notification_free(context->notifier);
888            context->notifier = NULL;
889        }
890
891        context->notifier = php_stream_notification_alloc();
892        context->notifier->func = user_space_stream_notifier;
893        ZVAL_COPY(&context->notifier->ptr, tmp);
894        context->notifier->dtor = user_space_stream_notifier_dtor;
895    }
896    if (NULL != (tmp = zend_hash_str_find(Z_ARRVAL_P(params), "options", sizeof("options")-1))) {
897        if (Z_TYPE_P(tmp) == IS_ARRAY) {
898            parse_context_options(context, tmp);
899        } else {
900            php_error_docref(NULL, E_WARNING, "Invalid stream/context parameter");
901        }
902    }
903
904    return ret;
905}
906
907/* given a zval which is either a stream or a context, return the underlying
908 * stream_context.  If it is a stream that does not have a context assigned, it
909 * will create and assign a context and return that.  */
910static php_stream_context *decode_context_param(zval *contextresource)
911{
912    php_stream_context *context = NULL;
913
914    context = zend_fetch_resource_ex(contextresource, NULL, php_le_stream_context());
915    if (context == NULL) {
916        php_stream *stream;
917
918        stream = zend_fetch_resource2_ex(contextresource, NULL, php_file_le_stream(), php_file_le_pstream());
919
920        if (stream) {
921            context = PHP_STREAM_CONTEXT(stream);
922            if (context == NULL) {
923                /* Only way this happens is if file is opened with NO_DEFAULT_CONTEXT
924                   param, but then something is called which requires a context.
925                   Don't give them the default one though since they already said they
926                   didn't want it. */
927                context = php_stream_context_alloc();
928                stream->ctx = context->res;
929            }
930        }
931    }
932
933    return context;
934}
935/* }}} */
936
937/* {{{ proto array stream_context_get_options(resource context|resource stream)
938   Retrieve options for a stream/wrapper/context */
939PHP_FUNCTION(stream_context_get_options)
940{
941    zval *zcontext;
942    php_stream_context *context;
943
944    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zcontext) == FAILURE) {
945        RETURN_FALSE;
946    }
947    context = decode_context_param(zcontext);
948    if (!context) {
949        php_error_docref(NULL, E_WARNING, "Invalid stream/context parameter");
950        RETURN_FALSE;
951    }
952
953    ZVAL_COPY(return_value, &context->options);
954}
955/* }}} */
956
957/* {{{ proto bool stream_context_set_option(resource context|resource stream, string wrappername, string optionname, mixed value)
958   Set an option for a wrapper */
959PHP_FUNCTION(stream_context_set_option)
960{
961    zval *options = NULL, *zcontext = NULL, *zvalue = NULL;
962    php_stream_context *context;
963    char *wrappername, *optionname;
964    size_t wrapperlen, optionlen;
965
966    if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(),
967                "rssz", &zcontext, &wrappername, &wrapperlen,
968                &optionname, &optionlen, &zvalue) == FAILURE) {
969        if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(),
970                    "ra", &zcontext, &options) == FAILURE) {
971            php_error_docref(NULL, E_WARNING, "called with wrong number or type of parameters; please RTM");
972            RETURN_FALSE;
973        }
974    }
975
976    /* figure out where the context is coming from exactly */
977    context = decode_context_param(zcontext);
978    if (!context) {
979        php_error_docref(NULL, E_WARNING, "Invalid stream/context parameter");
980        RETURN_FALSE;
981    }
982
983    if (options) {
984        /* handle the array syntax */
985        RETVAL_BOOL(parse_context_options(context, options) == SUCCESS);
986    } else {
987        php_stream_context_set_option(context, wrappername, optionname, zvalue);
988        RETVAL_TRUE;
989    }
990}
991/* }}} */
992
993/* {{{ proto bool stream_context_set_params(resource context|resource stream, array options)
994   Set parameters for a file context */
995PHP_FUNCTION(stream_context_set_params)
996{
997    zval *params, *zcontext;
998    php_stream_context *context;
999
1000    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ra", &zcontext, &params) == FAILURE) {
1001        RETURN_FALSE;
1002    }
1003
1004    context = decode_context_param(zcontext);
1005    if (!context) {
1006        php_error_docref(NULL, E_WARNING, "Invalid stream/context parameter");
1007        RETURN_FALSE;
1008    }
1009
1010    RETVAL_BOOL(parse_context_params(context, params) == SUCCESS);
1011}
1012/* }}} */
1013
1014/* {{{ proto array stream_context_get_params(resource context|resource stream)
1015   Get parameters of a file context */
1016PHP_FUNCTION(stream_context_get_params)
1017{
1018    zval *zcontext;
1019    php_stream_context *context;
1020
1021    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zcontext) == FAILURE) {
1022        RETURN_FALSE;
1023    }
1024
1025    context = decode_context_param(zcontext);
1026    if (!context) {
1027        php_error_docref(NULL, E_WARNING, "Invalid stream/context parameter");
1028        RETURN_FALSE;
1029    }
1030
1031    array_init(return_value);
1032    if (context->notifier && Z_TYPE(context->notifier->ptr) != IS_UNDEF && context->notifier->func == user_space_stream_notifier) {
1033        add_assoc_zval_ex(return_value, "notification", sizeof("notification")-1, &context->notifier->ptr);
1034        if (Z_REFCOUNTED(context->notifier->ptr)) Z_ADDREF(context->notifier->ptr);
1035    }
1036    if (Z_REFCOUNTED(context->options)) Z_ADDREF(context->options);
1037    add_assoc_zval_ex(return_value, "options", sizeof("options")-1, &context->options);
1038}
1039/* }}} */
1040
1041/* {{{ proto resource stream_context_get_default([array options])
1042   Get a handle on the default file/stream context and optionally set parameters */
1043PHP_FUNCTION(stream_context_get_default)
1044{
1045    zval *params = NULL;
1046    php_stream_context *context;
1047
1048    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|a", &params) == FAILURE) {
1049        RETURN_FALSE;
1050    }
1051
1052    if (FG(default_context) == NULL) {
1053        FG(default_context) = php_stream_context_alloc();
1054    }
1055    context = FG(default_context);
1056
1057    if (params) {
1058        parse_context_options(context, params);
1059    }
1060
1061    php_stream_context_to_zval(context, return_value);
1062}
1063/* }}} */
1064
1065/* {{{ proto resource stream_context_set_default(array options)
1066   Set default file/stream context, returns the context as a resource */
1067PHP_FUNCTION(stream_context_set_default)
1068{
1069    zval *options = NULL;
1070    php_stream_context *context;
1071
1072    if (zend_parse_parameters(ZEND_NUM_ARGS(), "a", &options) == FAILURE) {
1073        return;
1074    }
1075
1076    if (FG(default_context) == NULL) {
1077        FG(default_context) = php_stream_context_alloc();
1078    }
1079    context = FG(default_context);
1080
1081    parse_context_options(context, options);
1082
1083    php_stream_context_to_zval(context, return_value);
1084}
1085/* }}} */
1086
1087/* {{{ proto resource stream_context_create([array options[, array params]])
1088   Create a file context and optionally set parameters */
1089PHP_FUNCTION(stream_context_create)
1090{
1091    zval *options = NULL, *params = NULL;
1092    php_stream_context *context;
1093
1094    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|a!a!", &options, &params) == FAILURE) {
1095        RETURN_FALSE;
1096    }
1097
1098    context = php_stream_context_alloc();
1099
1100    if (options) {
1101        parse_context_options(context, options);
1102    }
1103
1104    if (params) {
1105        parse_context_params(context, params);
1106    }
1107
1108    RETURN_RES(context->res);
1109}
1110/* }}} */
1111
1112/* {{{ streams filter functions */
1113static void apply_filter_to_stream(int append, INTERNAL_FUNCTION_PARAMETERS)
1114{
1115    zval *zstream;
1116    php_stream *stream;
1117    char *filtername;
1118    size_t filternamelen;
1119    zend_long read_write = 0;
1120    zval *filterparams = NULL;
1121    php_stream_filter *filter = NULL;
1122    int ret;
1123
1124    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs|lz", &zstream,
1125                &filtername, &filternamelen, &read_write, &filterparams) == FAILURE) {
1126        RETURN_FALSE;
1127    }
1128
1129    php_stream_from_zval(stream, zstream);
1130
1131    if ((read_write & PHP_STREAM_FILTER_ALL) == 0) {
1132        /* Chain not specified.
1133         * Examine stream->mode to determine which filters are needed
1134         * There's no harm in attaching a filter to an unused chain,
1135         * but why waste the memory and clock cycles?
1136         */
1137        if (strchr(stream->mode, 'r') || strchr(stream->mode, '+')) {
1138            read_write |= PHP_STREAM_FILTER_READ;
1139        }
1140        if (strchr(stream->mode, 'w') || strchr(stream->mode, '+') || strchr(stream->mode, 'a')) {
1141            read_write |= PHP_STREAM_FILTER_WRITE;
1142        }
1143    }
1144
1145    if (read_write & PHP_STREAM_FILTER_READ) {
1146        filter = php_stream_filter_create(filtername, filterparams, php_stream_is_persistent(stream));
1147        if (filter == NULL) {
1148            RETURN_FALSE;
1149        }
1150
1151        if (append) {
1152            ret = php_stream_filter_append_ex(&stream->readfilters, filter);
1153        } else {
1154            ret = php_stream_filter_prepend_ex(&stream->readfilters, filter);
1155        }
1156        if (ret != SUCCESS) {
1157            php_stream_filter_remove(filter, 1);
1158            RETURN_FALSE;
1159        }
1160    }
1161
1162    if (read_write & PHP_STREAM_FILTER_WRITE) {
1163        filter = php_stream_filter_create(filtername, filterparams, php_stream_is_persistent(stream));
1164        if (filter == NULL) {
1165            RETURN_FALSE;
1166        }
1167
1168        if (append) {
1169            ret = php_stream_filter_append_ex(&stream->writefilters, filter);
1170        } else {
1171            ret = php_stream_filter_prepend_ex(&stream->writefilters, filter);
1172        }
1173        if (ret != SUCCESS) {
1174            php_stream_filter_remove(filter, 1);
1175            RETURN_FALSE;
1176        }
1177    }
1178
1179    if (filter) {
1180        filter->res = zend_register_resource(filter, php_file_le_stream_filter());
1181        GC_REFCOUNT(filter->res)++;
1182        RETURN_RES(filter->res);
1183    } else {
1184        RETURN_FALSE;
1185    }
1186}
1187/* }}} */
1188
1189/* {{{ proto resource stream_filter_prepend(resource stream, string filtername[, int read_write[, string filterparams]])
1190   Prepend a filter to a stream */
1191PHP_FUNCTION(stream_filter_prepend)
1192{
1193    apply_filter_to_stream(0, INTERNAL_FUNCTION_PARAM_PASSTHRU);
1194}
1195/* }}} */
1196
1197/* {{{ proto resource stream_filter_append(resource stream, string filtername[, int read_write[, string filterparams]])
1198   Append a filter to a stream */
1199PHP_FUNCTION(stream_filter_append)
1200{
1201    apply_filter_to_stream(1, INTERNAL_FUNCTION_PARAM_PASSTHRU);
1202}
1203/* }}} */
1204
1205/* {{{ proto bool stream_filter_remove(resource stream_filter)
1206    Flushes any data in the filter's internal buffer, removes it from the chain, and frees the resource */
1207PHP_FUNCTION(stream_filter_remove)
1208{
1209    zval *zfilter;
1210    php_stream_filter *filter;
1211
1212    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zfilter) == FAILURE) {
1213        RETURN_FALSE;
1214    }
1215
1216    filter = zend_fetch_resource(Z_RES_P(zfilter), NULL, php_file_le_stream_filter());
1217    if (!filter) {
1218        php_error_docref(NULL, E_WARNING, "Invalid resource given, not a stream filter");
1219        RETURN_FALSE;
1220    }
1221
1222    if (php_stream_filter_flush(filter, 1) == FAILURE) {
1223        php_error_docref(NULL, E_WARNING, "Unable to flush filter, not removing");
1224        RETURN_FALSE;
1225    }
1226
1227    if (zend_list_close(Z_RES_P(zfilter)) == FAILURE) {
1228        php_error_docref(NULL, E_WARNING, "Could not invalidate filter, not removing");
1229        RETURN_FALSE;
1230    } else {
1231        php_stream_filter_remove(filter, 1);
1232        RETURN_TRUE;
1233    }
1234}
1235/* }}} */
1236
1237/* {{{ proto string stream_get_line(resource stream, int maxlen [, string ending])
1238   Read up to maxlen bytes from a stream or until the ending string is found */
1239PHP_FUNCTION(stream_get_line)
1240{
1241    char *str = NULL;
1242    size_t str_len = 0;
1243    zend_long max_length;
1244    zval *zstream;
1245    zend_string *buf;
1246    php_stream *stream;
1247
1248    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl|s", &zstream, &max_length, &str, &str_len) == FAILURE) {
1249        RETURN_FALSE;
1250    }
1251
1252    if (max_length < 0) {
1253        php_error_docref(NULL, E_WARNING, "The maximum allowed length must be greater than or equal to zero");
1254        RETURN_FALSE;
1255    }
1256    if (!max_length) {
1257        max_length = PHP_SOCK_CHUNK_SIZE;
1258    }
1259
1260    php_stream_from_zval(stream, zstream);
1261
1262    if ((buf = php_stream_get_record(stream, max_length, str, str_len))) {
1263        RETURN_STR(buf);
1264    } else {
1265        RETURN_FALSE;
1266    }
1267}
1268
1269/* }}} */
1270
1271/* {{{ proto bool stream_set_blocking(resource socket, int mode)
1272   Set blocking/non-blocking mode on a socket or stream */
1273PHP_FUNCTION(stream_set_blocking)
1274{
1275    zval *arg1;
1276    zend_long block;
1277    php_stream *stream;
1278
1279    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &arg1, &block) == FAILURE) {
1280        return;
1281    }
1282
1283    php_stream_from_zval(stream, arg1);
1284
1285    if (php_stream_set_option(stream, PHP_STREAM_OPTION_BLOCKING, block ? 1 : 0, NULL) == -1) {
1286        RETURN_FALSE;
1287    }
1288
1289    RETURN_TRUE;
1290}
1291
1292/* }}} */
1293
1294/* {{{ proto bool stream_set_timeout(resource stream, int seconds [, int microseconds])
1295   Set timeout on stream read to seconds + microseonds */
1296#if HAVE_SYS_TIME_H || defined(PHP_WIN32)
1297PHP_FUNCTION(stream_set_timeout)
1298{
1299    zval *socket;
1300    zend_long seconds, microseconds = 0;
1301    struct timeval t;
1302    php_stream *stream;
1303    int argc = ZEND_NUM_ARGS();
1304
1305    if (zend_parse_parameters(argc, "rl|l", &socket, &seconds, &microseconds) == FAILURE) {
1306        return;
1307    }
1308
1309    php_stream_from_zval(stream, socket);
1310
1311#ifdef PHP_WIN32
1312    t.tv_sec = (long)seconds;
1313
1314    if (argc == 3) {
1315        t.tv_usec = (long)(microseconds % 1000000);
1316        t.tv_sec +=(long)(microseconds / 1000000);
1317    } else {
1318        t.tv_usec = 0;
1319    }
1320#else
1321    t.tv_sec = seconds;
1322
1323    if (argc == 3) {
1324        t.tv_usec = microseconds % 1000000;
1325        t.tv_sec += microseconds / 1000000;
1326    } else {
1327        t.tv_usec = 0;
1328    }
1329#endif
1330
1331    if (PHP_STREAM_OPTION_RETURN_OK == php_stream_set_option(stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &t)) {
1332        RETURN_TRUE;
1333    }
1334
1335    RETURN_FALSE;
1336}
1337#endif /* HAVE_SYS_TIME_H || defined(PHP_WIN32) */
1338/* }}} */
1339
1340/* {{{ proto int stream_set_write_buffer(resource fp, int buffer)
1341   Set file write buffer */
1342PHP_FUNCTION(stream_set_write_buffer)
1343{
1344    zval *arg1;
1345    int ret;
1346    zend_long arg2;
1347    size_t buff;
1348    php_stream *stream;
1349
1350    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &arg1, &arg2) == FAILURE) {
1351        RETURN_FALSE;
1352    }
1353
1354    php_stream_from_zval(stream, arg1);
1355
1356    buff = arg2;
1357
1358    /* if buff is 0 then set to non-buffered */
1359    if (buff == 0) {
1360        ret = php_stream_set_option(stream, PHP_STREAM_OPTION_WRITE_BUFFER, PHP_STREAM_BUFFER_NONE, NULL);
1361    } else {
1362        ret = php_stream_set_option(stream, PHP_STREAM_OPTION_WRITE_BUFFER, PHP_STREAM_BUFFER_FULL, &buff);
1363    }
1364
1365    RETURN_LONG(ret == 0 ? 0 : EOF);
1366}
1367/* }}} */
1368
1369/* {{{ proto int stream_set_chunk_size(resource fp, int chunk_size)
1370   Set the stream chunk size */
1371PHP_FUNCTION(stream_set_chunk_size)
1372{
1373    int         ret;
1374    zend_long       csize;
1375    zval        *zstream;
1376    php_stream  *stream;
1377
1378    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &zstream, &csize) == FAILURE) {
1379        RETURN_FALSE;
1380    }
1381
1382    if (csize <= 0) {
1383        php_error_docref(NULL, E_WARNING, "The chunk size must be a positive integer, given " ZEND_LONG_FMT, csize);
1384        RETURN_FALSE;
1385    }
1386    /* stream.chunk_size is actually a size_t, but php_stream_set_option
1387     * can only use an int to accept the new value and return the old one.
1388     * In any case, values larger than INT_MAX for a chunk size make no sense.
1389     */
1390    if (csize > INT_MAX) {
1391        php_error_docref(NULL, E_WARNING, "The chunk size cannot be larger than %d", INT_MAX);
1392        RETURN_FALSE;
1393    }
1394
1395    php_stream_from_zval(stream, zstream);
1396
1397    ret = php_stream_set_option(stream, PHP_STREAM_OPTION_SET_CHUNK_SIZE, (int)csize, NULL);
1398
1399    RETURN_LONG(ret > 0 ? (zend_long)ret : (zend_long)EOF);
1400}
1401/* }}} */
1402
1403/* {{{ proto int stream_set_read_buffer(resource fp, int buffer)
1404   Set file read buffer */
1405PHP_FUNCTION(stream_set_read_buffer)
1406{
1407    zval *arg1;
1408    int ret;
1409    zend_long arg2;
1410    size_t buff;
1411    php_stream *stream;
1412
1413    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &arg1, &arg2) == FAILURE) {
1414        RETURN_FALSE;
1415    }
1416
1417    php_stream_from_zval(stream, arg1);
1418
1419    buff = arg2;
1420
1421    /* if buff is 0 then set to non-buffered */
1422    if (buff == 0) {
1423        ret = php_stream_set_option(stream, PHP_STREAM_OPTION_READ_BUFFER, PHP_STREAM_BUFFER_NONE, NULL);
1424    } else {
1425        ret = php_stream_set_option(stream, PHP_STREAM_OPTION_READ_BUFFER, PHP_STREAM_BUFFER_FULL, &buff);
1426    }
1427
1428    RETURN_LONG(ret == 0 ? 0 : EOF);
1429}
1430/* }}} */
1431
1432/* {{{ proto int stream_socket_enable_crypto(resource stream, bool enable [, int cryptokind [, resource sessionstream]])
1433   Enable or disable a specific kind of crypto on the stream */
1434PHP_FUNCTION(stream_socket_enable_crypto)
1435{
1436    zend_long cryptokind = 0;
1437    zval *zstream, *zsessstream = NULL;
1438    php_stream *stream, *sessstream = NULL;
1439    zend_bool enable, cryptokindnull;
1440    int ret;
1441
1442    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rb|l!r", &zstream, &enable, &cryptokind, &cryptokindnull, &zsessstream) == FAILURE) {
1443        RETURN_FALSE;
1444    }
1445
1446    php_stream_from_zval(stream, zstream);
1447
1448    if (enable) {
1449        if (ZEND_NUM_ARGS() < 3 || cryptokindnull) {
1450            zval *val;
1451
1452            if (!GET_CTX_OPT(stream, "ssl", "crypto_method", val)) {
1453                php_error_docref(NULL, E_WARNING, "When enabling encryption you must specify the crypto type");
1454                RETURN_FALSE;
1455            }
1456
1457            cryptokind = Z_LVAL_P(val);
1458        }
1459
1460        if (zsessstream) {
1461            php_stream_from_zval(sessstream, zsessstream);
1462        }
1463
1464        if (php_stream_xport_crypto_setup(stream, cryptokind, sessstream) < 0) {
1465            RETURN_FALSE;
1466        }
1467    }
1468
1469    ret = php_stream_xport_crypto_enable(stream, enable);
1470    switch (ret) {
1471        case -1:
1472            RETURN_FALSE;
1473
1474        case 0:
1475            RETURN_LONG(0);
1476
1477        default:
1478            RETURN_TRUE;
1479    }
1480}
1481/* }}} */
1482
1483/* {{{ proto string stream_resolve_include_path(string filename)
1484Determine what file will be opened by calls to fopen() with a relative path */
1485PHP_FUNCTION(stream_resolve_include_path)
1486{
1487    char *filename;
1488    size_t filename_len;
1489    zend_string *resolved_path;
1490
1491    if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &filename, &filename_len) == FAILURE) {
1492        return;
1493    }
1494
1495    resolved_path = zend_resolve_path(filename, (int)filename_len);
1496
1497    if (resolved_path) {
1498        RETURN_STR(resolved_path);
1499    }
1500    RETURN_FALSE;
1501}
1502/* }}} */
1503
1504/* {{{ proto bool stream_is_local(resource stream|string url) U
1505*/
1506PHP_FUNCTION(stream_is_local)
1507{
1508    zval *zstream;
1509    php_stream *stream = NULL;
1510    php_stream_wrapper *wrapper = NULL;
1511
1512    if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &zstream) == FAILURE) {
1513        RETURN_FALSE;
1514    }
1515
1516    if (Z_TYPE_P(zstream) == IS_RESOURCE) {
1517        php_stream_from_zval(stream, zstream);
1518        if (stream == NULL) {
1519            RETURN_FALSE;
1520        }
1521        wrapper = stream->wrapper;
1522    } else {
1523        convert_to_string_ex(zstream);
1524
1525        wrapper = php_stream_locate_url_wrapper(Z_STRVAL_P(zstream), NULL, 0);
1526    }
1527
1528    if (!wrapper) {
1529        RETURN_FALSE;
1530    }
1531
1532    RETURN_BOOL(wrapper->is_url==0);
1533}
1534/* }}} */
1535
1536/* {{{ proto bool stream_supports_lock(resource stream)
1537   Tells whether the stream supports locking through flock(). */
1538PHP_FUNCTION(stream_supports_lock)
1539{
1540    php_stream *stream;
1541    zval *zsrc;
1542
1543    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zsrc) == FAILURE) {
1544        RETURN_FALSE;
1545    }
1546
1547    php_stream_from_zval(stream, zsrc);
1548
1549    if (!php_stream_supports_lock(stream)) {
1550        RETURN_FALSE;
1551    }
1552
1553    RETURN_TRUE;
1554}
1555
1556#ifdef HAVE_SHUTDOWN
1557/* {{{ proto int stream_socket_shutdown(resource stream, int how)
1558    causes all or part of a full-duplex connection on the socket associated
1559    with stream to be shut down.  If how is SHUT_RD,  further receptions will
1560    be disallowed. If how is SHUT_WR, further transmissions will be disallowed.
1561    If how is SHUT_RDWR,  further  receptions and transmissions will be
1562    disallowed. */
1563PHP_FUNCTION(stream_socket_shutdown)
1564{
1565    zend_long how;
1566    zval *zstream;
1567    php_stream *stream;
1568
1569    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &zstream, &how) == FAILURE) {
1570        RETURN_FALSE;
1571    }
1572
1573    if (how != STREAM_SHUT_RD &&
1574        how != STREAM_SHUT_WR &&
1575        how != STREAM_SHUT_RDWR) {
1576        RETURN_FALSE;
1577    }
1578
1579    php_stream_from_zval(stream, zstream);
1580
1581    RETURN_BOOL(php_stream_xport_shutdown(stream, (stream_shutdown_t)how) == 0);
1582}
1583/* }}} */
1584#endif
1585
1586/*
1587 * Local variables:
1588 * tab-width: 4
1589 * c-basic-offset: 4
1590 * End:
1591 * vim600: noet sw=4 ts=4 fdm=marker
1592 * vim<600: noet sw=4 ts=4
1593 */
1594
1595