/** * @brief Unsets @a index from array @a arr * @param[in,out] arr Array * @param index Index * @param flags Flags (@c PH_SEPARATE: separate array if its reference count is greater than 1; @c arr will contain the separated array) * @return Whether the operation succeeded * @retval @c FAILURE Failure, @a arr is not an array or @a index is of not supported type * @retval @c SUCCESS Success * @note @c index will be handled as follows: @c NULL is treated as an empty string, @c double values are cast to @c integer, @c bool or @c resource are treated as @c integer * @throw @c E_WARNING if @a offset is not a scalar */ int ZEPHIR_FASTCALL zephir_array_unset(zval **arr, zval *index, int flags) { HashTable *ht; if (Z_TYPE_PP(arr) != IS_ARRAY) { return 0; } if ((flags & PH_SEPARATE) == PH_SEPARATE) { SEPARATE_ZVAL(arr); } ht = Z_ARRVAL_PP(arr); switch (Z_TYPE_P(index)) { case IS_NULL: return (zend_hash_del(ht, "", 1) == SUCCESS); case IS_DOUBLE: return (zend_hash_index_del(ht, (ulong)Z_DVAL_P(index)) == SUCCESS); case IS_LONG: case IS_BOOL: case IS_RESOURCE: return (zend_hash_index_del(ht, Z_LVAL_P(index)) == SUCCESS); case IS_STRING: return (zend_symtable_del(ht, Z_STRVAL_P(index), Z_STRLEN_P(index)+1) == SUCCESS); default: zend_error(E_WARNING, "Illegal offset type"); return 0; } }
static int zephir_update_static_property_ex(zend_class_entry *scope, const char *name, int name_length, zval *value, zend_property_info **property_info) { zval garbage; zval *property; zend_class_entry *old_scope; #if PHP_VERSION_ID >= 70100 old_scope = EG(fake_scope); EG(fake_scope) = scope; #else old_scope = EG(scope); EG(scope) = scope; #endif property = zephir_std_get_static_property(scope, name, name_length, 0, property_info); #if PHP_VERSION_ID >= 70100 EG(fake_scope) = old_scope; #else EG(scope) = old_scope; #endif if (!property) { return FAILURE; } else { ZVAL_COPY_VALUE(&garbage, property); if (Z_ISREF_P(value)) { SEPARATE_ZVAL(value); } ZVAL_COPY(property, value); zval_ptr_dtor(&garbage); return SUCCESS; } }
/* {{{ php_autoglobal_merge */ static void php_autoglobal_merge(HashTable *dest, HashTable *src) { zval *src_entry, *dest_entry; zend_string *string_key; zend_ulong num_key; int globals_check = (dest == (&EG(symbol_table))); ZEND_HASH_FOREACH_KEY_VAL(src, num_key, string_key, src_entry) { if (Z_TYPE_P(src_entry) != IS_ARRAY || (string_key && (dest_entry = zend_hash_find(dest, string_key)) == NULL) || (string_key == NULL && (dest_entry = zend_hash_index_find(dest, num_key)) == NULL) || Z_TYPE_P(dest_entry) != IS_ARRAY) { if (Z_REFCOUNTED_P(src_entry)) { Z_ADDREF_P(src_entry); } if (string_key) { if (!globals_check || string_key->len != sizeof("GLOBALS") - 1 || memcmp(string_key->val, "GLOBALS", sizeof("GLOBALS") - 1)) { zend_hash_update(dest, string_key, src_entry); } else if (Z_REFCOUNTED_P(src_entry)) { Z_DELREF_P(src_entry); } } else { zend_hash_index_update(dest, num_key, src_entry); } } else { SEPARATE_ZVAL(dest_entry); php_autoglobal_merge(Z_ARRVAL_P(dest_entry), Z_ARRVAL_P(src_entry)); } } ZEND_HASH_FOREACH_END(); }
/** * @brief Updates value in @a arr at position @a index with @a value * @param[in,out] arr Array * @param index Index * @param[in,out] value Value * @param flags Flags * @return Whether the operation succeeded * @retval @c FAILURE Failure, @a arr is not an array * @retval @c SUCCESS Success * @throw @c E_WARNING if @c arr is not an array * * Equivalent to <tt>$arr[$index] = $value</tt> in PHP where @c $index is an integer. * Flags may be a bitwise OR of the following values: * @arg @c PH_CTOR: create a copy of @a value and work with that copy; @c *value will be updated with the newly constructed value * @arg @c PH_SEPARATE: separate @a arr if its reference count is greater than 1; @c *arr will contain the separated version * @arg @c PH_COPY: increment the reference count on @c **value */ int zephir_array_update_long(zval **arr, unsigned long index, zval **value, int flags){ if (Z_TYPE_PP(arr) != IS_ARRAY) { zend_error(E_WARNING, "Cannot use a scalar value as an array"); return FAILURE; } if ((flags & PH_CTOR) == PH_CTOR) { zval *new_zv; Z_DELREF_PP(value); ALLOC_ZVAL(new_zv); INIT_PZVAL_COPY(new_zv, *value); *value = new_zv; zval_copy_ctor(new_zv); } if ((flags & PH_SEPARATE) == PH_SEPARATE) { SEPARATE_ZVAL(arr); } if ((flags & PH_COPY) == PH_COPY) { Z_ADDREF_PP(value); } return zend_hash_index_update(Z_ARRVAL_PP(arr), index, value, sizeof(zval *), NULL); }
/** * @brief Unsets string @a index from array @a arr * @param[in,out] arr Array * @param index Index * @param index_length strlen(index)+1 * @param flags Flags (@c PH_SEPARATE: separate array if its reference count is greater than 1; @c arr will contain the separated array) * @return Whether the operation succeeded * @retval @c FAILURE Failure or @a arr is not an array * @retval @c SUCCESS Success */ int ZEPHIR_FASTCALL zephir_array_unset_string(zval **arr, const char *index, uint index_length, int flags) { if (Z_TYPE_PP(arr) != IS_ARRAY) { return 0; } if ((flags & PH_SEPARATE) == PH_SEPARATE) { SEPARATE_ZVAL(arr); } return zend_hash_del(Z_ARRVAL_PP(arr), index, index_length); }
/** * @brief Unsets numeric @a index from array @a arr * @param[in,out] arr Array * @param index Index * @param flags Flags (@c PH_SEPARATE: separate array if its reference count is greater than 1; @c arr will contain the separated array) * @return Whether the operation succeeded * @retval @c FAILURE Failure or @a arr is not an array * @retval @c SUCCESS Success */ int ZEPHIR_FASTCALL zephir_array_unset_long(zval **arr, unsigned long index, int flags) { if (Z_TYPE_PP(arr) != IS_ARRAY) { return 0; } if ((flags & PH_SEPARATE) == PH_SEPARATE) { SEPARATE_ZVAL(arr); } return zend_hash_index_del(Z_ARRVAL_PP(arr), index); }
/** * @brief Pushes @a value onto the end of @a arr * @param[in,out] arr Array * @param[in,out] value Value to add; reference counter of @c *value will be incrememnted * @param flags Flags (@c PH_SEPARATE: separate array if its reference count is greater than 1; @c arr will contain the separated array) * @return Whether the operation succeeded * @retval @c FAILURE Failure or @a arr is not an array * @retval @c SUCCESS Success * @throw @c E_WARNING if @a is not an array */ int zephir_array_append(zval **arr, zval *value, int flags) { if (Z_TYPE_PP(arr) != IS_ARRAY) { zend_error(E_WARNING, "Cannot use a scalar value as an array"); return FAILURE; } if ((flags & PH_SEPARATE) == PH_SEPARATE) { SEPARATE_ZVAL(arr); } Z_ADDREF_P(value); return add_next_index_zval(*arr, value); }
/** * @brief Updates value in @a arr at position @a index with @a value * @param[in,out] arr Array * @param index Index * @param[in,out] value Value * @param flags Flags * @return Whether the operation succeeded * @retval @c FAILURE Failure, @a arr is not an array or @a index is of not supported type * @retval @c SUCCESS Success * @note @c index will be handled as follows: @c NULL is treated as an empty string, @c double values are cast to @c integer, @c bool or @c resource are treated as @c integer * @throw @c E_WARNING if @a offset is not a scalar or @c arr is not an array * * Equivalent to <tt>$arr[$index] = $value</tt> in PHP. * Flags may be a bitwise OR of the following values: * @arg @c PH_CTOR: create a copy of @a value and work with that copy; @c *value will be updated with the newly constructed value * @arg @c PH_SEPARATE: separate @a arr if its reference count is greater than 1; @c *arr will contain the separated version * @arg @c PH_COPY: increment the reference count on @c **value */ int zephir_array_update_zval(zval **arr, zval *index, zval **value, int flags) { HashTable *ht; if (Z_TYPE_PP(arr) != IS_ARRAY) { zend_error(E_WARNING, "Cannot use a scalar value as an array"); return FAILURE; } if ((flags & PH_CTOR) == PH_CTOR) { zval *new_zv; Z_DELREF_PP(value); ALLOC_ZVAL(new_zv); INIT_PZVAL_COPY(new_zv, *value); *value = new_zv; zval_copy_ctor(new_zv); } if ((flags & PH_SEPARATE) == PH_SEPARATE) { SEPARATE_ZVAL(arr); } if ((flags & PH_COPY) == PH_COPY) { Z_ADDREF_PP(value); } ht = Z_ARRVAL_PP(arr); switch (Z_TYPE_P(index)) { case IS_NULL: return zend_symtable_update(ht, "", 1, value, sizeof(zval*), NULL); case IS_DOUBLE: return zend_hash_index_update(ht, (ulong)Z_DVAL_P(index), value, sizeof(zval*), NULL); case IS_LONG: case IS_BOOL: case IS_RESOURCE: return zend_hash_index_update(ht, Z_LVAL_P(index), value, sizeof(zval*), NULL); case IS_STRING: return zend_symtable_update(ht, Z_STRVAL_P(index), Z_STRLEN_P(index)+1, value, sizeof(zval*), NULL); default: zend_error(E_WARNING, "Illegal offset type"); return FAILURE; } }
/*=========================================================================================================== NAME string_append - Fast string concatenation. PROTOTYPE string_append ( &$value, ... ) ; DESCRIPTION Appends series of values to the specified string. PARAMETERS $value (string) - String where to append values. $... (mixed) - Any argument that can be converted to a string and appended to $value. NOTE This code is theorically faster than the inline string-catenation operator, except that calling a PHP_FUNCTION() has a cost. When catenating 100 000 times a set of value takes 170ms using the catenation operator, it takes 615ms for string_append(), 535 of them being consumed just by calling the PHP_FUNCTION(). *===========================================================================================================*/ THRAK_API zend_bool internal_string_append ( zval * z_string, int argc, zval ** argv, char ** result, int * result_length ) { char * data, * p ; int size = Z_STRLEN_P ( z_string ) ; int i ; // Compute the size needed to hold all the appended strings for ( i = 0 ; i < argc ; i ++ ) { if ( Z_ISREF_P ( argv [i] ) ) SEPARATE_ZVAL ( & argv [i] ) ; convert_to_string ( argv [i] ) ; size += Z_STRLEN_P ( argv [i] ) ; } // Allocate enough memory for it (just reallocate existing data, this will avoid to copy the appended variable // initial value) data = p = erealloc ( Z_STRVAL_P ( z_string ), size + 1 ) ; if ( data == NULL ) return ( 0 ) ; // Point at the end of initial value p += Z_STRLEN_P ( z_string ) ; for ( i = 0 ; i < argc ; i ++, argv ++ ) { memcpy ( p, Z_STRVAL_PP ( argv ), Z_STRLEN_PP ( argv ) ) ; p += Z_STRLEN_PP ( argv ) ; } /* Useless but makes me happy */ * p = 0 ; // Give the resulting string to the caller * result = data ; * result_length = size ; return ( 1 ) ; }
/* {{{ xslt_make_array() Make an XSLT array (char **) from a zval array (HashTable *) */ extern void xslt_make_array(zval **zarr, char ***carr) { zval **current; HashTable *arr; int idx = 0; arr = HASH_OF(*zarr); if (! arr) { php_error(E_WARNING, "Invalid argument or parameter array to %s", get_active_function_name()); return; } *carr = emalloc((zend_hash_num_elements(arr) * 2) + 1); for (zend_hash_internal_pointer_reset(arr); zend_hash_get_current_data(arr, (void **) ¤t) == SUCCESS; zend_hash_move_forward(arr)) { char *string_key = NULL; ulong num_key; int type; SEPARATE_ZVAL(current); convert_to_string_ex(current); type = zend_hash_get_current_key(arr, &string_key, &num_key, 0); if (type == HASH_KEY_IS_LONG) { php_error(E_WARNING, "Invalid argument or parameter array to %s", get_active_function_name()); return; } (*carr)[idx++] = estrdup(string_key); (*carr)[idx++] = estrndup(Z_STRVAL_PP(current), Z_STRLEN_PP(current)); } (*carr)[idx] = NULL; }
/** * Adds a number to a string or increment that number if it already is defined * *<code> * echo Phalcon\Text::increment("a"); // "a_1" * echo Phalcon\Text::increment("a_1"); // "a_2" *</code> * * @param string $str * @param string $separator * @return string */ PHP_METHOD(Phalcon_Text, increment) { zval *str, *separator = NULL, *parts, *number = NULL, *first_part; PHALCON_MM_GROW(); phalcon_fetch_params(1, 1, 1, &str, &separator); if (!separator) { PHALCON_INIT_VAR(separator); } else { PHALCON_SEPARATE_PARAM(separator); } if (Z_TYPE_P(separator) == IS_NULL) { PHALCON_INIT_NVAR(separator); ZVAL_STRING(separator, "_", 1); } PHALCON_INIT_VAR(parts); phalcon_fast_explode(parts, separator, str); if (phalcon_array_isset_long(parts, 1)) { PHALCON_OBS_VAR(number); phalcon_array_fetch_long(&number, parts, 1, PH_NOISY); SEPARATE_ZVAL(&number); phalcon_increment(number); } else { PHALCON_INIT_VAR(number); ZVAL_LONG(number, 1); } PHALCON_OBS_VAR(first_part); phalcon_array_fetch_long(&first_part, parts, 0, PH_NOISY); PHALCON_CONCAT_VVV(return_value, first_part, separator, number); RETURN_MM(); }
int main(int argc, char ** argv) { zval t1, * pt2, ** ppt3; INIT_ZVAL(t1); Z_TYPE(t1) = IS_LONG; Z_LVAL(t1) = 54321; zval_print(&t1); ALLOC_INIT_ZVAL(pt2); ZVAL_STRING(pt2, "this is string val.", 1); zval_print(pt2); *ppt3 = pt2; ZVAL_ADDREF(*ppt3); zval_print(*ppt3); //zval_copy_ctor(*ppt3); SEPARATE_ZVAL(ppt3); zval_print(*ppt3); zval_print(pt2); Z_TYPE(t1) = IS_BOOL; Z_LVAL(t1) = 1; zval_print(&t1); Z_TYPE(t1) = IS_DOUBLE; Z_DVAL(t1) = 20.12; zval_print(&t1); /* zval_dtor(pt2); FREE_ZVAL(pt2); zval_dtor(*ppt3); FREE_ZVAL(*ppt3); */ }
static void pcntl_sigwaitinfo(INTERNAL_FUNCTION_PARAMETERS, int timedwait) /* {{{ */ { zval *user_set, **user_signo, *user_siginfo = NULL; long tv_sec = 0, tv_nsec = 0; sigset_t set; HashPosition pos; int signo; siginfo_t siginfo; struct timespec timeout; if (timedwait) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|zll", &user_set, &user_siginfo, &tv_sec, &tv_nsec) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|z", &user_set, &user_siginfo) == FAILURE) { return; } } if (sigemptyset(&set) != 0) { PCNTL_G(last_error) = errno; php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); RETURN_FALSE; } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(user_set), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(user_set), (void **)&user_signo, &pos) == SUCCESS) { if (Z_TYPE_PP(user_signo) != IS_LONG) { SEPARATE_ZVAL(user_signo); convert_to_long_ex(user_signo); } signo = Z_LVAL_PP(user_signo); if (sigaddset(&set, signo) != 0) { PCNTL_G(last_error) = errno; php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); RETURN_FALSE; } zend_hash_move_forward_ex(Z_ARRVAL_P(user_set), &pos); } if (timedwait) { timeout.tv_sec = (time_t) tv_sec; timeout.tv_nsec = tv_nsec; signo = sigtimedwait(&set, &siginfo, &timeout); } else { signo = sigwaitinfo(&set, &siginfo); } if (signo == -1 && errno != EAGAIN) { PCNTL_G(last_error) = errno; php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); } /* * sigtimedwait and sigwaitinfo can return 0 on success on some * platforms, e.g. NetBSD */ if (!signo && siginfo.si_signo) { signo = siginfo.si_signo; } if (signo > 0 && user_siginfo) { if (Z_TYPE_P(user_siginfo) != IS_ARRAY) { zval_dtor(user_siginfo); array_init(user_siginfo); } else { zend_hash_clean(Z_ARRVAL_P(user_siginfo)); } add_assoc_long_ex(user_siginfo, "signo", sizeof("signo"), siginfo.si_signo); add_assoc_long_ex(user_siginfo, "errno", sizeof("errno"), siginfo.si_errno); add_assoc_long_ex(user_siginfo, "code", sizeof("code"), siginfo.si_code); switch(signo) { #ifdef SIGCHLD case SIGCHLD: add_assoc_long_ex(user_siginfo, "status", sizeof("status"), siginfo.si_status); # ifdef si_utime add_assoc_double_ex(user_siginfo, "utime", sizeof("utime"), siginfo.si_utime); # endif # ifdef si_stime add_assoc_double_ex(user_siginfo, "stime", sizeof("stime"), siginfo.si_stime); # endif add_assoc_long_ex(user_siginfo, "pid", sizeof("pid"), siginfo.si_pid); add_assoc_long_ex(user_siginfo, "uid", sizeof("uid"), siginfo.si_uid); break; #endif case SIGILL: case SIGFPE: case SIGSEGV: case SIGBUS: add_assoc_double_ex(user_siginfo, "addr", sizeof("addr"), (long)siginfo.si_addr); break; #ifdef SIGPOLL case SIGPOLL: add_assoc_long_ex(user_siginfo, "band", sizeof("band"), siginfo.si_band); # ifdef si_fd add_assoc_long_ex(user_siginfo, "fd", sizeof("fd"), siginfo.si_fd); # endif break; #endif EMPTY_SWITCH_DEFAULT_CASE(); } } RETURN_LONG(signo); }
static char *proxy_callback( const char *url, const int url_len, zend_fcall_info *fci, zend_fcall_info_cache *fcc, char *callback_name ) { zval *zurl, *retval_ptr = NULL, **params; int retval; char *result = NULL; TSRMLS_FETCH(); if (fci == NULL || fci->size == 0) return NULL; /* should not happen */ MAKE_STD_ZVAL(zurl); ZVAL_STRINGL(zurl, url, url_len, 1); params = &zurl; fci->retval_ptr_ptr = &retval_ptr; fci->params = ¶ms; fci->param_count = 1; fci->no_separation = 1; retval = zend_call_function(fci, fcc TSRMLS_CC); if (retval != SUCCESS || fci->retval_ptr_ptr == NULL) { /* failure was most likely due to a previous exception (probably * in a previous URL), so don't throw yet another exception on * top of it */ if (!EG(exception)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Call to PHP %s callback has failed", callback_name); } } else { /* success in zend_call_function, but there may've been an exception */ /* may have been changed by return by reference */ retval_ptr = *fci->retval_ptr_ptr; if (retval_ptr == NULL) { /* no retval - most likely an exception, but we feel confortable * stacking an exception here */ zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Call to PHP %s callback has failed (%s)", callback_name, EG(exception)?"exception":"no return value"); } else if (Z_TYPE_P(retval_ptr) == IS_NULL) { /* use the default string for the url */ } else { if (Z_TYPE_P(retval_ptr) != IS_STRING) { SEPARATE_ZVAL(&retval_ptr); convert_to_string(retval_ptr); } result = estrndup(Z_STRVAL_P(retval_ptr), Z_STRLEN_P(retval_ptr)); } } zval_ptr_dtor(&zurl); if (retval_ptr != NULL) { zval_ptr_dtor(&retval_ptr); } return result; }
static int pgsql_stmt_param_hook(pdo_stmt_t *stmt, struct pdo_bound_param_data *param, enum pdo_param_event event_type) { pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data; if (stmt->supports_placeholders == PDO_PLACEHOLDER_NAMED && param->is_param) { switch (event_type) { case PDO_PARAM_EVT_FREE: if (param->driver_data) { efree(param->driver_data); } break; case PDO_PARAM_EVT_NORMALIZE: /* decode name from $1, $2 into 0, 1 etc. */ if (param->name) { if (param->name->val[0] == '$') { ZEND_ATOL(param->paramno, param->name->val + 1); } else { /* resolve parameter name to rewritten name */ char *namevar; if (stmt->bound_param_map && (namevar = zend_hash_find_ptr(stmt->bound_param_map, param->name)) != NULL) { ZEND_ATOL(param->paramno, namevar + 1); param->paramno--; } else { pdo_raise_impl_error(stmt->dbh, stmt, "HY093", param->name->val); return 0; } } } break; case PDO_PARAM_EVT_ALLOC: case PDO_PARAM_EVT_EXEC_POST: case PDO_PARAM_EVT_FETCH_PRE: case PDO_PARAM_EVT_FETCH_POST: /* work is handled by EVT_NORMALIZE */ return 1; case PDO_PARAM_EVT_EXEC_PRE: if (!stmt->bound_param_map) { return 0; } if (!S->param_values) { S->param_values = ecalloc( zend_hash_num_elements(stmt->bound_param_map), sizeof(char*)); S->param_lengths = ecalloc( zend_hash_num_elements(stmt->bound_param_map), sizeof(int)); S->param_formats = ecalloc( zend_hash_num_elements(stmt->bound_param_map), sizeof(int)); S->param_types = ecalloc( zend_hash_num_elements(stmt->bound_param_map), sizeof(Oid)); } if (param->paramno >= 0) { zval *parameter; if (param->paramno >= zend_hash_num_elements(stmt->bound_params)) { pdo_raise_impl_error(stmt->dbh, stmt, "HY093", "parameter was not defined"); return 0; } if (Z_ISREF(param->parameter)) { parameter = Z_REFVAL(param->parameter); } else { parameter = ¶m->parameter; } if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_LOB && Z_TYPE_P(parameter) == IS_RESOURCE) { php_stream *stm; php_stream_from_zval_no_verify(stm, parameter); if (stm) { if (php_stream_is(stm, &pdo_pgsql_lob_stream_ops)) { struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stm->abstract; pdo_pgsql_bound_param *P = param->driver_data; if (P == NULL) { P = ecalloc(1, sizeof(*P)); param->driver_data = P; } P->oid = htonl(self->oid); S->param_values[param->paramno] = (char*)&P->oid; S->param_lengths[param->paramno] = sizeof(P->oid); S->param_formats[param->paramno] = 1; S->param_types[param->paramno] = OIDOID; return 1; } else { zend_string *str = php_stream_copy_to_mem(stm, PHP_STREAM_COPY_ALL, 0); if (str != NULL) { //??SEPARATE_ZVAL_IF_NOT_REF(¶m->parameter); ZVAL_STR(parameter, str); } else { ZVAL_EMPTY_STRING(parameter); } } } else { /* expected a stream resource */ pdo_pgsql_error_stmt(stmt, PGRES_FATAL_ERROR, "HY105"); return 0; } } if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_NULL || Z_TYPE_P(parameter) == IS_NULL) { S->param_values[param->paramno] = NULL; S->param_lengths[param->paramno] = 0; } else if (Z_TYPE_P(parameter) == IS_FALSE || Z_TYPE_P(parameter) == IS_TRUE) { S->param_values[param->paramno] = Z_TYPE_P(parameter) == IS_TRUE ? "t" : "f"; S->param_lengths[param->paramno] = 1; S->param_formats[param->paramno] = 0; } else { //SEPARATE_ZVAL_IF_NOT_REF(¶m->parameter); convert_to_string_ex(parameter); S->param_values[param->paramno] = Z_STRVAL_P(parameter); S->param_lengths[param->paramno] = Z_STRLEN_P(parameter); S->param_formats[param->paramno] = 0; } if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_LOB) { S->param_types[param->paramno] = 0; S->param_formats[param->paramno] = 1; } else { S->param_types[param->paramno] = 0; } } break; } } else if (param->is_param) { /* We need to manually convert to a pg native boolean value */ if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_BOOL && ((param->param_type & PDO_PARAM_INPUT_OUTPUT) != PDO_PARAM_INPUT_OUTPUT)) { SEPARATE_ZVAL(¶m->parameter); param->param_type = PDO_PARAM_STR; convert_to_boolean(¶m->parameter); ZVAL_STRINGL(¶m->parameter, Z_TYPE_P(¶m->parameter) == IS_TRUE ? "t" : "f", 1); } } return 1; }
U_CFUNC PHP_FUNCTION(intltz_create_enumeration) { zval *arg = NULL; StringEnumeration *se = NULL; intl_error_reset(NULL); /* double indirection to have the zend engine destroy the new zval that * results from separation */ if (zend_parse_parameters(ZEND_NUM_ARGS(), "|z", &arg) == FAILURE) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_create_enumeration: bad arguments", 0); RETURN_FALSE; } if (arg == NULL || Z_TYPE_P(arg) == IS_NULL) { se = TimeZone::createEnumeration(); } else if (Z_TYPE_P(arg) == IS_LONG) { int_offset: if (Z_LVAL_P(arg) < (zend_long)INT32_MIN || Z_LVAL_P(arg) > (zend_long)INT32_MAX) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_create_enumeration: value is out of range", 0); RETURN_FALSE; } else { se = TimeZone::createEnumeration((int32_t) Z_LVAL_P(arg)); } } else if (Z_TYPE_P(arg) == IS_DOUBLE) { double_offset: convert_to_long_ex(arg); goto int_offset; } else if (Z_TYPE_P(arg) == IS_OBJECT || Z_TYPE_P(arg) == IS_STRING) { zend_long lval; double dval; convert_to_string_ex(arg); switch (is_numeric_string(Z_STRVAL_P(arg), Z_STRLEN_P(arg), &lval, &dval, 0)) { case IS_DOUBLE: SEPARATE_ZVAL(arg); zval_dtor(arg); ZVAL_DOUBLE(arg, dval); goto double_offset; case IS_LONG: SEPARATE_ZVAL(arg); zval_dtor(arg); ZVAL_LONG(arg, lval); goto int_offset; } /* else call string version */ se = TimeZone::createEnumeration(Z_STRVAL_P(arg)); } else { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_create_enumeration: invalid argument type", 0); RETURN_FALSE; } if (se) { IntlIterator_from_StringEnumeration(se, return_value); } else { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "intltz_create_enumeration: error obtaining enumeration", 0); RETVAL_FALSE; } }
/** * Appends an IN condition to the current conditions * *<code> * $builder->inWhere('id', [1, 2, 3]); *</code> * * @param string $expr * @param array $values * @return Phalcon\Mvc\Model\Query\Builder */ PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, inWhere){ zval *expr, *values, *hidden_param, *bind_params; zval *bind_keys, *value = NULL, *key = NULL, *query_key = NULL, *joined_keys; zval *conditions; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); phalcon_fetch_params(1, 2, 0, &expr, &values); if (Z_TYPE_P(values) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Values must be an array"); return; } PHALCON_OBS_VAR(hidden_param); phalcon_read_property_this(&hidden_param, this_ptr, SL("_hiddenParamNumber"), PH_NOISY_CC); SEPARATE_ZVAL(&hidden_param); PHALCON_INIT_VAR(bind_params); array_init(bind_params); PHALCON_INIT_VAR(bind_keys); array_init(bind_keys); phalcon_is_iterable(values, &ah0, &hp0, 0, 0); while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_HVALUE(value); /** * Key with auto bind-params */ PHALCON_INIT_NVAR(key); PHALCON_CONCAT_SV(key, "phi", hidden_param); PHALCON_INIT_NVAR(query_key); PHALCON_CONCAT_SVS(query_key, ":", key, ":"); phalcon_array_append(&bind_keys, query_key, PH_SEPARATE); phalcon_array_update_zval(&bind_params, key, &value, PH_COPY | PH_SEPARATE); phalcon_increment(hidden_param); zend_hash_move_forward_ex(ah0, &hp0); } PHALCON_INIT_VAR(joined_keys); phalcon_fast_join_str(joined_keys, SL(", "), bind_keys TSRMLS_CC); /** * Create a standard IN condition with bind params */ PHALCON_INIT_VAR(conditions); PHALCON_CONCAT_VSVS(conditions, expr, " IN (", joined_keys, ")"); /** * Append the IN to the current conditions using and 'and' */ phalcon_call_method_p2_noret(this_ptr, "andwhere", conditions, bind_params); phalcon_update_property_this(this_ptr, SL("_hiddenParamNumber"), hidden_param TSRMLS_CC); RETURN_THIS(); }
php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, const char *path, const char *mode, int options, char **opened_path, php_stream_context *context, int redirect_max, int flags STREAMS_DC TSRMLS_DC) /* {{{ */ { php_stream *stream = NULL; php_url *resource = NULL; int use_ssl; int use_proxy = 0; char *scratch = NULL; char *tmp = NULL; char *ua_str = NULL; zval **ua_zval = NULL, **tmpzval = NULL, *ssl_proxy_peer_name = NULL; int scratch_len = 0; int body = 0; char location[HTTP_HEADER_BLOCK_SIZE]; zval *response_header = NULL; int reqok = 0; char *http_header_line = NULL; char tmp_line[128]; size_t chunk_size = 0, file_size = 0; int eol_detect = 0; char *transport_string, *errstr = NULL; int transport_len, have_header = 0, request_fulluri = 0, ignore_errors = 0; char *protocol_version = NULL; int protocol_version_len = 3; /* Default: "1.0" */ struct timeval timeout; char *user_headers = NULL; int header_init = ((flags & HTTP_WRAPPER_HEADER_INIT) != 0); int redirected = ((flags & HTTP_WRAPPER_REDIRECTED) != 0); int follow_location = 1; php_stream_filter *transfer_encoding = NULL; int response_code; tmp_line[0] = '\0'; if (redirect_max < 1) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Redirection limit reached, aborting"); return NULL; } resource = php_url_parse(path); if (resource == NULL) { return NULL; } if (strncasecmp(resource->scheme, "http", sizeof("http")) && strncasecmp(resource->scheme, "https", sizeof("https"))) { if (!context || php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == FAILURE || Z_TYPE_PP(tmpzval) != IS_STRING || Z_STRLEN_PP(tmpzval) <= 0) { php_url_free(resource); return php_stream_open_wrapper_ex(path, mode, REPORT_ERRORS, NULL, context); } /* Called from a non-http wrapper with http proxying requested (i.e. ftp) */ request_fulluri = 1; use_ssl = 0; use_proxy = 1; transport_len = Z_STRLEN_PP(tmpzval); transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { /* Normal http request (possibly with proxy) */ if (strpbrk(mode, "awx+")) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP wrapper does not support writeable connections"); php_url_free(resource); return NULL; } use_ssl = resource->scheme && (strlen(resource->scheme) > 4) && resource->scheme[4] == 's'; /* choose default ports */ if (use_ssl && resource->port == 0) resource->port = 443; else if (resource->port == 0) resource->port = 80; if (context && php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { use_proxy = 1; transport_len = Z_STRLEN_PP(tmpzval); transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { transport_len = spprintf(&transport_string, 0, "%s://%s:%d", use_ssl ? "ssl" : "tcp", resource->host, resource->port); } } if (context && php_stream_context_get_option(context, wrapper->wops->label, "timeout", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_double_ex(tmpzval); timeout.tv_sec = (time_t) Z_DVAL_PP(tmpzval); timeout.tv_usec = (size_t) ((Z_DVAL_PP(tmpzval) - timeout.tv_sec) * 1000000); } else { timeout.tv_sec = FG(default_socket_timeout); timeout.tv_usec = 0; } stream = php_stream_xport_create(transport_string, transport_len, options, STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT, NULL, &timeout, context, &errstr, NULL); if (stream) { php_stream_set_option(stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &timeout); } if (errstr) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "%s", errstr); efree(errstr); errstr = NULL; } efree(transport_string); if (stream && use_proxy && use_ssl) { smart_str header = {0}; /* Set peer_name or name verification will try to use the proxy server name */ if (!context || php_stream_context_get_option(context, "ssl", "peer_name", &tmpzval) == FAILURE) { MAKE_STD_ZVAL(ssl_proxy_peer_name); ZVAL_STRING(ssl_proxy_peer_name, resource->host, 1); php_stream_context_set_option(stream->context, "ssl", "peer_name", ssl_proxy_peer_name); } smart_str_appendl(&header, "CONNECT ", sizeof("CONNECT ")-1); smart_str_appends(&header, resource->host); smart_str_appendc(&header, ':'); smart_str_append_unsigned(&header, resource->port); smart_str_appendl(&header, " HTTP/1.0\r\n", sizeof(" HTTP/1.0\r\n")-1); /* check if we have Proxy-Authorization header */ if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) { char *s, *p; if (Z_TYPE_PP(tmpzval) == IS_ARRAY) { HashPosition pos; zval **tmpheader = NULL; for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos); SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos); zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos)) { if (Z_TYPE_PP(tmpheader) == IS_STRING) { s = Z_STRVAL_PP(tmpheader); do { while (*s == ' ' || *s == '\t') s++; p = s; while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++; if (*p == ':') { p++; if (p - s == sizeof("Proxy-Authorization:") - 1 && zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1, "Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) { while (*p != 0 && *p != '\r' && *p !='\n') p++; smart_str_appendl(&header, s, p - s); smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1); goto finish; } else { while (*p != 0 && *p != '\r' && *p !='\n') p++; } } s = p; while (*s == '\r' || *s == '\n') s++; } while (*s != 0); } } } else if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) { s = Z_STRVAL_PP(tmpzval); do { while (*s == ' ' || *s == '\t') s++; p = s; while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++; if (*p == ':') { p++; if (p - s == sizeof("Proxy-Authorization:") - 1 && zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1, "Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) { while (*p != 0 && *p != '\r' && *p !='\n') p++; smart_str_appendl(&header, s, p - s); smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1); goto finish; } else { while (*p != 0 && *p != '\r' && *p !='\n') p++; } } s = p; while (*s == '\r' || *s == '\n') s++; } while (*s != 0); } } finish: smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1); if (php_stream_write(stream, header.c, header.len) != header.len) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy"); php_stream_close(stream); stream = NULL; } smart_str_free(&header); if (stream) { char header_line[HTTP_HEADER_BLOCK_SIZE]; /* get response header */ while (php_stream_gets(stream, header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL) { if (header_line[0] == '\n' || header_line[0] == '\r' || header_line[0] == '\0') { break; } } } /* enable SSL transport layer */ if (stream) { if (php_stream_xport_crypto_setup(stream, STREAM_CRYPTO_METHOD_ANY_CLIENT, NULL TSRMLS_CC) < 0 || php_stream_xport_crypto_enable(stream, 1 TSRMLS_CC) < 0) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy"); php_stream_close(stream); stream = NULL; } } } if (stream == NULL) goto out; /* avoid buffering issues while reading header */ if (options & STREAM_WILL_CAST) chunk_size = php_stream_set_chunk_size(stream, 1); /* avoid problems with auto-detecting when reading the headers -> the headers * are always in canonical \r\n format */ eol_detect = stream->flags & (PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC); stream->flags &= ~(PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC); php_stream_context_set(stream, context TSRMLS_CC); php_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0); if (header_init && context && php_stream_context_get_option(context, "http", "max_redirects", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_long_ex(tmpzval); redirect_max = Z_LVAL_PP(tmpzval); } if (context && php_stream_context_get_option(context, "http", "method", &tmpzval) == SUCCESS) { if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { /* As per the RFC, automatically redirected requests MUST NOT use other methods than * GET and HEAD unless it can be confirmed by the user */ if (!redirected || (Z_STRLEN_PP(tmpzval) == 3 && memcmp("GET", Z_STRVAL_PP(tmpzval), 3) == 0) || (Z_STRLEN_PP(tmpzval) == 4 && memcmp("HEAD",Z_STRVAL_PP(tmpzval), 4) == 0) ) { scratch_len = strlen(path) + 29 + Z_STRLEN_PP(tmpzval); scratch = emalloc(scratch_len); strlcpy(scratch, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval) + 1); strncat(scratch, " ", 1); } } } if (context && php_stream_context_get_option(context, "http", "protocol_version", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_double_ex(tmpzval); protocol_version_len = spprintf(&protocol_version, 0, "%.1F", Z_DVAL_PP(tmpzval)); } if (!scratch) { scratch_len = strlen(path) + 29 + protocol_version_len; scratch = emalloc(scratch_len); strncpy(scratch, "GET ", scratch_len); } /* Should we send the entire path in the request line, default to no. */ if (!request_fulluri && context && php_stream_context_get_option(context, "http", "request_fulluri", &tmpzval) == SUCCESS) { zval ztmp = **tmpzval; zval_copy_ctor(&ztmp); convert_to_boolean(&ztmp); request_fulluri = Z_BVAL(ztmp) ? 1 : 0; zval_dtor(&ztmp); } if (request_fulluri) { /* Ask for everything */ strcat(scratch, path); } else { /* Send the traditional /path/to/file?query_string */ /* file */ if (resource->path && *resource->path) { strlcat(scratch, resource->path, scratch_len); } else { strlcat(scratch, "/", scratch_len); } /* query string */ if (resource->query) { strlcat(scratch, "?", scratch_len); strlcat(scratch, resource->query, scratch_len); } } /* protocol version we are speaking */ if (protocol_version) { strlcat(scratch, " HTTP/", scratch_len); strlcat(scratch, protocol_version, scratch_len); strlcat(scratch, "\r\n", scratch_len); } else { strlcat(scratch, " HTTP/1.0\r\n", scratch_len); } /* send it */ php_stream_write(stream, scratch, strlen(scratch)); if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) { tmp = NULL; if (Z_TYPE_PP(tmpzval) == IS_ARRAY) { HashPosition pos; zval **tmpheader = NULL; smart_str tmpstr = {0}; for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos); SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos); zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos) ) { if (Z_TYPE_PP(tmpheader) == IS_STRING) { smart_str_appendl(&tmpstr, Z_STRVAL_PP(tmpheader), Z_STRLEN_PP(tmpheader)); smart_str_appendl(&tmpstr, "\r\n", sizeof("\r\n") - 1); } } smart_str_0(&tmpstr); /* Remove newlines and spaces from start and end. there's at least one extra \r\n at the end that needs to go. */ if (tmpstr.c) { tmp = php_trim(tmpstr.c, strlen(tmpstr.c), NULL, 0, NULL, 3 TSRMLS_CC); smart_str_free(&tmpstr); } } if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) { /* Remove newlines and spaces from start and end php_trim will estrndup() */ tmp = php_trim(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval), NULL, 0, NULL, 3 TSRMLS_CC); } if (tmp && strlen(tmp) > 0) { char *s; user_headers = estrdup(tmp); /* Make lowercase for easy comparison against 'standard' headers */ php_strtolower(tmp, strlen(tmp)); if (!header_init) { /* strip POST headers on redirect */ strip_header(user_headers, tmp, "content-length:"); strip_header(user_headers, tmp, "content-type:"); } if ((s = strstr(tmp, "user-agent:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_USER_AGENT; } if ((s = strstr(tmp, "host:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_HOST; } if ((s = strstr(tmp, "from:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_FROM; } if ((s = strstr(tmp, "authorization:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_AUTH; } if ((s = strstr(tmp, "content-length:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_CONTENT_LENGTH; } if ((s = strstr(tmp, "content-type:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_TYPE; } if ((s = strstr(tmp, "connection:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_CONNECTION; } /* remove Proxy-Authorization header */ if (use_proxy && use_ssl && (s = strstr(tmp, "proxy-authorization:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { char *p = s + sizeof("proxy-authorization:") - 1; while (s > tmp && (*(s-1) == ' ' || *(s-1) == '\t')) s--; while (*p != 0 && *p != '\r' && *p != '\n') p++; while (*p == '\r' || *p == '\n') p++; if (*p == 0) { if (s == tmp) { efree(user_headers); user_headers = NULL; } else { while (s > tmp && (*(s-1) == '\r' || *(s-1) == '\n')) s--; user_headers[s - tmp] = 0; } } else { memmove(user_headers + (s - tmp), user_headers + (p - tmp), strlen(p) + 1); } } } if (tmp) { efree(tmp); } } /* auth header if it was specified */ if (((have_header & HTTP_HEADER_AUTH) == 0) && resource->user) { /* decode the strings first */ php_url_decode(resource->user, strlen(resource->user)); /* scratch is large enough, since it was made large enough for the whole URL */ strcpy(scratch, resource->user); strcat(scratch, ":"); /* Note: password is optional! */ if (resource->pass) { php_url_decode(resource->pass, strlen(resource->pass)); strcat(scratch, resource->pass); } tmp = (char*)php_base64_encode((unsigned char*)scratch, strlen(scratch), NULL); if (snprintf(scratch, scratch_len, "Authorization: Basic %s\r\n", tmp) > 0) { php_stream_write(stream, scratch, strlen(scratch)); php_stream_notify_info(context, PHP_STREAM_NOTIFY_AUTH_REQUIRED, NULL, 0); } efree(tmp); tmp = NULL; } /* if the user has configured who they are, send a From: line */ if (((have_header & HTTP_HEADER_FROM) == 0) && FG(from_address)) { if (snprintf(scratch, scratch_len, "From: %s\r\n", FG(from_address)) > 0) php_stream_write(stream, scratch, strlen(scratch)); } /* Send Host: header so name-based virtual hosts work */ if ((have_header & HTTP_HEADER_HOST) == 0) { if ((use_ssl && resource->port != 443 && resource->port != 0) || (!use_ssl && resource->port != 80 && resource->port != 0)) { if (snprintf(scratch, scratch_len, "Host: %s:%i\r\n", resource->host, resource->port) > 0) php_stream_write(stream, scratch, strlen(scratch)); } else { if (snprintf(scratch, scratch_len, "Host: %s\r\n", resource->host) > 0) { php_stream_write(stream, scratch, strlen(scratch)); } } } /* Send a Connection: close header when using HTTP 1.1 or later to avoid * hanging when the server interprets the RFC literally and establishes a * keep-alive connection, unless the user specifically requests something * else by specifying a Connection header in the context options. */ if (protocol_version && ((have_header & HTTP_HEADER_CONNECTION) == 0) && (strncmp(protocol_version, "1.0", MIN(protocol_version_len, 3)) > 0)) { php_stream_write_string(stream, "Connection: close\r\n"); } if (context && php_stream_context_get_option(context, "http", "user_agent", &ua_zval) == SUCCESS && Z_TYPE_PP(ua_zval) == IS_STRING) { ua_str = Z_STRVAL_PP(ua_zval); } else if (FG(user_agent)) { ua_str = FG(user_agent); } if (((have_header & HTTP_HEADER_USER_AGENT) == 0) && ua_str) { #define _UA_HEADER "User-Agent: %s\r\n" char *ua; size_t ua_len; ua_len = sizeof(_UA_HEADER) + strlen(ua_str); /* ensure the header is only sent if user_agent is not blank */ if (ua_len > sizeof(_UA_HEADER)) { ua = emalloc(ua_len + 1); if ((ua_len = slprintf(ua, ua_len, _UA_HEADER, ua_str)) > 0) { ua[ua_len] = 0; php_stream_write(stream, ua, ua_len); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot construct User-agent header"); } if (ua) { efree(ua); } } } if (user_headers) { /* A bit weird, but some servers require that Content-Length be sent prior to Content-Type for POST * see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first. */ if ( header_init && context && !(have_header & HTTP_HEADER_CONTENT_LENGTH) && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0 ) { scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval)); php_stream_write(stream, scratch, scratch_len); have_header |= HTTP_HEADER_CONTENT_LENGTH; } php_stream_write(stream, user_headers, strlen(user_headers)); php_stream_write(stream, "\r\n", sizeof("\r\n")-1); efree(user_headers); } /* Request content, such as for POST requests */ if (header_init && context && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { if (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) { scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval)); php_stream_write(stream, scratch, scratch_len); } if (!(have_header & HTTP_HEADER_TYPE)) { php_stream_write(stream, "Content-Type: application/x-www-form-urlencoded\r\n", sizeof("Content-Type: application/x-www-form-urlencoded\r\n") - 1); php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Content-type not specified assuming application/x-www-form-urlencoded"); } php_stream_write(stream, "\r\n", sizeof("\r\n")-1); php_stream_write(stream, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { php_stream_write(stream, "\r\n", sizeof("\r\n")-1); } location[0] = '\0'; if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } if (header_init) { zval *ztmp; MAKE_STD_ZVAL(ztmp); array_init(ztmp); ZEND_SET_SYMBOL(EG(active_symbol_table), "http_response_header", ztmp); } { zval **rh; zend_hash_find(EG(active_symbol_table), "http_response_header", sizeof("http_response_header"), (void **) &rh); response_header = *rh; } if (!php_stream_eof(stream)) { size_t tmp_line_len; /* get response header */ if (php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL) { zval *http_response; if (tmp_line_len > 9) { response_code = atoi(tmp_line + 9); } else { response_code = 0; } if (context && SUCCESS==php_stream_context_get_option(context, "http", "ignore_errors", &tmpzval)) { ignore_errors = zend_is_true(*tmpzval TSRMLS_CC); } /* when we request only the header, don't fail even on error codes */ if ((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) { reqok = 1; } /* all status codes in the 2xx range are defined by the specification as successful; * all status codes in the 3xx range are for redirection, and so also should never * fail */ if (response_code >= 200 && response_code < 400) { reqok = 1; } else { switch(response_code) { case 403: php_stream_notify_error(context, PHP_STREAM_NOTIFY_AUTH_RESULT, tmp_line, response_code); break; default: /* safety net in the event tmp_line == NULL */ if (!tmp_line_len) { tmp_line[0] = '\0'; } php_stream_notify_error(context, PHP_STREAM_NOTIFY_FAILURE, tmp_line, response_code); } } if (tmp_line[tmp_line_len - 1] == '\n') { --tmp_line_len; if (tmp_line[tmp_line_len - 1] == '\r') { --tmp_line_len; } } MAKE_STD_ZVAL(http_response); ZVAL_STRINGL(http_response, tmp_line, tmp_line_len, 1); zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_response, sizeof(zval *), NULL); } } else { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, unexpected end of socket!"); goto out; } /* read past HTTP headers */ http_header_line = emalloc(HTTP_HEADER_BLOCK_SIZE); while (!body && !php_stream_eof(stream)) { size_t http_header_line_length; if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) && *http_header_line != '\n' && *http_header_line != '\r') { char *e = http_header_line + http_header_line_length - 1; if (*e != '\n') { do { /* partial header */ if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) == NULL) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Failed to read HTTP headers"); goto out; } e = http_header_line + http_header_line_length - 1; } while (*e != '\n'); continue; } while (*e == '\n' || *e == '\r') { e--; } http_header_line_length = e - http_header_line + 1; http_header_line[http_header_line_length] = '\0'; if (!strncasecmp(http_header_line, "Location: ", 10)) { if (context && php_stream_context_get_option(context, "http", "follow_location", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_long_ex(tmpzval); follow_location = Z_LVAL_PP(tmpzval); } else if (!(response_code >= 300 && response_code < 304 || 307 == response_code || 308 == response_code)) { /* we shouldn't redirect automatically if follow_location isn't set and response_code not in (300, 301, 302, 303 and 307) see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1 RFC 7238 defines 308: http://tools.ietf.org/html/rfc7238 */ follow_location = 0; } strlcpy(location, http_header_line + 10, sizeof(location)); } else if (!strncasecmp(http_header_line, "Content-Type: ", 14)) { php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_line + 14, 0); } else if (!strncasecmp(http_header_line, "Content-Length: ", 16)) { file_size = atoi(http_header_line + 16); php_stream_notify_file_size(context, file_size, http_header_line, 0); } else if (!strncasecmp(http_header_line, "Transfer-Encoding: chunked", sizeof("Transfer-Encoding: chunked"))) { /* create filter to decode response body */ if (!(options & STREAM_ONLY_GET_HEADERS)) { long decode = 1; if (context && php_stream_context_get_option(context, "http", "auto_decode", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_boolean(*tmpzval); decode = Z_LVAL_PP(tmpzval); } if (decode) { transfer_encoding = php_stream_filter_create("dechunk", NULL, php_stream_is_persistent(stream) TSRMLS_CC); if (transfer_encoding) { /* don't store transfer-encodeing header */ continue; } } } } if (http_header_line[0] == '\0') { body = 1; } else { zval *http_header; MAKE_STD_ZVAL(http_header); ZVAL_STRINGL(http_header, http_header_line, http_header_line_length, 1); zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL); } } else { break; } } if (!reqok || (location[0] != '\0' && follow_location)) { if (!follow_location || (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1)) { goto out; } if (location[0] != '\0') php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0); php_stream_close(stream); stream = NULL; if (location[0] != '\0') { char new_path[HTTP_HEADER_BLOCK_SIZE]; char loc_path[HTTP_HEADER_BLOCK_SIZE]; *new_path='\0'; if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) && strncasecmp(location, "https://", sizeof("https://")-1) && strncasecmp(location, "ftp://", sizeof("ftp://")-1) && strncasecmp(location, "ftps://", sizeof("ftps://")-1))) { if (*location != '/') { if (*(location+1) != '\0' && resource->path) { char *s = strrchr(resource->path, '/'); if (!s) { s = resource->path; if (!s[0]) { efree(s); s = resource->path = estrdup("/"); } else { *s = '/'; } } s[1] = '\0'; if (resource->path && *(resource->path) == '/' && *(resource->path + 1) == '\0') { snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", resource->path, location); } else { snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", resource->path, location); } } else { snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location); } } else { strlcpy(loc_path, location, sizeof(loc_path)); } if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) { snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", resource->scheme, resource->host, resource->port, loc_path); } else { snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", resource->scheme, resource->host, loc_path); } } else { strlcpy(new_path, location, sizeof(new_path)); } php_url_free(resource); /* check for invalid redirection URLs */ if ((resource = php_url_parse(new_path)) == NULL) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); goto out; } #define CHECK_FOR_CNTRL_CHARS(val) { \ if (val) { \ unsigned char *s, *e; \ int l; \ l = php_url_decode(val, strlen(val)); \ s = (unsigned char*)val; e = s + l; \ while (s < e) { \ if (iscntrl(*s)) { \ php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); \ goto out; \ } \ s++; \ } \ } \ } /* check for control characters in login, password & path */ if (strncasecmp(new_path, "http://", sizeof("http://") - 1) || strncasecmp(new_path, "https://", sizeof("https://") - 1)) { CHECK_FOR_CNTRL_CHARS(resource->user) CHECK_FOR_CNTRL_CHARS(resource->pass) CHECK_FOR_CNTRL_CHARS(resource->path) } stream = php_stream_url_wrap_http_ex(wrapper, new_path, mode, options, opened_path, context, --redirect_max, HTTP_WRAPPER_REDIRECTED STREAMS_CC TSRMLS_CC); } else {
/* php_formatted_print() {{{ * New sprintf implementation for PHP. * * Modifiers: * * " " pad integers with spaces * "-" left adjusted field * n field size * "."n precision (floats only) * "+" Always place a sign (+ or -) in front of a number * * Type specifiers: * * "%" literal "%", modifiers are ignored. * "b" integer argument is printed as binary * "c" integer argument is printed as a single character * "d" argument is an integer * "f" the argument is a float * "o" integer argument is printed as octal * "s" argument is a string * "x" integer argument is printed as lowercase hexadecimal * "X" integer argument is printed as uppercase hexadecimal * */ static char * php_formatted_print(int ht, int *len, int use_array, int format_offset TSRMLS_DC) { zval ***args, **z_format; int argc, size = 240, inpos = 0, outpos = 0, temppos; int alignment, currarg, adjusting, argnum, width, precision; char *format, *result, padding; int always_sign; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return NULL; } /* verify the number of args */ if ((use_array && argc != (2 + format_offset)) || (!use_array && argc < (1 + format_offset))) { efree(args); WRONG_PARAM_COUNT_WITH_RETVAL(NULL); } if (use_array) { int i = 1; zval ***newargs; zval **array; z_format = args[format_offset]; array = args[1 + format_offset]; SEPARATE_ZVAL(array); convert_to_array_ex(array); argc = 1 + zend_hash_num_elements(Z_ARRVAL_PP(array)); newargs = (zval ***)safe_emalloc(argc, sizeof(zval *), 0); newargs[0] = z_format; for (zend_hash_internal_pointer_reset(Z_ARRVAL_PP(array)); zend_hash_get_current_data(Z_ARRVAL_PP(array), (void **)&newargs[i++]) == SUCCESS; zend_hash_move_forward(Z_ARRVAL_PP(array))); efree(args); args = newargs; format_offset = 0; } convert_to_string_ex(args[format_offset]); format = Z_STRVAL_PP(args[format_offset]); result = emalloc(size); currarg = 1; while (inpos<Z_STRLEN_PP(args[format_offset])) { int expprec = 0, multiuse = 0; zval *tmp; PRINTF_DEBUG(("sprintf: format[%d]='%c'\n", inpos, format[inpos])); PRINTF_DEBUG(("sprintf: outpos=%d\n", outpos)); if (format[inpos] != '%') { php_sprintf_appendchar(&result, &outpos, &size, format[inpos++] TSRMLS_CC); } else if (format[inpos + 1] == '%') { php_sprintf_appendchar(&result, &outpos, &size, '%' TSRMLS_CC); inpos += 2; } else { /* starting a new format specifier, reset variables */ alignment = ALIGN_RIGHT; adjusting = 0; padding = ' '; always_sign = 0; inpos++; /* skip the '%' */ PRINTF_DEBUG(("sprintf: first looking at '%c', inpos=%d\n", format[inpos], inpos)); if (isascii((int)format[inpos]) && !isalpha((int)format[inpos])) { /* first look for argnum */ temppos = inpos; while (isdigit((int)format[temppos])) temppos++; if (format[temppos] == '$') { argnum = php_sprintf_getnumber(format, &inpos); if (argnum <= 0) { efree(result); efree(args); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument number must be greater than zero"); return NULL; } multiuse = 1; inpos++; /* skip the '$' */ } else { argnum = currarg++; } argnum += format_offset; /* after argnum comes modifiers */ PRINTF_DEBUG(("sprintf: looking for modifiers\n" "sprintf: now looking at '%c', inpos=%d\n", format[inpos], inpos)); for (;; inpos++) { if (format[inpos] == ' ' || format[inpos] == '0') { padding = format[inpos]; } else if (format[inpos] == '-') { alignment = ALIGN_LEFT; /* space padding, the default */ } else if (format[inpos] == '+') { always_sign = 1; } else if (format[inpos] == '\'') { padding = format[++inpos]; } else { PRINTF_DEBUG(("sprintf: end of modifiers\n")); break; } } PRINTF_DEBUG(("sprintf: padding='%c'\n", padding)); PRINTF_DEBUG(("sprintf: alignment=%s\n", (alignment == ALIGN_LEFT) ? "left" : "right")); /* after modifiers comes width */ if (isdigit((int)format[inpos])) { PRINTF_DEBUG(("sprintf: getting width\n")); if ((width = php_sprintf_getnumber(format, &inpos)) < 0) { efree(result); efree(args); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Width must be greater than zero and less than %d", INT_MAX); return NULL; } adjusting |= ADJ_WIDTH; } else { width = 0; } PRINTF_DEBUG(("sprintf: width=%d\n", width)); /* after width and argnum comes precision */ if (format[inpos] == '.') { inpos++; PRINTF_DEBUG(("sprintf: getting precision\n")); if (isdigit((int)format[inpos])) { if ((precision = php_sprintf_getnumber(format, &inpos)) < 0) { efree(result); efree(args); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Precision must be greater than zero and less than %d", INT_MAX); return NULL; } adjusting |= ADJ_PRECISION; expprec = 1; } else { precision = 0; } } else { precision = 0; } PRINTF_DEBUG(("sprintf: precision=%d\n", precision)); } else { width = precision = 0; argnum = currarg++ + format_offset; } if (argnum >= argc) { efree(result); efree(args); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Too few arguments"); return NULL; } if (format[inpos] == 'l') { inpos++; } PRINTF_DEBUG(("sprintf: format character='%c'\n", format[inpos])); /* now we expect to find a type specifier */ if (multiuse) { MAKE_STD_ZVAL(tmp); *tmp = **(args[argnum]); INIT_PZVAL(tmp); zval_copy_ctor(tmp); } else { SEPARATE_ZVAL(args[argnum]); tmp = *(args[argnum]); } switch (format[inpos]) { case 's': { zval *var, var_copy; int use_copy; zend_make_printable_zval(tmp, &var_copy, &use_copy); if (use_copy) { var = &var_copy; } else { var = tmp; } php_sprintf_appendstring(&result, &outpos, &size, Z_STRVAL_P(var), width, precision, padding, alignment, Z_STRLEN_P(var), 0, expprec, 0); if (use_copy) { zval_dtor(&var_copy); } break; } case 'd': convert_to_long(tmp); php_sprintf_appendint(&result, &outpos, &size, Z_LVAL_P(tmp), width, padding, alignment, always_sign); break; case 'u': convert_to_long(tmp); php_sprintf_appenduint(&result, &outpos, &size, Z_LVAL_P(tmp), width, padding, alignment); break; case 'g': case 'G': case 'e': case 'E': case 'f': case 'F': convert_to_double(tmp); php_sprintf_appenddouble(&result, &outpos, &size, Z_DVAL_P(tmp), width, padding, alignment, precision, adjusting, format[inpos], always_sign TSRMLS_CC); break; case 'c': convert_to_long(tmp); php_sprintf_appendchar(&result, &outpos, &size, (char) Z_LVAL_P(tmp) TSRMLS_CC); break; case 'o': convert_to_long(tmp); php_sprintf_append2n(&result, &outpos, &size, Z_LVAL_P(tmp), width, padding, alignment, 3, hexchars, expprec); break; case 'x': convert_to_long(tmp); php_sprintf_append2n(&result, &outpos, &size, Z_LVAL_P(tmp), width, padding, alignment, 4, hexchars, expprec); break; case 'X': convert_to_long(tmp); php_sprintf_append2n(&result, &outpos, &size, Z_LVAL_P(tmp), width, padding, alignment, 4, HEXCHARS, expprec); break; case 'b': convert_to_long(tmp); php_sprintf_append2n(&result, &outpos, &size, Z_LVAL_P(tmp), width, padding, alignment, 1, hexchars, expprec); break; case '%': php_sprintf_appendchar(&result, &outpos, &size, '%' TSRMLS_CC); break; default: break; } if (multiuse) { zval_ptr_dtor(&tmp); } inpos++; } } efree(args); /* possibly, we have to make sure we have room for the terminating null? */ result[outpos]=0; *len = outpos; return result; }
php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, char *path, char *mode, int options, char **opened_path, php_stream_context *context, int redirect_max, int header_init STREAMS_DC TSRMLS_DC) { php_stream *stream = NULL; php_url *resource = NULL; int use_ssl; int use_proxy = 0; char *scratch = NULL; char *tmp = NULL; char *ua_str = NULL; zval **ua_zval = NULL, **tmpzval = NULL; int scratch_len = 0; int body = 0; char location[HTTP_HEADER_BLOCK_SIZE]; zval *response_header = NULL; int reqok = 0; char *http_header_line = NULL; char tmp_line[128]; size_t chunk_size = 0, file_size = 0; int eol_detect = 0; char *transport_string, *errstr = NULL; int transport_len, have_header = 0, request_fulluri = 0; char *protocol_version = NULL; int protocol_version_len = 3; /* Default: "1.0" */ struct timeval timeout; char *user_headers = NULL; tmp_line[0] = '\0'; if (redirect_max < 1) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Redirection limit reached, aborting"); return NULL; } resource = php_url_parse(path); if (resource == NULL) { return NULL; } if (strncasecmp(resource->scheme, "http", sizeof("http")) && strncasecmp(resource->scheme, "https", sizeof("https"))) { if (!context || php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == FAILURE || Z_TYPE_PP(tmpzval) != IS_STRING || Z_STRLEN_PP(tmpzval) <= 0) { php_url_free(resource); return php_stream_open_wrapper_ex(path, mode, REPORT_ERRORS, NULL, context); } /* Called from a non-http wrapper with http proxying requested (i.e. ftp) */ request_fulluri = 1; use_ssl = 0; use_proxy = 1; transport_len = Z_STRLEN_PP(tmpzval); transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { /* Normal http request (possibly with proxy) */ if (strpbrk(mode, "awx+")) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP wrapper does not support writeable connections"); php_url_free(resource); return NULL; } use_ssl = resource->scheme && (strlen(resource->scheme) > 4) && resource->scheme[4] == 's'; /* choose default ports */ if (use_ssl && resource->port == 0) resource->port = 443; else if (resource->port == 0) resource->port = 80; if (context && php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { use_proxy = 1; transport_len = Z_STRLEN_PP(tmpzval); transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { transport_len = spprintf(&transport_string, 0, "%s://%s:%d", use_ssl ? "ssl" : "tcp", resource->host, resource->port); } } if (context && php_stream_context_get_option(context, wrapper->wops->label, "timeout", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_double_ex(tmpzval); timeout.tv_sec = (time_t) Z_DVAL_PP(tmpzval); timeout.tv_usec = (size_t) ((Z_DVAL_PP(tmpzval) - timeout.tv_sec) * 1000000); } else { timeout.tv_sec = FG(default_socket_timeout); timeout.tv_usec = 0; } stream = php_stream_xport_create(transport_string, transport_len, options, STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT, NULL, &timeout, context, &errstr, NULL); if (stream) { php_stream_set_option(stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &timeout); } if (errstr) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "%s", errstr); efree(errstr); errstr = NULL; } efree(transport_string); if (stream && use_proxy && use_ssl) { smart_str header = {0}; smart_str_appendl(&header, "CONNECT ", sizeof("CONNECT ")-1); smart_str_appends(&header, resource->host); smart_str_appendc(&header, ':'); smart_str_append_unsigned(&header, resource->port); smart_str_appendl(&header, " HTTP/1.0\r\n\r\n", sizeof(" HTTP/1.0\r\n\r\n")-1); if (php_stream_write(stream, header.c, header.len) != header.len) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy"); php_stream_close(stream); stream = NULL; } smart_str_free(&header); if (stream) { char header_line[HTTP_HEADER_BLOCK_SIZE]; /* get response header */ while (php_stream_gets(stream, header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL) { if (header_line[0] == '\n' || header_line[0] == '\r' || header_line[0] == '\0') { break; } } } /* enable SSL transport layer */ if (stream) { if (php_stream_xport_crypto_setup(stream, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, NULL TSRMLS_CC) < 0 || php_stream_xport_crypto_enable(stream, 1 TSRMLS_CC) < 0) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy"); php_stream_close(stream); stream = NULL; } } } if (stream == NULL) goto out; /* avoid buffering issues while reading header */ if (options & STREAM_WILL_CAST) chunk_size = php_stream_set_chunk_size(stream, 1); /* avoid problems with auto-detecting when reading the headers -> the headers * are always in canonical \r\n format */ eol_detect = stream->flags & (PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC); stream->flags &= ~(PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC); php_stream_context_set(stream, context); php_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0); if (header_init && context && php_stream_context_get_option(context, "http", "max_redirects", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_long_ex(tmpzval); redirect_max = Z_LVAL_PP(tmpzval); } if (context && php_stream_context_get_option(context, "http", "method", &tmpzval) == SUCCESS) { if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { scratch_len = strlen(path) + 29 + Z_STRLEN_PP(tmpzval); scratch = emalloc(scratch_len); strlcpy(scratch, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval) + 1); strcat(scratch, " "); } } if (context && php_stream_context_get_option(context, "http", "protocol_version", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_double_ex(tmpzval); protocol_version_len = spprintf(&protocol_version, 0, "%.1F", Z_DVAL_PP(tmpzval)); } if (!scratch) { scratch_len = strlen(path) + 29 + protocol_version_len; scratch = emalloc(scratch_len); strcpy(scratch, "GET "); } /* Should we send the entire path in the request line, default to no. */ if (!request_fulluri && context && php_stream_context_get_option(context, "http", "request_fulluri", &tmpzval) == SUCCESS) { zval tmp = **tmpzval; zval_copy_ctor(&tmp); convert_to_boolean(&tmp); request_fulluri = Z_BVAL(tmp) ? 1 : 0; zval_dtor(&tmp); } if (request_fulluri) { /* Ask for everything */ strcat(scratch, path); } else { /* Send the traditional /path/to/file?query_string */ /* file */ if (resource->path && *resource->path) { strlcat(scratch, resource->path, scratch_len); } else { strlcat(scratch, "/", scratch_len); } /* query string */ if (resource->query) { strlcat(scratch, "?", scratch_len); strlcat(scratch, resource->query, scratch_len); } } /* protocol version we are speaking */ if (protocol_version) { strlcat(scratch, " HTTP/", scratch_len); strlcat(scratch, protocol_version, scratch_len); strlcat(scratch, "\r\n", scratch_len); efree(protocol_version); protocol_version = NULL; } else { strlcat(scratch, " HTTP/1.0\r\n", scratch_len); } /* send it */ php_stream_write(stream, scratch, strlen(scratch)); if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) { /* Remove newlines and spaces from start and end, php_trim will estrndup() */ tmp = php_trim(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval), NULL, 0, NULL, 3 TSRMLS_CC); if (strlen(tmp) > 0) { if (!header_init) { /* Remove post headers for redirects */ int l = strlen(tmp); char *s, *s2, *tmp_c = estrdup(tmp); php_strtolower(tmp_c, l); if ((s = strstr(tmp_c, "content-length:"))) { if ((s2 = memchr(s, '\n', tmp_c + l - s))) { int b = tmp_c + l - 1 - s2; memmove(tmp, tmp + (s2 + 1 - tmp_c), b); memmove(tmp_c, s2 + 1, b); } else { tmp[s - tmp_c] = *s = '\0'; } l = strlen(tmp_c); } if ((s = strstr(tmp_c, "content-type:"))) { if ((s2 = memchr(s, '\n', tmp_c + l - s))) { memmove(tmp, tmp + (s2 + 1 - tmp_c), tmp_c + l - 1 - s2); } else { tmp[s - tmp_c] = '\0'; } } efree(tmp_c); tmp_c = php_trim(tmp, strlen(tmp), NULL, 0, NULL, 3 TSRMLS_CC); efree(tmp); tmp = tmp_c; } user_headers = estrdup(tmp); /* Make lowercase for easy comparison against 'standard' headers */ php_strtolower(tmp, strlen(tmp)); if (strstr(tmp, "user-agent:")) { have_header |= HTTP_HEADER_USER_AGENT; } if (strstr(tmp, "host:")) { have_header |= HTTP_HEADER_HOST; } if (strstr(tmp, "from:")) { have_header |= HTTP_HEADER_FROM; } if (strstr(tmp, "authorization:")) { have_header |= HTTP_HEADER_AUTH; } if (strstr(tmp, "content-length:")) { have_header |= HTTP_HEADER_CONTENT_LENGTH; } if (strstr(tmp, "content-type:")) { have_header |= HTTP_HEADER_TYPE; } } efree(tmp); } /* auth header if it was specified */ if (((have_header & HTTP_HEADER_AUTH) == 0) && resource->user && resource->pass) { /* decode the strings first */ php_url_decode(resource->user, strlen(resource->user)); php_url_decode(resource->pass, strlen(resource->pass)); /* scratch is large enough, since it was made large enough for the whole URL */ strcpy(scratch, resource->user); strcat(scratch, ":"); strcat(scratch, resource->pass); tmp = php_base64_encode((unsigned char*)scratch, strlen(scratch), NULL); if (snprintf(scratch, scratch_len, "Authorization: Basic %s\r\n", tmp) > 0) { php_stream_write(stream, scratch, strlen(scratch)); php_stream_notify_info(context, PHP_STREAM_NOTIFY_AUTH_REQUIRED, NULL, 0); } efree(tmp); tmp = NULL; } /* if the user has configured who they are, send a From: line */ if (((have_header & HTTP_HEADER_FROM) == 0) && cfg_get_string("from", &tmp) == SUCCESS) { if (snprintf(scratch, scratch_len, "From: %s\r\n", tmp) > 0) php_stream_write(stream, scratch, strlen(scratch)); } /* Send Host: header so name-based virtual hosts work */ if ((have_header & HTTP_HEADER_HOST) == 0) { if ((use_ssl && resource->port != 443 && resource->port != 0) || (!use_ssl && resource->port != 80 && resource->port != 0)) { if (snprintf(scratch, scratch_len, "Host: %s:%i\r\n", resource->host, resource->port) > 0) php_stream_write(stream, scratch, strlen(scratch)); } else { if (snprintf(scratch, scratch_len, "Host: %s\r\n", resource->host) > 0) { php_stream_write(stream, scratch, strlen(scratch)); } } } if (context && php_stream_context_get_option(context, "http", "user_agent", &ua_zval) == SUCCESS && Z_TYPE_PP(ua_zval) == IS_STRING) { ua_str = Z_STRVAL_PP(ua_zval); } else if (FG(user_agent)) { ua_str = FG(user_agent); } if (((have_header & HTTP_HEADER_USER_AGENT) == 0) && ua_str) { #define _UA_HEADER "User-Agent: %s\r\n" char *ua; size_t ua_len; ua_len = sizeof(_UA_HEADER) + strlen(ua_str); /* ensure the header is only sent if user_agent is not blank */ if (ua_len > sizeof(_UA_HEADER)) { ua = emalloc(ua_len + 1); if ((ua_len = slprintf(ua, ua_len, _UA_HEADER, ua_str)) > 0) { ua[ua_len] = 0; php_stream_write(stream, ua, ua_len); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot construct User-agent header"); } if (ua) { efree(ua); } } } if (user_headers) { /* A bit weird, but some servers require that Content-Length be sent prior to Content-Type for POST * see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first. */ if ( header_init && context && !(have_header & HTTP_HEADER_CONTENT_LENGTH) && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0 ) { scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval)); php_stream_write(stream, scratch, scratch_len); have_header |= HTTP_HEADER_CONTENT_LENGTH; } php_stream_write(stream, user_headers, strlen(user_headers)); php_stream_write(stream, "\r\n", sizeof("\r\n")-1); efree(user_headers); } /* Request content, such as for POST requests */ if (header_init && context && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { if (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) { scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval)); php_stream_write(stream, scratch, scratch_len); } if (!(have_header & HTTP_HEADER_TYPE)) { php_stream_write(stream, "Content-Type: application/x-www-form-urlencoded\r\n", sizeof("Content-Type: application/x-www-form-urlencoded\r\n") - 1); php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Content-type not specified assuming application/x-www-form-urlencoded"); } php_stream_write(stream, "\r\n", sizeof("\r\n")-1); php_stream_write(stream, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); php_stream_write(stream, "\r\n\r\n", sizeof("\r\n\r\n")-1); } else { php_stream_write(stream, "\r\n", sizeof("\r\n")-1); } location[0] = '\0'; if (header_init) { zval *tmp; MAKE_STD_ZVAL(tmp); array_init(tmp); ZEND_SET_SYMBOL(EG(active_symbol_table), "http_response_header", tmp); } { zval **rh; zend_hash_find(EG(active_symbol_table), "http_response_header", sizeof("http_response_header"), (void **) &rh); response_header = *rh; } if (!php_stream_eof(stream)) { size_t tmp_line_len; /* get response header */ if (php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL) { zval *http_response; int response_code; if (tmp_line_len > 9) { response_code = atoi(tmp_line + 9); } else { response_code = 0; } /* when we request only the header, don't fail even on error codes */ if (options & STREAM_ONLY_GET_HEADERS) { reqok = 1; } switch(response_code) { case 200: case 206: /* partial content */ case 302: case 303: case 301: reqok = 1; break; case 403: php_stream_notify_error(context, PHP_STREAM_NOTIFY_AUTH_RESULT, tmp_line, response_code); break; default: /* safety net in the event tmp_line == NULL */ if (!tmp_line_len) { tmp_line[0] = '\0'; } php_stream_notify_error(context, PHP_STREAM_NOTIFY_FAILURE, tmp_line, response_code); } if (tmp_line[tmp_line_len - 1] == '\n') { --tmp_line_len; if (tmp_line[tmp_line_len - 1] == '\r') { --tmp_line_len; } } MAKE_STD_ZVAL(http_response); ZVAL_STRINGL(http_response, tmp_line, tmp_line_len, 1); zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_response, sizeof(zval *), NULL); } } else { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, unexpected end of socket!"); goto out; } /* read past HTTP headers */ http_header_line = emalloc(HTTP_HEADER_BLOCK_SIZE); while (!body && !php_stream_eof(stream)) { size_t http_header_line_length; if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) && *http_header_line != '\n' && *http_header_line != '\r') { char *e = http_header_line + http_header_line_length - 1; while (*e == '\n' || *e == '\r') { e--; } http_header_line_length = e - http_header_line + 1; http_header_line[http_header_line_length] = '\0'; if (!strncasecmp(http_header_line, "Location: ", 10)) { strlcpy(location, http_header_line + 10, sizeof(location)); } else if (!strncasecmp(http_header_line, "Content-Type: ", 14)) { php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_line + 14, 0); } else if (!strncasecmp(http_header_line, "Content-Length: ", 16)) { file_size = atoi(http_header_line + 16); php_stream_notify_file_size(context, file_size, http_header_line, 0); } if (http_header_line[0] == '\0') { body = 1; } else { zval *http_header; MAKE_STD_ZVAL(http_header); ZVAL_STRINGL(http_header, http_header_line, http_header_line_length, 1); zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL); } } else { break; } } if (!reqok || location[0] != '\0') { if (options & STREAM_ONLY_GET_HEADERS && redirect_max <= 1) { goto out; } if (location[0] != '\0') php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0); php_stream_close(stream); stream = NULL; if (location[0] != '\0') { char new_path[HTTP_HEADER_BLOCK_SIZE]; char loc_path[HTTP_HEADER_BLOCK_SIZE]; *new_path='\0'; if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) && strncasecmp(location, "https://", sizeof("https://")-1) && strncasecmp(location, "ftp://", sizeof("ftp://")-1) && strncasecmp(location, "ftps://", sizeof("ftps://")-1))) { if (*location != '/') { if (*(location+1) != '\0' && resource->path) { char *s = strrchr(resource->path, '/'); if (!s) { s = resource->path; if (!s[0]) { efree(s); s = resource->path = estrdup("/"); } else { *s = '/'; } } s[1] = '\0'; if (resource->path && *(resource->path) == '/' && *(resource->path + 1) == '\0') { snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", resource->path, location); } else { snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", resource->path, location); } } else { snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location); } } else { strlcpy(loc_path, location, sizeof(loc_path)); } if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) { snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", resource->scheme, resource->host, resource->port, loc_path); } else { snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", resource->scheme, resource->host, loc_path); } } else { strlcpy(new_path, location, sizeof(new_path)); } php_url_free(resource); /* check for invalid redirection URLs */ if ((resource = php_url_parse(new_path)) == NULL) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); goto out; } #define CHECK_FOR_CNTRL_CHARS(val) { \ if (val) { \ unsigned char *s, *e; \ int l; \ l = php_url_decode(val, strlen(val)); \ s = val; e = s + l; \ while (s < e) { \ if (iscntrl(*s)) { \ php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); \ goto out; \ } \ s++; \ } \ } \ } \ /* check for control characters in login, password & path */ if (strncasecmp(new_path, "http://", sizeof("http://") - 1) || strncasecmp(new_path, "https://", sizeof("https://") - 1)) { CHECK_FOR_CNTRL_CHARS(resource->user) CHECK_FOR_CNTRL_CHARS(resource->pass) CHECK_FOR_CNTRL_CHARS(resource->path) } stream = php_stream_url_wrap_http_ex(wrapper, new_path, mode, options, opened_path, context, --redirect_max, 0 STREAMS_CC TSRMLS_CC); } else {