Пример #1
0
static php_vedis_t *
php_vedis_get(char *storage, int storage_len, zend_bool is_persistent TSRMLS_DC)
{
    php_vedis_t *vedis;
    char plist_key[48];
    int plist_key_len;
    zend_rsrc_list_entry le, *le_p = NULL;

    if (is_persistent) {
        plist_key_len = snprintf(plist_key, 48, "vedis");
        plist_key_len += 1;

        if (zend_hash_find(&EG(persistent_list), plist_key, plist_key_len,
                           (void *)&le_p) == SUCCESS) {
            if (le_p->type == le_vedis) {
                return (php_vedis_t *) le_p->ptr;
            }
        }
    }

    vedis = php_vedis_new(storage, storage_len, is_persistent TSRMLS_CC);
    if (!vedis) {
        return NULL;
    }

    if (is_persistent) {
        le.type = le_vedis;
        le.ptr  = vedis;
        if (zend_hash_update(&EG(persistent_list),
                             (char *)plist_key, plist_key_len, (void *)&le,
                             sizeof(le), NULL) == FAILURE) {
            php_error_docref(NULL TSRMLS_CC, E_ERROR,
                             "Could not register persistent entry for vedis");
        }
    }
    return vedis;
}
Пример #2
0
/* {{{ proto Router Router::setDefault(Callable handler) 
	Throws RoutingException on failure 
	The default route is invoked for web requests that match no other route */
static PHP_METHOD(Router, setDefault) {
	zval *callable;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &callable) != SUCCESS) {
		return;
	}

	{
		char *callable_name = NULL;

		if (zend_is_callable(callable, 0, &callable_name TSRMLS_CC)) {
			route_t route = {ROUTER_ROUTE_DEFAULT};

			route.callable = callable;
			
			Z_ADDREF_P(route.callable);

			{
				router_t *router = getRouter();
				
				zend_hash_update(
					&router->routes, 
					Default_Route, Default_Route_Size,
					(void**)&route, sizeof(route_t), (void**)&router->fallback);
			}
		} else {
			zend_throw_exception(
				RoutingException, "handler is not callable", 0 TSRMLS_CC);
		}

		if (callable_name) {
			efree(callable_name);
		}
	}

	RETURN_CHAIN();
} /* }}} */
Пример #3
0
void* connect_pool_perisent(zval* zres, int port)
{
    zend_rsrc_list_entry sock_le;
    int ret;
    cpClient* cli = (cpClient*) pecalloc(sizeof (cpClient), 1, 1);
    if (cpClient_create(cli) < 0)
    {
        php_error_docref(NULL TSRMLS_CC, E_ERROR, "pdo_connect_pool: create sock fail. Error: %s [%d]", strerror(errno), errno);
    }
    cli->port = port;
    ret = cpClient_connect(cli, "127.0.0.1", cli->port, (float) 100, 0); //所有的操作100s超时
    if (ret < 0)
    {
        pefree(cli, 1);
        return NULL;
    }
    sock_le.type = le_cli_connect_pool;
    sock_le.ptr = cli;
    ZEND_REGISTER_RESOURCE(zres, cli, le_cli_connect_pool);
    char str[100] = {0};
    CON_FORMART_KEY(str, cli->port);
    zend_hash_update(&EG(persistent_list), str, strlen(str), (void*) &sock_le, sizeof (zend_rsrc_list_entry), NULL);
    return cli;
}
Пример #4
0
static int fcgi_get_params(fcgi_request *req, unsigned char *p, unsigned char *end)
{
	char buf[128];
	char *tmp = buf;
	size_t buf_size = sizeof(buf);
	int name_len = 0;
	int val_len = 0;
	uint eff_name_lenk = 0;
	char *s;
	int ret = 1;
	size_t bytes_consumed;

	while (p < end) {
		bytes_consumed = fcgi_get_params_len(&name_len, p, end);
		if (!bytes_consumed) {
			/* Malformated request */
			ret = 0;
			break;
		}
		p += bytes_consumed;
		bytes_consumed = fcgi_get_params_len(&val_len, p, end);
		if (!bytes_consumed) {
			/* Malformated request */
			ret = 0;
			break;
		}
		p += bytes_consumed;
		if (name_len > (INT_MAX - val_len) || /* would the addition overflow? */
		    name_len + val_len > end - p) {   /* would we exceed the buffer? */
			/* Malformated request */
			ret = 0;
			break;
		}

		/*
		 * get the effective length of the name in case it's not a valid string
		 * don't do this on the value because it can be binary data
		 */
		if (!fcgi_param_get_eff_len(p, p+name_len, &eff_name_len)){
			/* Malicious request */
			ret = 0;
			break;
		}
		if (eff_name_len >= buf_size-1) {
			if (eff_name_len > ((uint)-1)-64) { 
				ret = 0;
				break;
			}
			buf_size = eff_name_len + 64;
			tmp = (tmp == buf ? emalloc(buf_size): erealloc(tmp, buf_size));
			if (tmp == NULL) {
				ret = 0;
				break;
			}
		}
		memcpy(tmp, p, eff_name_len);
		tmp[eff_name_len] = 0;
		s = estrndup((char*)p + name_len, val_len);
		if (s == NULL) {
			ret = 0;
			break;
		}
		zend_hash_update(req->env, tmp, eff_name_len+1, &s, sizeof(char*), NULL);
		p += name_len + val_len;
	}
	if (tmp != buf && tmp != NULL) {
		efree(tmp);
	}
	return ret;
}
Пример #5
0
static zend_always_inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, zend_long elements, int objprops)
{
	while (elements-- > 0) {
		zval key, *data, d, *old_data;
		zend_ulong idx;

		ZVAL_UNDEF(&key);

		if (!php_var_unserialize_ex(&key, p, max, NULL, classes)) {
			zval_dtor(&key);
			return 0;
		}

		data = NULL;
		ZVAL_UNDEF(&d);

		if (!objprops) {
			if (Z_TYPE(key) == IS_LONG) {
				idx = Z_LVAL(key);
numeric_key:
				if (UNEXPECTED((old_data = zend_hash_index_find(ht, idx)) != NULL)) {
					//??? update hash
					var_push_dtor(var_hash, old_data);
					data = zend_hash_index_update(ht, idx, &d);
				} else {
					data = zend_hash_index_add_new(ht, idx, &d);
				}
			} else if (Z_TYPE(key) == IS_STRING) {
				if (UNEXPECTED(ZEND_HANDLE_NUMERIC(Z_STR(key), idx))) {
					goto numeric_key;
				}
				if (UNEXPECTED((old_data = zend_hash_find(ht, Z_STR(key))) != NULL)) {
					//??? update hash
					var_push_dtor(var_hash, old_data);
					data = zend_hash_update(ht, Z_STR(key), &d);
				} else {
					data = zend_hash_add_new(ht, Z_STR(key), &d);
				}
			} else {
				zval_dtor(&key);
				return 0;
			}
		} else {
			if (EXPECTED(Z_TYPE(key) == IS_STRING)) {
string_key:
				if ((old_data = zend_hash_find(ht, Z_STR(key))) != NULL) {
					if (Z_TYPE_P(old_data) == IS_INDIRECT) {
						old_data = Z_INDIRECT_P(old_data);
					}
					var_push_dtor(var_hash, old_data);
					data = zend_hash_update_ind(ht, Z_STR(key), &d);
				} else {
					data = zend_hash_add_new(ht, Z_STR(key), &d);
				}
			} else if (Z_TYPE(key) == IS_LONG) {
				/* object properties should include no integers */
				convert_to_string(&key);
				goto string_key;
			} else {
				zval_dtor(&key);
				return 0;
			}
		}

		if (!php_var_unserialize_ex(data, p, max, var_hash, classes)) {
			zval_dtor(&key);
			return 0;
		}

		if (UNEXPECTED(Z_ISUNDEF_P(data))) {
			if (Z_TYPE(key) == IS_LONG) {
				zend_hash_index_del(ht, Z_LVAL(key));
			} else {
				zend_hash_del_ind(ht, Z_STR(key));
			}
		} else {
			var_push_dtor(var_hash, data);
		}

		zval_dtor(&key);

		if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
			(*p)--;
			return 0;
		}
	}

	return 1;
}
Пример #6
0
static HashTable *zend_closure_get_debug_info(zval *object, int *is_temp) /* {{{ */
{
	zend_closure *closure = (zend_closure *)Z_OBJ_P(object);
	zval val;
	struct _zend_arg_info *arg_info = closure->func.common.arg_info;
	HashTable *debug_info;
	zend_bool zstr_args = (closure->func.type == ZEND_USER_FUNCTION) || (closure->func.common.fn_flags & ZEND_ACC_USER_ARG_INFO);

	*is_temp = 1;

	debug_info = zend_new_array(8);

	if (closure->func.type == ZEND_USER_FUNCTION && closure->func.op_array.static_variables) {
		HashTable *static_variables = closure->func.op_array.static_variables;
		ZVAL_ARR(&val, zend_array_dup(static_variables));
		zend_hash_update(debug_info, ZSTR_KNOWN(ZEND_STR_STATIC), &val);
	}

	if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
		Z_ADDREF(closure->this_ptr);
		zend_hash_update(debug_info, ZSTR_KNOWN(ZEND_STR_THIS), &closure->this_ptr);
	}

	if (arg_info &&
		(closure->func.common.num_args ||
		 (closure->func.common.fn_flags & ZEND_ACC_VARIADIC))) {
		uint32_t i, num_args, required = closure->func.common.required_num_args;

		array_init(&val);

		num_args = closure->func.common.num_args;
		if (closure->func.common.fn_flags & ZEND_ACC_VARIADIC) {
			num_args++;
		}
		for (i = 0; i < num_args; i++) {
			zend_string *name;
			zval info;
			if (arg_info->name) {
				if (zstr_args) {
					name = zend_strpprintf(0, "%s$%s",
							arg_info->pass_by_reference ? "&" : "",
							ZSTR_VAL(arg_info->name));
				} else {
					name = zend_strpprintf(0, "%s$%s",
							arg_info->pass_by_reference ? "&" : "",
							((zend_internal_arg_info*)arg_info)->name);
				}
			} else {
				name = zend_strpprintf(0, "%s$param%d",
						arg_info->pass_by_reference ? "&" : "",
						i + 1);
			}
			ZVAL_NEW_STR(&info, zend_strpprintf(0, "%s", i >= required ? "<optional>" : "<required>"));
			zend_hash_update(Z_ARRVAL(val), name, &info);
			zend_string_release_ex(name, 0);
			arg_info++;
		}
		zend_hash_str_update(debug_info, "parameter", sizeof("parameter")-1, &val);
	}

	return debug_info;
}
Пример #7
0
static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops)
{
	while (elements-- > 0) {
		zval *key, *data, **old_data;

		ALLOC_INIT_ZVAL(key);

		if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) {
			zval_dtor(key);
			FREE_ZVAL(key);
			return 0;
		}

		if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) {
			zval_dtor(key);
			FREE_ZVAL(key);
			return 0;
		}

		ALLOC_INIT_ZVAL(data);

		if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) {
			zval_dtor(key);
			FREE_ZVAL(key);
			zval_dtor(data);
			FREE_ZVAL(data);
			return 0;
		}

		if (!objprops) {
			switch (Z_TYPE_P(key)) {
			case IS_LONG:
				if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) {
					var_push_dtor(var_hash, old_data);
				}
				zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL);
				break;
			case IS_STRING:
				if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
					var_push_dtor(var_hash, old_data);
				}
				zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL);
				break;
			}
		} else {
			/* object properties should include no integers */
			convert_to_string(key);
			zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data,
					sizeof data, NULL);
		}
		
		zval_dtor(key);
		FREE_ZVAL(key);

		if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
			(*p)--;
			return 0;
		}
	}

	return 1;
}
Пример #8
0
PHP_METHOD(Edge_Controller, model)
{
    char *model_name = NULL;
    char *model_dir = NULL;
    int mnlen=0;
    int mdlen=0;
    if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &model_name, &mnlen, &model_dir, &mdlen) == FAILURE)
    {
        RETURN_FALSE;
    }
    
    char *model_class_name;
    int class_name_len;
    class_name_len = spprintf(&model_class_name, 0, "%s%s", model_name, "Model");

    zval **z_obj;
    if(zend_hash_find(Z_ARRVAL_P(EDGE_G(regs)), model_class_name, class_name_len+1, (void **)&z_obj) == SUCCESS)
    {
        efree(model_class_name);
        RETURN_ZVAL(*z_obj, 1, 0);
    }
    
    zval *config;
    zval *config_data;
    config = zend_read_static_property(edge_core_ce, ZEND_STRL("config"), 1 TSRMLS_DC);
    config_data = zend_read_property(edge_config_ce, config, ZEND_STRL("_data"), 1 TSRMLS_DC);

    zval **models_home_pp;
    if(zend_hash_find(Z_ARRVAL_P(config_data), "_models_home", strlen("_models_home")+1, (void **)&models_home_pp) == FAILURE)
    {
        RETURN_FALSE;
    }
    
    zval *z_model_name;
    MAKE_STD_ZVAL(z_model_name);
    ZVAL_STRING(z_model_name, model_class_name, 1);

    zval *loader;
    zval *ret;
    loader = zend_read_static_property(edge_core_ce, ZEND_STRL("loader"), 1 TSRMLS_DC);
    zend_call_method_with_2_params(&loader, Z_OBJCE_P(loader), NULL, "autoload", &ret, z_model_name, *models_home_pp);
    zval_ptr_dtor(&z_model_name);
    if(!Z_BVAL_P(ret))
    {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "model %s%s load fail", Z_STRVAL_PP(models_home_pp), model_class_name);
        zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "model %s%s load fail", Z_STRVAL_PP(models_home_pp), model_class_name);
        zval_ptr_dtor(&ret);
        efree(model_class_name);
        RETURN_FALSE;
    }
    zval_ptr_dtor(&ret);

    zend_class_entry **model_ce;
    if(zend_lookup_class(model_class_name, class_name_len, &model_ce TSRMLS_CC) == FAILURE)
    {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "model class %s not exist", model_class_name);
        zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "model class %s%s  not exist", model_class_name);
        efree(model_class_name);
        RETURN_FALSE;
    }

    zval *model_obj;
    MAKE_STD_ZVAL(model_obj);
    object_init_ex(model_obj, *model_ce);

    zval **cfptr;
    if(zend_hash_find(&((*model_ce)->function_table), "__construct", strlen("__construct")+1, (void **)&cfptr) == SUCCESS)
    {
        zval *cretval;
        zend_call_method(&model_obj, *model_ce, NULL, "__construct", strlen("__construct"), &cretval, 0, NULL, NULL TSRMLS_CC);
        zval_ptr_dtor(&cretval);
    }

    zend_hash_update(Z_ARRVAL_P(EDGE_G(regs)), model_class_name, class_name_len+1, (void **)&model_obj, sizeof(zval *), NULL);

    efree(model_class_name);
    RETURN_ZVAL(model_obj, 1, 0);
}
Пример #9
0
static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, zend_long elements, int objprops)
{
	while (elements-- > 0) {
		zval key, *data, d, *old_data;

		ZVAL_UNDEF(&key);
		if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) {
			zval_dtor(&key);
			return 0;
		}

		if (Z_TYPE(key) != IS_LONG && Z_TYPE(key) != IS_STRING) {
			zval_dtor(&key);
			return 0;
		}

		data = NULL;
		ZVAL_UNDEF(&d);

		if (!objprops) {
			switch (Z_TYPE(key)) {
			case IS_LONG:
				if ((old_data = zend_hash_index_find(ht, Z_LVAL(key))) != NULL) {
					//??? update hash
					var_push_dtor(var_hash, old_data);
				}
				data = zend_hash_index_update(ht, Z_LVAL(key), &d);
				break;
			case IS_STRING:
				if ((old_data = zend_symtable_find(ht, Z_STR(key))) != NULL) {
					//??? update hash
					var_push_dtor(var_hash, old_data);
				}
				data = zend_symtable_update(ht, Z_STR(key), &d);
				break;
			}
		} else {
			/* object properties should include no integers */
			convert_to_string(&key);
//???
#if 1
			data = zend_hash_update_ind(ht, Z_STR(key), &d);
#else
			if ((data = zend_hash_find(ht, Z_STR(key))) != NULL) {
				if (Z_TYPE_P(data) == IS_INDIRECT) {
					data = Z_INDIRECT_P(data);
				}
				zval_ptr_dtor(data);
//???				var_push_dtor(var_hash, data);
				ZVAL_UNDEF(data);
			} else {
				data = zend_hash_update(ht, Z_STR(key), &d);
			}
#endif
		}
		
		zval_dtor(&key);

		if (!php_var_unserialize(data, p, max, var_hash TSRMLS_CC)) {
			return 0;
		}

		if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
			(*p)--;
			return 0;
		}
	}

	return 1;
}
Пример #10
0
/* {{{ static void php_couchbase_get_callback(...)
 */
static void
php_couchbase_get_callback(lcb_t instance,
						   const void *cookie,
						   lcb_error_t error,
						   const lcb_get_resp_t *resp)
{
	zval *retval;
	php_couchbase_ctx *ctx = (php_couchbase_ctx *)cookie;
	const void *key;
	size_t nkey;
	const void *bytes;
	size_t nbytes;
	uint32_t flags;
	uint64_t cas;


	TSRMLS_FETCH();

	if (--ctx->res->seqno == 0) {
		pcbc_stop_loop(ctx->res);
	}

	if (resp->version != 0) {
		ctx->res->rc = LCB_ERROR;
		return;
	}
	key = resp->v.v0.key;
	nkey = resp->v.v0.nkey;
	bytes = resp->v.v0.bytes;
	nbytes = resp->v.v0.nbytes;
	flags = resp->v.v0.flags;
	cas = resp->v.v0.cas;

	ctx->res->rc = error;
	if (LCB_SUCCESS != error && LCB_KEY_ENOENT != error) {
		pcbc_stop_loop(ctx->res);
		return;
	}

	if (ctx->res->async) { /* get_delayed */
		zval *k, *v;
		MAKE_STD_ZVAL(v);
		if (!php_couchbase_zval_from_payload(v, (char *)bytes, nbytes, flags, ctx->res->serializer, ctx->res->ignoreflags TSRMLS_CC)) {
			ctx->res->rc = LCB_ERROR;
			efree(v);
			return;
		}

		if (ctx->res->prefix_key_len && nkey) {
			if (!strncmp(key, ctx->res->prefix_key, ctx->res->prefix_key_len)) {
				nkey -= (ctx->res->prefix_key_len + 1); /* '_' */
				key = estrndup(((const char *)key) + ctx->res->prefix_key_len + 1, nkey);
			}
		}

		MAKE_STD_ZVAL(retval);
		array_init(retval);
		zend_hash_next_index_insert(Z_ARRVAL_P(ctx->rv), (void **)&retval, sizeof(zval *), NULL);

		MAKE_STD_ZVAL(k);
		ZVAL_STRINGL(k, (char *)key, nkey, 1);

		zend_hash_add(Z_ARRVAL_P(retval), "key", sizeof("key"), (void **)&k, sizeof(zval *), NULL);
		zend_hash_add(Z_ARRVAL_P(retval), "value", sizeof("value"), (void **)&v, sizeof(zval *), NULL);

		if (ctx->flags) {
			zval *c;
			MAKE_STD_ZVAL(c);
			Z_TYPE_P(c) = IS_STRING;
			Z_STRLEN_P(c) = spprintf(&(Z_STRVAL_P(c)), 0, "%llu", cas);
			zend_hash_add(Z_ARRVAL_P(retval), "cas", sizeof("cas"), (void **)&c, sizeof(zval *), NULL);
		}

		if (ctx->res->prefix_key_len && nkey) {
			efree((void *)key);
		}
	} else {
		if (LCB_KEY_ENOENT == error) {
			return;
		}

		if (IS_ARRAY == Z_TYPE_P(ctx->rv)) { /* multi get */
			zval *v;
			char *key_string = NULL;
			MAKE_STD_ZVAL(v);
			if (!php_couchbase_zval_from_payload(v, (char *)bytes, nbytes, flags, ctx->res->serializer, ctx->res->ignoreflags TSRMLS_CC)) {
				ctx->res->rc = LCB_ERROR;
				efree(v);
				return;
			}

			if (ctx->res->prefix_key_len && nkey) {
				if (!strncmp(key, ctx->res->prefix_key, ctx->res->prefix_key_len)) {
					nkey -= (ctx->res->prefix_key_len + 1);
					key_string = estrndup(((const char *)key) + ctx->res->prefix_key_len + 1, nkey);
				}
			} else {
				key_string = emalloc(nkey + 1);
				memcpy(key_string, key, nkey);
				key_string[nkey] = '\0';
			}
			zend_hash_update((Z_ARRVAL_P(ctx->rv)), (char *)key_string, nkey + 1, (void **)&v, sizeof(zval *), NULL);

			if (ctx->cas) {
				zval *c;
				MAKE_STD_ZVAL(c);
				Z_TYPE_P(c) = IS_STRING;
				Z_STRLEN_P(c) = spprintf(&(Z_STRVAL_P(c)), 0, "%llu", cas);
				zend_hash_add(Z_ARRVAL_P(ctx->cas), (char *)key_string, nkey + 1, (void **)&c, sizeof(zval *), NULL);
			}
			efree(key_string);
		} else {
			if (ctx->res->prefix_key_len && nkey) {
				if (!strncmp(key, ctx->res->prefix_key, ctx->res->prefix_key_len)) {
					nkey -= (ctx->res->prefix_key_len + 1);
					key = estrndup(((const char *)key) + ctx->res->prefix_key_len + 1, nkey);
				}
			}
			if (!php_couchbase_zval_from_payload(ctx->rv, (char *)bytes, nbytes, flags, ctx->res->serializer, ctx->res->ignoreflags TSRMLS_CC)) {
				if (ctx->res->prefix_key_len && nkey) {
					efree((void *)key);
				}
				ctx->res->rc = LCB_ERROR;
				return;
			}
			if (ctx->res->prefix_key_len && nkey) {
				efree((void *)key);
			}
			if (ctx->cas) {
				Z_TYPE_P(ctx->cas) = IS_STRING;
				Z_STRLEN_P(ctx->cas) = spprintf(&(Z_STRVAL_P(ctx->cas)), 0, "%llu", cas);
			}
		}
	}
}
Пример #11
0
/* {{{ php_ini_parser_cb
 */
static void php_ini_parser_cb(zval *arg1, zval *arg2, zval *arg3, int callback_type, HashTable *target_hash)
{
	zval *entry;
	HashTable *active_hash;
	char *extension_name;

	if (active_ini_hash) {
		active_hash = active_ini_hash;
	} else {
		active_hash = target_hash;
	}

	switch (callback_type) {
		case ZEND_INI_PARSER_ENTRY: {
				if (!arg2) {
					/* bare string - nothing to do */
					break;
				}

				/* PHP and Zend extensions are not added into configuration hash! */
				if (!is_special_section && !strcasecmp(Z_STRVAL_P(arg1), PHP_EXTENSION_TOKEN)) { /* load PHP extension */
					extension_name = estrndup(Z_STRVAL_P(arg2), Z_STRLEN_P(arg2));
					zend_llist_add_element(&extension_lists.functions, &extension_name);
				} else if (!is_special_section && !strcasecmp(Z_STRVAL_P(arg1), ZEND_EXTENSION_TOKEN)) { /* load Zend extension */
					extension_name = estrndup(Z_STRVAL_P(arg2), Z_STRLEN_P(arg2));
					zend_llist_add_element(&extension_lists.engine, &extension_name);

				/* All other entries are added into either configuration_hash or active ini section array */
				} else {
					/* Store in active hash */
					entry = zend_hash_update(active_hash, Z_STR_P(arg1), arg2);
					Z_STR_P(entry) = zend_string_dup(Z_STR_P(entry), 1);
				}
			}
			break;

		case ZEND_INI_PARSER_POP_ENTRY: {
				zval option_arr;
				zval *find_arr;

				if (!arg2) {
					/* bare string - nothing to do */
					break;
				}

/* fprintf(stdout, "ZEND_INI_PARSER_POP_ENTRY: %s[%s] = %s\n",Z_STRVAL_P(arg1), Z_STRVAL_P(arg3), Z_STRVAL_P(arg2)); */

				/* If option not found in hash or is not an array -> create array, otherwise add to existing array */
				if ((find_arr = zend_hash_find(active_hash, Z_STR_P(arg1))) == NULL || Z_TYPE_P(find_arr) != IS_ARRAY) {
					ZVAL_NEW_PERSISTENT_ARR(&option_arr);
					zend_hash_init(Z_ARRVAL(option_arr), 8, NULL, config_zval_dtor, 1);
					find_arr = zend_hash_update(active_hash, Z_STR_P(arg1), &option_arr);
				}

				/* arg3 is possible option offset name */
				if (arg3 && Z_STRLEN_P(arg3) > 0) {
					entry = zend_symtable_update(Z_ARRVAL_P(find_arr), Z_STR_P(arg3), arg2);
				} else {
					entry = zend_hash_next_index_insert(Z_ARRVAL_P(find_arr), arg2);
				}
				Z_STR_P(entry) = zend_string_dup(Z_STR_P(entry), 1);
			}
			break;

		case ZEND_INI_PARSER_SECTION: { /* Create an array of entries of each section */

/* fprintf(stdout, "ZEND_INI_PARSER_SECTION: %s\n",Z_STRVAL_P(arg1)); */

				char *key = NULL;
				size_t key_len;

				/* PATH sections */
				if (!strncasecmp(Z_STRVAL_P(arg1), "PATH", sizeof("PATH") - 1)) {
					key = Z_STRVAL_P(arg1);
					key = key + sizeof("PATH") - 1;
					key_len = Z_STRLEN_P(arg1) - sizeof("PATH") + 1;
					is_special_section = 1;
					has_per_dir_config = 1;

					/* make the path lowercase on Windows, for case insensitivity. Does nothing for other platforms */
					TRANSLATE_SLASHES_LOWER(key);

				/* HOST sections */
				} else if (!strncasecmp(Z_STRVAL_P(arg1), "HOST", sizeof("HOST") - 1)) {
					key = Z_STRVAL_P(arg1);
					key = key + sizeof("HOST") - 1;
					key_len = Z_STRLEN_P(arg1) - sizeof("HOST") + 1;
					is_special_section = 1;
					has_per_host_config = 1;
					zend_str_tolower(key, key_len); /* host names are case-insensitive. */

				} else {
					is_special_section = 0;
				}

				if (key && key_len > 0) {
					/* Strip any trailing slashes */
					while (key_len > 0 && (key[key_len - 1] == '/' || key[key_len - 1] == '\\')) {
						key_len--;
						key[key_len] = 0;
					}

					/* Strip any leading whitespace and '=' */
					while (*key && (
						*key == '=' ||
						*key == ' ' ||
						*key == '\t'
					)) {
						key++;
						key_len--;
					}

					/* Search for existing entry and if it does not exist create one */
					if ((entry = zend_hash_str_find(target_hash, key, key_len)) == NULL) {
						zval section_arr;

						ZVAL_NEW_PERSISTENT_ARR(&section_arr);
						zend_hash_init(Z_ARRVAL(section_arr), 8, NULL, (dtor_func_t) config_zval_dtor, 1);
						entry = zend_hash_str_update(target_hash, key, key_len, &section_arr);
					}
					active_ini_hash = Z_ARRVAL_P(entry);
				}
			}
			break;
	}
}
Пример #12
0
// file_get_contents
// and then 
// parse all tags
static void parse_sys_tags(const char *filename) 
{
	long size, maxsize;
	int error = 0;

	FILE *fp = VCWD_FOPEN(filename, "rb");
	if (!fp) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "tpl_tags file error(%s)", filename);
		return ;
	}
	fseek(fp, 0, SEEK_END);
	maxsize = ftell(fp);
	rewind(fp);
	if (maxsize > 2097152) // 2M limit
		maxsize = 2097152;
	char *contents = (char *)emalloc(maxsize + 1);
	size = fread(contents, 1, maxsize, fp);
	fclose(fp);
	if (size < 0)
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "tpl_tags file error(%s)", filename);
	if (size <= 0)
		return;
	contents[size] = '\0';

	// parse
	const int S_KEY_START = 0, S_KEY_END = 1, S_CONT_START = 2;
	int state = S_KEY_START;
	char *tag_name, *tag_content;
	char *p, *cur = contents, *end = contents + size - 1;
	while (cur < end) {
		p = strstr(cur, "---");
		if (p == NULL) {
			cur = end;
			if (state != S_CONT_START)
				break;
		} else {
			cur = p + 3;
			p--;
		}
		if (state == S_CONT_START) {
			if (p == NULL)
				p = end;
			while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
				p--;
			*++p = '\0';
			// add tag
			char *tmp_s = pestrdup(tag_content, 1);
			zend_hash_update(STU_G(tpl_tags_sys), tag_name, strlen(tag_name) + 1, &tmp_s, sizeof(char *), NULL);
			state = S_KEY_START;
			if (cur == end) 
				break;
		}
		if (state == S_KEY_START) {
			while (cur < end && (*cur == ' ' || *cur == '\t' || *cur == '-')) // cannot has newline arround tag_name
				cur++;
			if ((*cur >= 'A' && *cur <= 'Z') || (*cur >= 'a' && *cur <= 'z') || *cur == '_')
				tag_name = cur;
			else {
				// tag name must start with [a-zA-Z_]
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "tag name must start with [a-zA-Z_] (%s)", tag_name);
				break;
			}
			state = S_KEY_END;
		} else if (state == S_KEY_END) {
			while (*p == ' ' || *p == '\t' || *cur == '-') // cannot has newline arround tag_name
				p--;
			*++p = '\0';
			while (cur < end && (*cur == ' ' || *cur++ == '\t' || *cur == '\n' || *cur == '\r'))
				cur++;
			tag_content = cur;
			state = S_CONT_START;
		}
	}
	efree(contents);
}
Пример #13
0
static
void binary_deserialize(int8_t thrift_typeID, PHPInputTransport& transport, zval* return_value, HashTable* fieldspec) {
    ZVAL_NULL(return_value);

    switch (thrift_typeID) {
    case T_STOP:
    case T_VOID:
        RETURN_NULL();
        return;
    case T_STRUCT: {
        zval* val_ptr = zend_hash_str_find(fieldspec, "class", sizeof("class")-1);
        if (val_ptr == nullptr) {
            throw_tprotocolexception("no class type in spec", INVALID_DATA);
            skip_element(T_STRUCT, transport);
            RETURN_NULL();
        }

        char* structType = Z_STRVAL_P(val_ptr);
        // Create an object in PHP userland based on our spec
        createObject(structType, return_value);
        if (Z_TYPE_P(return_value) == IS_NULL) {
            // unable to create class entry
            skip_element(T_STRUCT, transport);
            RETURN_NULL();
        }

        zval* spec = zend_read_static_property(Z_OBJCE_P(return_value), "_TSPEC", sizeof("_TSPEC")-1, false);
        if (Z_TYPE_P(spec) != IS_ARRAY) {
            char errbuf[128];
            snprintf(errbuf, 128, "spec for %s is wrong type: %d\n", structType, Z_TYPE_P(spec));
            throw_tprotocolexception(errbuf, INVALID_DATA);
            RETURN_NULL();
        }
        binary_deserialize_spec(return_value, transport, Z_ARRVAL_P(spec));
        return;
    }
    break;
    case T_BOOL: {
        uint8_t c;
        transport.readBytes(&c, 1);
        RETURN_BOOL(c != 0);
    }
    //case T_I08: // same numeric value as T_BYTE
    case T_BYTE: {
        uint8_t c;
        transport.readBytes(&c, 1);
        RETURN_LONG((int8_t)c);
    }
    case T_I16: {
        uint16_t c;
        transport.readBytes(&c, 2);
        RETURN_LONG((int16_t)ntohs(c));
    }
    case T_I32: {
        uint32_t c;
        transport.readBytes(&c, 4);
        RETURN_LONG((int32_t)ntohl(c));
    }
    case T_U64:
    case T_I64: {
        uint64_t c;
        transport.readBytes(&c, 8);
        RETURN_LONG((int64_t)ntohll(c));
    }
    case T_DOUBLE: {
        union {
            uint64_t c;
            double d;
        } a;
        transport.readBytes(&(a.c), 8);
        a.c = ntohll(a.c);
        RETURN_DOUBLE(a.d);
    }
    //case T_UTF7: // aliases T_STRING
    case T_UTF8:
    case T_UTF16:
    case T_STRING: {
        uint32_t size = transport.readU32();
        if (size) {
            char strbuf[size+1];
            transport.readBytes(strbuf, size);
            strbuf[size] = '\0';
            ZVAL_STRINGL(return_value, strbuf, size);
        } else {
            ZVAL_EMPTY_STRING(return_value);
        }
        return;
    }
    case T_MAP: { // array of key -> value
        uint8_t types[2];
        transport.readBytes(types, 2);
        uint32_t size = transport.readU32();
        array_init(return_value);

        zval *val_ptr;
        val_ptr = zend_hash_str_find(fieldspec, "key", sizeof("key")-1);
        HashTable* keyspec = Z_ARRVAL_P(val_ptr);
        val_ptr = zend_hash_str_find(fieldspec, "val", sizeof("val")-1);
        HashTable* valspec = Z_ARRVAL_P(val_ptr);

        for (uint32_t s = 0; s < size; ++s) {
            zval key, value;

            binary_deserialize(types[0], transport, &key, keyspec);
            binary_deserialize(types[1], transport, &value, valspec);
            if (Z_TYPE(key) == IS_LONG) {
                zend_hash_index_update(Z_ARR_P(return_value), Z_LVAL(key), &value);
            } else {
                if (Z_TYPE(key) != IS_STRING) convert_to_string(&key);
                zend_hash_update(Z_ARR_P(return_value), Z_STR(key), &value);
            }
        }
        return; // return_value already populated
    }
    case T_LIST: { // array with autogenerated numeric keys
        int8_t type = transport.readI8();
        uint32_t size = transport.readU32();
        zval *val_ptr = zend_hash_str_find(fieldspec, "elem", sizeof("elem")-1);
        HashTable* elemspec = Z_ARRVAL_P(val_ptr);

        array_init(return_value);
        for (uint32_t s = 0; s < size; ++s) {
            zval value;
            binary_deserialize(type, transport, &value, elemspec);
            zend_hash_next_index_insert(Z_ARR_P(return_value), &value);
        }
        return;
    }
    case T_SET: { // array of key -> TRUE
        uint8_t type;
        uint32_t size;
        transport.readBytes(&type, 1);
        transport.readBytes(&size, 4);
        size = ntohl(size);
        zval *val_ptr = zend_hash_str_find(fieldspec, "elem", sizeof("elem")-1);
        HashTable* elemspec = Z_ARRVAL_P(val_ptr);

        array_init(return_value);

        for (uint32_t s = 0; s < size; ++s) {
            zval key, value;
            ZVAL_UNDEF(&value);

            binary_deserialize(type, transport, &key, elemspec);

            if (Z_TYPE(key) == IS_LONG) {
                zend_hash_index_update(Z_ARR_P(return_value), Z_LVAL(key), &value);
            } else {
                if (Z_TYPE(key) != IS_STRING) convert_to_string(&key);
                zend_hash_update(Z_ARR_P(return_value), Z_STR(key), &value);
            }
        }
        return;
    }
    };

    char errbuf[128];
    sprintf(errbuf, "Unknown thrift typeID %d", thrift_typeID);
    throw_tprotocolexception(errbuf, INVALID_DATA);
}
Пример #14
0
/* {{{ php_build_argv
 */
PHPAPI void php_build_argv(char *s, zval *track_vars_array)
{
	zval arr, argc, tmp;
	int count = 0;
	char *ss, *space;

	if (!(SG(request_info).argc || track_vars_array)) {
		return;
	}

	array_init(&arr);

	/* Prepare argv */
	if (SG(request_info).argc) { /* are we in cli sapi? */
		int i;
		for (i = 0; i < SG(request_info).argc; i++) {
			ZVAL_STRING(&tmp, SG(request_info).argv[i]);
			if (zend_hash_next_index_insert(Z_ARRVAL(arr), &tmp) == NULL) {
				zend_string_efree(Z_STR(tmp));
			}
		}
	} else 	if (s && *s) {
		ss = s;
		while (ss) {
			space = strchr(ss, '+');
			if (space) {
				*space = '\0';
			}
			/* auto-type */
			ZVAL_STRING(&tmp, ss);
			count++;
			if (zend_hash_next_index_insert(Z_ARRVAL(arr), &tmp) == NULL) {
				zend_string_efree(Z_STR(tmp));
			}
			if (space) {
				*space = '+';
				ss = space + 1;
			} else {
				ss = space;
			}
		}
	}

	/* prepare argc */
	if (SG(request_info).argc) {
		ZVAL_LONG(&argc, SG(request_info).argc);
	} else {
		ZVAL_LONG(&argc, count);
	}

	if (SG(request_info).argc) {
		Z_ADDREF(arr);
		zend_hash_update(&EG(symbol_table), ZSTR_KNOWN(ZEND_STR_ARGV), &arr);
		zend_hash_update(&EG(symbol_table), ZSTR_KNOWN(ZEND_STR_ARGC), &argc);
	}
	if (track_vars_array && Z_TYPE_P(track_vars_array) == IS_ARRAY) {
		Z_ADDREF(arr);
		zend_hash_update(Z_ARRVAL_P(track_vars_array), ZSTR_KNOWN(ZEND_STR_ARGV), &arr);
		zend_hash_update(Z_ARRVAL_P(track_vars_array), ZSTR_KNOWN(ZEND_STR_ARGC), &argc);
	}
	zval_ptr_dtor_nogc(&arr);
}
Пример #15
0
static int fcgi_read_request(fcgi_request *req)
{
    fcgi_header hdr;
    int len, padding;
    unsigned char buf[FCGI_MAX_LENGTH+8];

    req->keep = 0;
    req->in_len = 0;
    req->out_hdr = NULL;
    req->out_pos = req->out_buf;
    zend_hash_init(&req->env, 0, NULL, (void (*)(void *)) fcgi_free_var, 1);

    if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
            hdr.version < FCGI_VERSION_1) {
        return 0;
    }

    len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
    padding = hdr.paddingLength;

    while (hdr.type == FCGI_STDIN && len == 0) {
        if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
                hdr.version < FCGI_VERSION_1) {
            return 0;
        }

        len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
        padding = hdr.paddingLength;
    }

    req->id = (hdr.requestIdB1 << 8) + hdr.requestIdB0;

    if (hdr.type == FCGI_BEGIN_REQUEST && len == sizeof(fcgi_begin_request)) {
        char *val;

        if (safe_read(req, buf, len+padding) != len+padding) {
            return 0;
        }

        req->keep = (((fcgi_begin_request*)buf)->flags & FCGI_KEEP_CONN);
        switch ((((fcgi_begin_request*)buf)->roleB1 << 8) + ((fcgi_begin_request*)buf)->roleB0) {
        case FCGI_RESPONDER:
            val = strdup("RESPONDER");
            zend_hash_update(&req->env, "FCGI_ROLE", sizeof("FCGI_ROLE"), &val, sizeof(char*), NULL);
            break;
        case FCGI_AUTHORIZER:
            val = strdup("AUTHORIZER");
            zend_hash_update(&req->env, "FCGI_ROLE", sizeof("FCGI_ROLE"), &val, sizeof(char*), NULL);
            break;
        case FCGI_FILTER:
            val = strdup("FILTER");
            zend_hash_update(&req->env, "FCGI_ROLE", sizeof("FCGI_ROLE"), &val, sizeof(char*), NULL);
            break;
        default:
            return 0;
        }

        if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
                hdr.version < FCGI_VERSION_1) {
            return 0;
        }

        len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
        padding = hdr.paddingLength;

        while (hdr.type == FCGI_PARAMS && len > 0) {
            if (safe_read(req, buf, len+padding) != len+padding) {
                req->keep = 0;
                return 0;
            }

            if (!fcgi_get_params(req, buf, buf+len)) {
                req->keep = 0;
                return 0;
            }

            if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
                    hdr.version < FCGI_VERSION_1) {
                req->keep = 0;
                return 0;
            }
            len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
            padding = hdr.paddingLength;
        }
    } else if (hdr.type == FCGI_GET_VALUES) {
        int j;
        unsigned char *p = buf + sizeof(fcgi_header);

        if (safe_read(req, buf, len+padding) != len+padding) {
            req->keep = 0;
            return 0;
        }

        if (!fcgi_get_params(req, buf, buf+len)) {
            req->keep = 0;
            return 0;
        }

        for (j = 0; j < sizeof(fcgi_mgmt_vars)/sizeof(fcgi_mgmt_vars[0]); j++) {
            if (zend_hash_exists(&req->env, fcgi_mgmt_vars[j].name, fcgi_mgmt_vars[j].name_len+1) == 0) {
                sprintf((char*)p, "%c%c%s%c", fcgi_mgmt_vars[j].name_len, 1, fcgi_mgmt_vars[j].name, fcgi_mgmt_vars[j].val);
                p += fcgi_mgmt_vars[j].name_len + 3;
            }
        }
        len = p - buf - sizeof(fcgi_header);
        len += fcgi_make_header((fcgi_header*)buf, FCGI_GET_VALUES_RESULT, 0, len);
        if (safe_write(req, buf, sizeof(fcgi_header)+len) != (int)sizeof(fcgi_header)+len) {
            req->keep = 0;
            return 0;
        }
        return 0;
    } else {
        return 0;
    }

    return 1;
}
Пример #16
0
static void php_dba_open(INTERNAL_FUNCTION_PARAMETERS, int persistent)
{
	pval ***args = (pval ***) NULL;
	int ac = ZEND_NUM_ARGS();
	dba_mode_t modenr;
	dba_info *info;
	dba_handler *hptr;
	char *key = NULL;
	int keylen = 0;
	int listid;
	int i;
	
	if(ac < 3) {
		WRONG_PARAM_COUNT;
	}
	
	/* we pass additional args to the respective handler */
	args = emalloc(ac * sizeof(pval *));
	if(zend_get_parameters_array_ex(ac, args) != SUCCESS) {
		FREENOW;
		WRONG_PARAM_COUNT;
	}
		
	/* we only take string arguments */
	for(i = 0; i < ac; i++) {
		convert_to_string_ex(args[i]);
		keylen += Z_STRLEN_PP(args[i]);
	}

	if(persistent) {
		/* calculate hash */
		key = emalloc(keylen);
		keylen = 0;
		
		for(i = 0; i < ac; i++) {
			memcpy(key+keylen,Z_STRVAL_PP(args[i]),Z_STRLEN_PP(args[i]));
			keylen += Z_STRLEN_PP(args[i]);
		}
		
		if(zend_hash_find(&ht_keys, key, keylen, (void **) &info) == SUCCESS) {
			FREENOW;
			RETURN_LONG(zend_list_insert(info, GLOBAL(le_pdb)));
		}
	}
	
	for(hptr = handler; hptr->name &&
			strcasecmp(hptr->name, (*args[2])->value.str.val); hptr++);

	if(!hptr->name) {
		php_error(E_WARNING, "no such handler: %s", (*args[2])->value.str.val);
		FREENOW;
		RETURN_FALSE;
	}

	switch((*args[1])->value.str.val[0]) {
		case 'c': 
			modenr = DBA_CREAT; 
			break;
		case 'w': 
			modenr = DBA_WRITER; 
			break;
		case 'r': 
			modenr = DBA_READER; 
			break;
		case 'n':
			modenr = DBA_TRUNC;
			break;
		default:
			php_error(E_WARNING,"illegal DBA mode: %s",(*args[1])->value.str.val);
			FREENOW;
			RETURN_FALSE;
	}
			
	info = malloc(sizeof(*info));
	memset(info, 0, sizeof(info));
	info->path = strdup((*args[0])->value.str.val);
	info->mode = modenr;
	info->argc = ac - 3;
	info->argv = args + 3;
	info->hnd = NULL;

	if(hptr->open(info) != SUCCESS) {
		dba_close(info);
		php_error(E_WARNING, "driver initialization failed");
		FREENOW;
		RETURN_FALSE;
	}
	info->hnd = hptr;
	info->argc = 0;
	info->argv = NULL;

	listid = zend_list_insert(info, persistent?GLOBAL(le_pdb):GLOBAL(le_db));
	if(persistent) {
		zend_hash_update(&ht_keys, key, keylen, info, sizeof(*info), NULL);
	}
	
	FREENOW;
	RETURN_LONG(listid);
}
Пример #17
0
PHP_SUHOSIN_API void suhosin_log(int loglevel, char *fmt, ...)
{
	int s, r, i=0, fd;
	long written, towrite;
	int getcaller=0;
	char *wbuf;
	struct timeval tv;
	time_t now;
	struct tm tm;
#if defined(AF_UNIX)
	struct sockaddr_un saun;
#endif
#ifdef PHP_WIN32
	LPTSTR strs[2];
	unsigned short etype;
	DWORD evid;
#endif
	char buf[5000];
	char error[5000];
	char *ip_address;
	char *fname;
	char *alertstring;
	int lineno;
	va_list ap;
	TSRMLS_FETCH();

#if PHP_VERSION_ID >= 50500
	getcaller = (loglevel & S_GETCALLER) == S_GETCALLER;
#endif
	/* remove the S_GETCALLER flag */
	loglevel = loglevel & ~S_GETCALLER;

	SDEBUG("(suhosin_log) loglevel: %d log_syslog: %u - log_sapi: %u - log_script: %u", loglevel, SUHOSIN_G(log_syslog), SUHOSIN_G(log_sapi), SUHOSIN_G(log_script));

	/* dump core if wanted */
	if (SUHOSIN_G(coredump) && loglevel == S_MEMORY) {
		volatile unsigned int *x = 0;
		volatile int y = *x;
	}
	
	if (SUHOSIN_G(log_use_x_forwarded_for)) {
		ip_address = suhosin_getenv("HTTP_X_FORWARDED_FOR", 20 TSRMLS_CC);
		if (ip_address == NULL) {
			ip_address = "X-FORWARDED-FOR not set";
		}
	} else {
		ip_address = suhosin_getenv("REMOTE_ADDR", 11 TSRMLS_CC);
		if (ip_address == NULL) {
			ip_address = "REMOTE_ADDR not set";
		}
	}
	
	
	va_start(ap, fmt);
	ap_php_vsnprintf(error, sizeof(error), fmt, ap);
	va_end(ap);
	while (error[i]) {
		if (error[i] < 32) error[i] = '.';
		i++;
	}
	
	if (SUHOSIN_G(simulation)) {
		alertstring = "ALERT-SIMULATION";
	} else {
		alertstring = "ALERT";
	}
	
	if (zend_is_executing(TSRMLS_C)) {
		zend_execute_data *exdata = EG(current_execute_data);
		if (exdata) {
			if (getcaller && exdata->prev_execute_data) {
				lineno = exdata->prev_execute_data->opline->lineno;
				fname = (char *)exdata->prev_execute_data->op_array->filename;									
			} else {
				lineno = exdata->opline->lineno;
				fname = (char *)exdata->op_array->filename;				
			}
		} else {
			lineno = zend_get_executed_lineno(TSRMLS_C);
			fname = (char *)zend_get_executed_filename(TSRMLS_C);
		}
		ap_php_snprintf(buf, sizeof(buf), "%s - %s (attacker '%s', file '%s', line %u)", alertstring, error, ip_address, fname, lineno);
	} else {
		fname = suhosin_getenv("SCRIPT_FILENAME", 15 TSRMLS_CC);
		if (fname==NULL) {
			fname = "unknown";
		}
		ap_php_snprintf(buf, sizeof(buf), "%s - %s (attacker '%s', file '%s')", alertstring, error, ip_address, fname);
	}
			
	/* Syslog-Logging disabled? */
	if (((SUHOSIN_G(log_syslog)|S_INTERNAL) & loglevel)==0) {
		goto log_file;
	}	
	
#if defined(AF_UNIX)
	ap_php_snprintf(error, sizeof(error), "<%u>suhosin[%u]: %s\n", (unsigned int)(SUHOSIN_G(log_syslog_facility)|SUHOSIN_G(log_syslog_priority)),getpid(),buf);

	s = socket(AF_UNIX, SOCK_DGRAM, 0);
	if (s == -1) {
		goto log_file;
	}
	
	memset(&saun, 0, sizeof(saun));
	saun.sun_family = AF_UNIX;
	strcpy(saun.sun_path, SYSLOG_PATH);
	/*saun.sun_len = sizeof(saun);*/
	
	r = connect(s, (struct sockaddr *)&saun, sizeof(saun));
	if (r) {
		close(s);
    		s = socket(AF_UNIX, SOCK_STREAM, 0);
		if (s == -1) {
			goto log_file;
		}
	
		memset(&saun, 0, sizeof(saun));
		saun.sun_family = AF_UNIX;
		strcpy(saun.sun_path, SYSLOG_PATH);
		/*saun.sun_len = sizeof(saun);*/

		r = connect(s, (struct sockaddr *)&saun, sizeof(saun));
		if (r) { 
			close(s);
			goto log_file;
		}
	}
	send(s, error, strlen(error), 0);
	
	close(s);
#endif
#ifdef PHP_WIN32
	ap_php_snprintf(error, sizeof(error), "suhosin[%u]: %s", getpid(),buf);

	switch (SUHOSIN_G(log_syslog_priority)) {			/* translate UNIX type into NT type */
		case 1: /*LOG_ALERT:*/
			etype = EVENTLOG_ERROR_TYPE;
			break;
		case 6: /*LOG_INFO:*/
			etype = EVENTLOG_INFORMATION_TYPE;
			break;
		default:
			etype = EVENTLOG_WARNING_TYPE;
	}
	evid = loglevel;
	strs[0] = error;
	/* report the event */
	if (log_source == NULL) {
		log_source = RegisterEventSource(NULL, "Suhosin-" SUHOSIN_EXT_VERSION);
	}
	ReportEvent(log_source, etype, (unsigned short) SUHOSIN_G(log_syslog_priority), evid, NULL, 1, 0, strs, NULL);
	
#endif
log_file:
	/* File-Logging disabled? */
	if ((SUHOSIN_G(log_file) & loglevel)==0) {
		goto log_sapi;
	}
	
	if (!SUHOSIN_G(log_filename) || !SUHOSIN_G(log_filename)[0]) {
		goto log_sapi;
	}
	fd = open(SUHOSIN_G(log_filename), O_CREAT|O_APPEND|O_WRONLY, 0640);
	if (fd == -1) {
	    suhosin_log(S_INTERNAL, "Unable to open logfile: %s", SUHOSIN_G(log_filename));
	    return;
	}

	gettimeofday(&tv, NULL);
	now = tv.tv_sec;
	php_gmtime_r(&now, &tm);
	ap_php_snprintf(error, sizeof(error), "%s %2d %02d:%02d:%02d [%u] %s\n", month_names[tm.tm_mon], tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, getpid(),buf);
	towrite = strlen(error);
	wbuf = error;
	php_flock(fd, LOCK_EX);
	while (towrite > 0) {
		written = write(fd, wbuf, towrite);
		if (written < 0) {
			break;
		}
		towrite -= written;
		wbuf += written;
	}
	php_flock(fd, LOCK_UN);
	close(fd);

log_sapi:
	/* SAPI Logging activated? */
	SDEBUG("(suhosin_log) log_syslog: %u - log_sapi: %u - log_script: %u - log_phpscript: %u", SUHOSIN_G(log_syslog), SUHOSIN_G(log_sapi), SUHOSIN_G(log_script), SUHOSIN_G(log_phpscript));
	if (((SUHOSIN_G(log_sapi)|S_INTERNAL) & loglevel)!=0) {
#if PHP_VERSION_ID < 50400
		sapi_module.log_message(buf);
#else
		sapi_module.log_message(buf TSRMLS_CC);
#endif
	}
	if ((SUHOSIN_G(log_stdout) & loglevel)!=0) {
		printf("%s\n", buf);
	}

/*log_script:*/
	/* script logging activaed? */
	if (((SUHOSIN_G(log_script) & loglevel)!=0) && SUHOSIN_G(log_scriptname)!=NULL) {
		char cmd[8192], *cmdpos, *bufpos;
		FILE *in;
		int space;
		struct stat st;
		
		char *sname = SUHOSIN_G(log_scriptname);
		while (isspace(*sname)) ++sname;
		if (*sname == 0) goto log_phpscript;
		
		if (VCWD_STAT(sname, &st) < 0) {
			suhosin_log(S_INTERNAL, "unable to find logging shell script %s - file dropped", sname);
			goto log_phpscript;
		}
		if (access(sname, X_OK|R_OK) < 0) {
			suhosin_log(S_INTERNAL, "logging shell script %s is not executable - file dropped", sname);
			goto log_phpscript;					
		}
		
		/* TODO: clean up this code to calculate size of output dynamically */
		ap_php_snprintf(cmd, sizeof(cmd) - 20, "%s %s \'", sname, loglevel2string(loglevel));
		space = sizeof(cmd) - strlen(cmd) - 20;
		cmdpos = cmd + strlen(cmd);
		bufpos = buf;
		if (space <= 1) return;
		while (space > 2 && *bufpos) {
			if (*bufpos == '\'') {
				if (space<=5) break;
				*cmdpos++ = '\'';
				*cmdpos++ = '\\';
				*cmdpos++ = '\'';
				*cmdpos++ = '\'';
				bufpos++;
				space-=4;
			} else {
				*cmdpos++ = *bufpos++;
				space--;
			}
		}
		*cmdpos++ = '\'';
		*cmdpos++ = ' ';
		*cmdpos++ = '2';
		*cmdpos++ = '>';
		*cmdpos++ = '&';
		*cmdpos++ = '1';
		*cmdpos = 0;
		
		if ((in=VCWD_POPEN(cmd, "r"))==NULL) {
			suhosin_log(S_INTERNAL, "Unable to execute logging shell script: %s", sname);
			goto log_phpscript;
		}
		/* read and forget the result */
		while (1) {
			int readbytes = fread(cmd, 1, sizeof(cmd), in);
			if (readbytes<=0) {
				break;
			}
			if (strncmp(cmd, "sh: ", 4) == 0) {
				/* assume this is an error */
				suhosin_log(S_INTERNAL, "Error while executing logging shell script: %s", sname);
				pclose(in);
				goto log_phpscript;
			}
		}
		pclose(in);
	}
log_phpscript:
	if ((SUHOSIN_G(log_phpscript) & loglevel)!=0 && EG(in_execution) && SUHOSIN_G(log_phpscriptname) && SUHOSIN_G(log_phpscriptname)[0]) {
		zend_file_handle file_handle;
		zend_op_array *new_op_array;
		zval *result = NULL;
		
		long orig_execution_depth = SUHOSIN_G(execution_depth);
#if PHP_VERSION_ID < 50400
		zend_bool orig_safe_mode = PG(safe_mode);
#endif
		char *orig_basedir = PG(open_basedir);
		
		char *phpscript = SUHOSIN_G(log_phpscriptname);
SDEBUG("scriptname %s", SUHOSIN_G(log_phpscriptname));				
#ifdef ZEND_ENGINE_2
		if (zend_stream_open(phpscript, &file_handle TSRMLS_CC) == SUCCESS) {
#else
		if (zend_open(phpscript, &file_handle) == SUCCESS && ZEND_IS_VALID_FILE_HANDLE(&file_handle)) {
			file_handle.filename = phpscript;
			file_handle.free_filename = 0;
#endif		
			if (!file_handle.opened_path) {
				file_handle.opened_path = estrndup(phpscript, strlen(phpscript));
			}
			new_op_array = zend_compile_file(&file_handle, ZEND_REQUIRE TSRMLS_CC);
			zend_destroy_file_handle(&file_handle TSRMLS_CC);
			if (new_op_array) {
				HashTable *active_symbol_table = EG(active_symbol_table);
				zval *zerror, *zerror_class;
				
				if (active_symbol_table == NULL) {
					active_symbol_table = &EG(symbol_table);
				}
				EG(return_value_ptr_ptr) = &result;
				EG(active_op_array) = new_op_array;
				
				MAKE_STD_ZVAL(zerror);
				MAKE_STD_ZVAL(zerror_class);
				ZVAL_STRING(zerror, buf, 1);
				ZVAL_LONG(zerror_class, loglevel);

				zend_hash_update(active_symbol_table, "SUHOSIN_ERROR", sizeof("SUHOSIN_ERROR"), (void **)&zerror, sizeof(zval *), NULL);
				zend_hash_update(active_symbol_table, "SUHOSIN_ERRORCLASS", sizeof("SUHOSIN_ERRORCLASS"), (void **)&zerror_class, sizeof(zval *), NULL);
				
				SUHOSIN_G(execution_depth) = 0;
				if (SUHOSIN_G(log_phpscript_is_safe)) {
#if PHP_VERSION_ID < 50400
					PG(safe_mode) = 0;
#endif
					PG(open_basedir) = NULL;
				}
				
				zend_execute(new_op_array TSRMLS_CC);
				
				SUHOSIN_G(execution_depth) = orig_execution_depth;
#if PHP_VERSION_ID < 50400				
				PG(safe_mode) = orig_safe_mode;
#endif
				PG(open_basedir) = orig_basedir;
				
#ifdef ZEND_ENGINE_2
				destroy_op_array(new_op_array TSRMLS_CC);
#else
				destroy_op_array(new_op_array);
#endif
				efree(new_op_array);
#ifdef ZEND_ENGINE_2
				if (!EG(exception))
#endif			
				{
					if (EG(return_value_ptr_ptr)) {
						zval_ptr_dtor(EG(return_value_ptr_ptr));
						EG(return_value_ptr_ptr) = NULL;
					}
				}
			} else {
				suhosin_log(S_INTERNAL, "Unable to execute logging PHP script: %s", SUHOSIN_G(log_phpscriptname));
				return;
			}
		} else {
			suhosin_log(S_INTERNAL, "Unable to execute logging PHP script: %s", SUHOSIN_G(log_phpscriptname));
			return;
		}
	}

}
Пример #18
0
//PHPAPI pcre_cache_entry* pcre_get_compiled_regex_cache(char *regex, int regex_len TSRMLS_DC)
pcre *compileRegex( char *regex , int regex_len , char *msg , int msglen ) 
{
	pcre				*re = NULL;
	pcre_extra			*extra;
	int					 coptions = 0;
	int					 soptions = 0;
	const char			*error;
	int					 erroffset;
	char				 delimiter;
	char				 start_delimiter;
	char				 end_delimiter;
	char				*p, *pp;
	char				*pattern;
	int					 do_study = 0;
	int					 poptions = 0;
	unsigned const char *tables = NULL;
    char buf[ 1024 ] ;

#if HAVE_SETLOCALE
	char				*locale = setlocale(LC_CTYPE, NULL);
#endif

    //R.A.W.
	//pcre_cache_entry	*pce;
	//pcre_cache_entry	 new_entry;
    if( msglen )
    {
        *msg = '\0';
    }

	/* Try to lookup the cached regex entry, and if successful, just pass
	   back the compiled pattern, otherwise go on and compile it. */
	regex_len = strlen(regex);

//R.A.W.
#if 0  

	if (zend_hash_find(&PCRE_G(pcre_cache), regex, regex_len+1, (void **)&pce) == SUCCESS) {
		/*
		 * We use a quick pcre_info() check to see whether cache is corrupted, and if it
		 * is, we flush it and compile the pattern from scratch.
		 */
		if (pcre_info(pce->re, NULL, NULL) == PCRE_ERROR_BADMAGIC) {
			zend_hash_clean(&PCRE_G(pcre_cache));
		} else {
#if HAVE_SETLOCALE
			if (!strcmp(pce->locale, locale)) {
#endif
				return pce;
#if HAVE_SETLOCALE
			}
#endif
		}
	}
#endif
	p = regex;
	
	/* Parse through the leading whitespace, and display a warning if we
	   get to the end without encountering a delimiter. */
	while (isspace((int)*(unsigned char *)p)) p++;
	if (*p == 0) {

        // R.A.W.
		//php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty regular expression");
        strncpy(msg, "Empty regular expression" , msglen );

		return NULL;
	}
	
	/* Get the delimiter and display a warning if it is alphanumeric
	   or a backslash. */
	delimiter = *p++;
	if (isalnum((int)*(unsigned char *)&delimiter) || delimiter == '\\') {
		//php_error_docref(NULL TSRMLS_CC,E_WARNING, "Delimiter must not be alphanumeric or backslash");
		strncpy( msg, "Delimiter must not be alphanumeric or backslash",msglen);
		return NULL;
	}

	start_delimiter = delimiter;
	if ((pp = strchr("([{< )]}> )]}>", delimiter)))
		delimiter = pp[5];
	end_delimiter = delimiter;

	if (start_delimiter == end_delimiter) {
		/* We need to iterate through the pattern, searching for the ending delimiter,
		   but skipping the backslashed delimiters.  If the ending delimiter is not
		   found, display a warning. */
		pp = p;
		while (*pp != 0) {
			if (*pp == '\\' && pp[1] != 0) pp++;
			else if (*pp == delimiter)
				break;
			pp++;
		}
		if (*pp == 0) {
			//php_error_docref(NULL TSRMLS_CC,E_WARNING, "No ending delimiter '%c' found", delimiter);

            //R.A.W.
            strncpy( msg, "No ending delimiter found" ,msglen ) ;
			return NULL;
		}
	} else {
		/* We iterate through the pattern, searching for the matching ending
		 * delimiter. For each matching starting delimiter, we increment nesting
		 * level, and decrement it for each matching ending delimiter. If we
		 * reach the end of the pattern without matching, display a warning.
		 */
		int brackets = 1; 	/* brackets nesting level */
		pp = p;
		while (*pp != 0) {
			if (*pp == '\\' && pp[1] != 0) pp++;
			else if (*pp == end_delimiter && --brackets <= 0)
				break;
			else if (*pp == start_delimiter)
				brackets++;
			pp++;
		}
		if (*pp == 0) {
			//php_error_docref(NULL TSRMLS_CC,E_WARNING, "No ending matching delimiter '%c' found", end_delimiter);
			strncpy( msg,"No ending matching delimiter found",msglen ) ;
			return NULL;
		}
	}
	
	/* Make a copy of the actual pattern. */
    // R.A.W.
	//pattern = strndup(p, pp-p);
    // osx compile is complaining about strndup and since I have te
    // other function anyway and since I'll someday rewrite this fn, just
    // call that other function now :>)
    pattern = ghstrndup( p,pp-p) ;


	/* Move on to the options */
	pp++;

	/* Parse through the options, setting appropriate flags.  Display
	   a warning if we encounter an unknown modifier. */	
	while (*pp != 0) {
		switch (*pp++) {
			/* Perl compatible options */
			case 'i':	coptions |= PCRE_CASELESS;		break;
			case 'm':	coptions |= PCRE_MULTILINE;		break;
			case 's':	coptions |= PCRE_DOTALL;		break;
			case 'x':	coptions |= PCRE_EXTENDED;		break;
			
			/* PCRE specific options */
			case 'A':	coptions |= PCRE_ANCHORED;		break;
			case 'D':	coptions |= PCRE_DOLLAR_ENDONLY;break;
			case 'S':	do_study  = 1;					break;
			case 'U':	coptions |= PCRE_UNGREEDY;		break;
			case 'X':	coptions |= PCRE_EXTRA;			break;
			case 'u':	coptions |= PCRE_UTF8;			break;

                // R.A.W.
			/* Custom preg options */
                //case 'e':	poptions |= PREG_REPLACE_EVAL;	break;
			
			case ' ':
			case '\n':
				break;

			default:
				//php_error_docref(NULL TSRMLS_CC,E_WARNING, "Unknown modifier '%c'", pp[-1]);
                strncpy( msg,"Unknown modifier",msglen ) ;
				free(pattern);
				return NULL;
		}
	}

    //R.A.W.
    tables = NULL ;
#if 0 
#if HAVE_SETLOCALE
	if (strcmp(locale, "C"))
		tables = pcre_maketables();
#endif
#endif

	/* Compile pattern and display a warning if compilation failed. */
	re = pcre_compile(pattern,
					  coptions,
					  &error,
					  &erroffset,
					  tables);

	if (re == NULL) {
		//php_error_docref(NULL TSRMLS_CC,E_WARNING, "Compilation failed: %s at offset %d", error, erroffset);

        // R.A.W.
		sprintf(buf, "Compilation of /%s/ failed: %s at offset %d",pattern, error, erroffset);
		//sprintf(buf, "Compilation failed: %s at offset %d",error, erroffset);
        strncpy( msg, buf , msglen ) ;
		free(pattern);
        // R.A.W.
		//if (tables) {
			//pefree((void*)tables, 1);
        //}
		return NULL;
	}

	/* If study option was specified, study the pattern and
	   store the result in extra for passing to pcre_exec. */
	if (do_study) {
		extra = pcre_study(re, soptions, &error);
		if (extra) {
			extra->flags |= PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
		}
		if (error != NULL) {
			strncpy( msg, "Error while studying pattern",msglen);
		}
	} else {
		extra = NULL;
	}

	free(pattern);


//R.A.W.
#if 0 
	/*
	 * If we reached cache limit, clean out the items from the head of the list;
	 * these are supposedly the oldest ones (but not necessarily the least used
	 * ones).
	 */
	if (zend_hash_num_elements(&PCRE_G(pcre_cache)) == PCRE_CACHE_SIZE) {
		int num_clean = PCRE_CACHE_SIZE / 8;
		zend_hash_apply_with_argument(&PCRE_G(pcre_cache), pcre_clean_cache, &num_clean TSRMLS_CC);
	}

	/* Store the compiled pattern and extra info in the cache. */
	new_entry.re = re;
	new_entry.extra = extra;
	new_entry.preg_options = poptions;
	new_entry.compile_options = coptions;
#if HAVE_SETLOCALE
	new_entry.locale = pestrdup(locale, 1);
	new_entry.tables = tables;
#endif
	zend_hash_update(&PCRE_G(pcre_cache), regex, regex_len+1, (void *)&new_entry,
						sizeof(pcre_cache_entry), (void**)&pce);

#endif

    //	return pce;
    //R.A.W.
    return re ;
}
Пример #19
0
void binary_deserialize(int8_t thrift_typeID, PHPInputTransport& transport, zval* return_value, HashTable* fieldspec) {
    zval** val_ptr;
    Z_TYPE_P(return_value) = IS_NULL; // just in case

    switch (thrift_typeID) {
    case T_STOP:
    case T_VOID:
        RETURN_NULL();
        return;
    case T_STRUCT: {
        if (zend_hash_find(fieldspec, "class", 6, (void**)&val_ptr) != SUCCESS) {
            throw_tprotocolexception("no class type in spec", INVALID_DATA);
            skip_element(T_STRUCT, transport);
            RETURN_NULL();
        }
        char* structType = Z_STRVAL_PP(val_ptr);
        createObject(structType, return_value);
        if (Z_TYPE_P(return_value) == IS_NULL) {
            // unable to create class entry
            skip_element(T_STRUCT, transport);
            RETURN_NULL();
        }
        TSRMLS_FETCH();
        zval* spec = zend_read_static_property(zend_get_class_entry(return_value TSRMLS_CC), "_TSPEC", 6, false TSRMLS_CC);
        if (Z_TYPE_P(spec) != IS_ARRAY) {
            char errbuf[128];
            snprintf(errbuf, 128, "spec for %s is wrong type: %d\n", structType, Z_TYPE_P(spec));
            throw_tprotocolexception(errbuf, INVALID_DATA);
            RETURN_NULL();
        }
        binary_deserialize_spec(return_value, transport, Z_ARRVAL_P(spec));
        return;
    }
    break;
    case T_BOOL: {
        uint8_t c;
        transport.readBytes(&c, 1);
        RETURN_BOOL(c != 0);
    }
    //case T_I08: // same numeric value as T_BYTE
    case T_BYTE: {
        uint8_t c;
        transport.readBytes(&c, 1);
        RETURN_LONG(c);
    }
    case T_I16: {
        uint16_t c;
        transport.readBytes(&c, 2);
        RETURN_LONG(ntohs(c));
    }
    case T_I32: {
        uint32_t c;
        transport.readBytes(&c, 4);
        RETURN_LONG(ntohl(c));
    }
    case T_U64:
    case T_I64: {
        uint64_t c;
        transport.readBytes(&c, 8);
        RETURN_LONG(ntohll(c));
    }
    case T_DOUBLE: {
        union {
            uint64_t c;
            double d;
        } a;
        transport.readBytes(&(a.c), 8);
        a.c = ntohll(a.c);
        RETURN_DOUBLE(a.d);
    }
    //case T_UTF7: // aliases T_STRING
    case T_UTF8:
    case T_UTF16:
    case T_STRING: {
        uint32_t size = transport.readU32();
        if (size) {
            char* strbuf = (char*) emalloc(size + 1);
            transport.readBytes(strbuf, size);
            strbuf[size] = '\0';
            ZVAL_STRINGL(return_value, strbuf, size, 0);
        } else {
            ZVAL_EMPTY_STRING(return_value);
        }
        return;
    }
    case T_MAP: { // array of key -> value
        uint8_t types[2];
        transport.readBytes(types, 2);
        uint32_t size = transport.readU32();
        array_init(return_value);

        zend_hash_find(fieldspec, "key", 4, (void**)&val_ptr);
        HashTable* keyspec = Z_ARRVAL_PP(val_ptr);
        zend_hash_find(fieldspec, "val", 4, (void**)&val_ptr);
        HashTable* valspec = Z_ARRVAL_PP(val_ptr);

        for (uint32_t s = 0; s < size; ++s) {
            zval *value;
            MAKE_STD_ZVAL(value);

            zval* key;
            MAKE_STD_ZVAL(key);

            binary_deserialize(types[0], transport, key, keyspec);
            binary_deserialize(types[1], transport, value, valspec);
            if (Z_TYPE_P(key) == IS_LONG) {
                zend_hash_index_update(return_value->value.ht, Z_LVAL_P(key), &value, sizeof(zval *), NULL);
            }
            else {
                if (Z_TYPE_P(key) != IS_STRING) convert_to_string(key);
                zend_hash_update(return_value->value.ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &value, sizeof(zval *), NULL);
            }
            zval_ptr_dtor(&key);
        }
        return; // return_value already populated
    }
    case T_LIST: { // array with autogenerated numeric keys
        int8_t type = transport.readI8();
        uint32_t size = transport.readU32();
        zend_hash_find(fieldspec, "elem", 5, (void**)&val_ptr);
        HashTable* elemspec = Z_ARRVAL_PP(val_ptr);

        array_init(return_value);
        for (uint32_t s = 0; s < size; ++s) {
            zval *value;
            MAKE_STD_ZVAL(value);
            binary_deserialize(type, transport, value, elemspec);
            zend_hash_next_index_insert(return_value->value.ht, &value, sizeof(zval *), NULL);
        }
        return;
    }
    case T_SET: { // array of key -> TRUE
        uint8_t type;
        uint32_t size;
        transport.readBytes(&type, 1);
        transport.readBytes(&size, 4);
        size = ntohl(size);
        zend_hash_find(fieldspec, "elem", 5, (void**)&val_ptr);
        HashTable* elemspec = Z_ARRVAL_PP(val_ptr);

        array_init(return_value);

        for (uint32_t s = 0; s < size; ++s) {
            zval* key;
            zval* value;
            MAKE_STD_ZVAL(key);
            MAKE_STD_ZVAL(value);
            ZVAL_TRUE(value);

            binary_deserialize(type, transport, key, elemspec);

            if (Z_TYPE_P(key) == IS_LONG) {
                zend_hash_index_update(return_value->value.ht, Z_LVAL_P(key), &value, sizeof(zval *), NULL);
            }
            else {
                if (Z_TYPE_P(key) != IS_STRING) convert_to_string(key);
                zend_hash_update(return_value->value.ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &value, sizeof(zval *), NULL);
            }
            zval_ptr_dtor(&key);
        }
        return;
    }
    };

    char errbuf[128];
    sprintf(errbuf, "Unknown thrift typeID %d", thrift_typeID);
    throw_tprotocolexception(errbuf, INVALID_DATA);
}
Пример #20
0
inline int sw_zend_hash_update(HashTable *ht, char *k, int len, void * val, int size, void *ptr) {
    zval key;
    ZVAL_STRING(&key, k);

    return zend_hash_update(ht, Z_STR(key), val) ? SUCCESS : FAILURE;
}
/* ArchiveWriter::addEntry {{{
 *
*/
ZEND_METHOD(ArchiveWriter, addEntry)
{
	zval *this = getThis();
	zval *entry_obj;
	archive_file_t *arch;
	archive_entry_t *entry, *entry_copy;
	char *pathname;
	int pathname_len;
	const struct stat *stat_sb;
	zend_error_handling error_handling;

	zend_replace_error_handling(EH_THROW, ce_ArchiveException, &error_handling TSRMLS_CC);

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &entry_obj) == FAILURE) {
		zend_restore_error_handling(&error_handling TSRMLS_CC);
		return;
	}

	if (!_archive_get_fd(this, &arch TSRMLS_CC)) {
		zend_restore_error_handling(&error_handling TSRMLS_CC);
		return;
	}

	if (!instanceof_function(Z_OBJCE_P(entry_obj), ce_ArchiveEntry TSRMLS_CC)) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "An instance of ArchiveEntry is required");
		zend_restore_error_handling(&error_handling TSRMLS_CC);
		return;
	}

	if (!_archive_get_entry_struct(entry_obj, &entry TSRMLS_CC)) {
		zend_restore_error_handling(&error_handling TSRMLS_CC);
		return;
	}

	pathname = entry->filename;
	pathname_len = strlen(pathname);

	_archive_normalize_path(&pathname, &pathname_len);

	if (pathname_len == 0 || pathname[0] == '\0') {
		/* user is probably trying to add "./", "/", ".." or ".", ignoring it silently */
		zend_restore_error_handling(&error_handling TSRMLS_CC);
		RETURN_TRUE;
	}

	/* copy entry.. */
	entry_copy = emalloc(sizeof(archive_entry_t));
	memcpy(entry_copy, entry, sizeof(archive_entry_t));
	entry_copy->entry = archive_entry_new();
	entry_copy->filename = estrdup(entry->filename);

	entry_copy->data = NULL;
	entry_copy->data_len = 0;

	archive_entry_copy_pathname(entry_copy->entry, pathname);
	stat_sb = archive_entry_stat(entry->entry);
	archive_entry_copy_stat(entry_copy->entry, stat_sb);

	/* ..and add it to the hash */
	zend_hash_update(arch->entries, pathname, pathname_len + 1, &entry_copy, sizeof(archive_entry_t), NULL);
	zend_restore_error_handling(&error_handling TSRMLS_CC);
	RETURN_TRUE;
}
Пример #22
0
PHPAPI int php_stream_xport_register(char *protocol, php_stream_transport_factory factory TSRMLS_DC)
{
	return zend_hash_update(&xport_hash, protocol, strlen(protocol) + 1, &factory, sizeof(factory), NULL);
}
static void
SWIG_ZTS_SetPointerZval(zval *z, void *ptr, swig_type_info *type, int newobject TSRMLS_DC) {
  /*
   * First test for Null pointers.  Return those as PHP native NULL
   */
  if (!ptr ) {
    ZVAL_NULL(z);
    return;
  }
  if (type->clientdata) {
    swig_object_wrapper *value;
    if (! (*(int *)(type->clientdata)))
      zend_error(E_ERROR, "Type: %s failed to register with zend",type->name);
    value=(swig_object_wrapper *)emalloc(sizeof(swig_object_wrapper));
    value->ptr=ptr;
    value->newobject=(newobject & 1);
    if ((newobject & 2) == 0) {
      /* Just register the pointer as a resource. */
      ZEND_REGISTER_RESOURCE(z, value, *(int *)(type->clientdata));
    } else {
      /*
       * Wrap the resource in an object, the resource will be accessible
       * via the "_cPtr" member. This is currently only used by
       * directorin typemaps.
       */
      zval *resource;
      zend_class_entry **ce = NULL;
      const char *type_name = type->name+3; /* +3 so: _p_Foo -> Foo */
      size_t type_name_len;
      int result;
      const char * p;

      /* Namespace__Foo -> Foo */
      /* FIXME: ugly and goes wrong for classes with __ in their names. */
      while ((p = strstr(type_name, "__")) != NULL) {
        type_name = p + 2;
      }
      type_name_len = strlen(type_name);

      MAKE_STD_ZVAL(resource);
      ZEND_REGISTER_RESOURCE(resource, value, *(int *)(type->clientdata));
      if (SWIG_PREFIX_LEN > 0) {
        char * classname = (char*)emalloc(SWIG_PREFIX_LEN + type_name_len + 1);
        strcpy(classname, SWIG_PREFIX);
        strcpy(classname + SWIG_PREFIX_LEN, type_name);
        result = zend_lookup_class(classname, SWIG_PREFIX_LEN + type_name_len, &ce TSRMLS_CC);
        efree(classname);
      } else {
        result = zend_lookup_class((char *)type_name, type_name_len, &ce TSRMLS_CC);
      }
      if (result != SUCCESS) {
        /* class does not exist */
        object_init(z);
      } else {
        object_init_ex(z, *ce);
      }
      Z_SET_REFCOUNT_P(z, 1);
      Z_SET_ISREF_P(z);
      zend_hash_update(HASH_OF(z), (char*)"_cPtr", sizeof("_cPtr"), (void*)&resource, sizeof(zval), NULL);
    }
    return;
  }
  zend_error(E_ERROR, "Type: %s not registered with zend",type->name);
}
Пример #24
0
PHP_METHOD(DefaultCluster, connectAsync)
{
  char* hash_key;
  int   hash_key_len = 0;
  char* keyspace = NULL;
  int   keyspace_len;
  cassandra_cluster* cluster = NULL;
  cassandra_future_session* future = NULL;

  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &keyspace, &keyspace_len) == FAILURE) {
    return;
  }

  cluster = (cassandra_cluster*) zend_object_store_get_object(getThis() TSRMLS_CC);

  object_init_ex(return_value, cassandra_future_session_ce);
  future = (cassandra_future_session*) zend_object_store_get_object(return_value TSRMLS_CC);

  future->persist = cluster->persist;

  if (cluster->persist) {
    zend_rsrc_list_entry *le;

    hash_key_len = spprintf(&hash_key, 0,
      "%s:session:%s", cluster->hash_key, SAFE_STR(keyspace));

    future->hash_key     = hash_key;
    future->hash_key_len = hash_key_len;

    if (zend_hash_find(&EG(persistent_list), hash_key, hash_key_len + 1, (void **)&le) == SUCCESS) {
      if (Z_TYPE_P(le) == php_le_cassandra_session()) {
        cassandra_psession* psession = (cassandra_psession*) le->ptr;
        future->session = psession->session;
        future->future  = psession->future;
        return;
      }
    }
  }

  future->session = cass_session_new();

  if (keyspace) {
    future->future = cass_session_connect_keyspace(future->session, cluster->cluster, keyspace);
  } else {
    future->future = cass_session_connect(future->session, cluster->cluster);
  }

  if (cluster->persist) {
    zend_rsrc_list_entry le;
    cassandra_psession* psession =
      (cassandra_psession*) pecalloc(1, sizeof(cassandra_psession), 1);
    psession->session = future->session;
    psession->future  = future->future;

    le.type = php_le_cassandra_session();
    le.ptr  = psession;

    zend_hash_update(&EG(persistent_list), hash_key, hash_key_len + 1, &le, sizeof(zend_rsrc_list_entry), NULL);
    CASSANDRA_G(persistent_sessions)++;
  }
}
Пример #25
0
void zend_closure_bind_var(zval *closure_zv, zend_string *var_name, zval *var) /* {{{ */
{
	zend_closure *closure = (zend_closure *) Z_OBJ_P(closure_zv);
	HashTable *static_variables = closure->func.op_array.static_variables;
	zend_hash_update(static_variables, var_name, var);
}
Пример #26
0
PHP_METHOD(DefaultCluster, connect)
{
  CassFuture* future = NULL;
  char* hash_key;
  int   hash_key_len = 0;
  char* keyspace = NULL;
  int   keyspace_len;
  zval* timeout = NULL;
  cassandra_psession* psession;
  cassandra_cluster* cluster = NULL;
  cassandra_session* session = NULL;

  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sz", &keyspace, &keyspace_len, &timeout) == FAILURE) {
    return;
  }

  cluster = (cassandra_cluster*) zend_object_store_get_object(getThis() TSRMLS_CC);

  object_init_ex(return_value, cassandra_default_session_ce);
  session = (cassandra_session*) zend_object_store_get_object(return_value TSRMLS_CC);

  session->default_consistency = cluster->default_consistency;
  session->default_page_size   = cluster->default_page_size;
  session->default_timeout     = cluster->default_timeout;
  session->persist             = cluster->persist;

  if (session->default_timeout) {
    Z_ADDREF_P(session->default_timeout);
  }

  if (session->persist) {
    zend_rsrc_list_entry *le;

    hash_key_len = spprintf(&hash_key, 0, "%s:session:%s",
                            cluster->hash_key, SAFE_STR(keyspace));

    if (zend_hash_find(&EG(persistent_list), hash_key, hash_key_len + 1, (void **)&le) == SUCCESS &&
        Z_TYPE_P(le) == php_le_cassandra_session()) {
      psession = (cassandra_psession*) le->ptr;
      session->session = psession->session;
      future = psession->future;
    }
  }

  if (future == NULL) {
    session->session = cass_session_new();

    if (keyspace) {
      future = cass_session_connect_keyspace(session->session, cluster->cluster, keyspace);
    } else {
      future = cass_session_connect(session->session, cluster->cluster);
    }

    if (session->persist) {
      zend_rsrc_list_entry pe;
      psession = (cassandra_psession*) pecalloc(1, sizeof(cassandra_psession), 1);
      psession->session = session->session;
      psession->future  = future;

      pe.type = php_le_cassandra_session();
      pe.ptr  = psession;

      zend_hash_update(&EG(persistent_list), hash_key, hash_key_len + 1, &pe, sizeof(zend_rsrc_list_entry), NULL);
      CASSANDRA_G(persistent_sessions)++;
    }
  }

  if (php_cassandra_future_wait_timed(future, timeout TSRMLS_CC) == FAILURE) {
    if (session->persist) {
      efree(hash_key);
    } else {
      cass_future_free(future);
    }

    return;
  }

  if (php_cassandra_future_is_error(future TSRMLS_CC) == FAILURE) {
    if (session->persist) {
      if (zend_hash_del(&EG(persistent_list), hash_key, hash_key_len + 1) == SUCCESS) {
        session->session = NULL;
      }

      efree(hash_key);
    } else {
      cass_future_free(future);
    }

    return;
  }

  if (session->persist)
    efree(hash_key);
}
Пример #27
0
int php_init_config(char *php_ini_path_override)
{
	char *env_location, *php_ini_search_path;
	int safe_mode_state;
	char *open_basedir;
	int free_ini_search_path=0;
	zend_file_handle fh;
	PLS_FETCH();

	if (zend_hash_init(&configuration_hash, 0, NULL, (dtor_func_t) pvalue_config_destructor, 1)==FAILURE) {
		return FAILURE;
	}

	zend_llist_init(&extension_lists.engine, sizeof(zval), (llist_dtor_func_t) free_estring, 1);
	zend_llist_init(&extension_lists.functions, sizeof(zval), (llist_dtor_func_t)  ZVAL_DESTRUCTOR, 1);
	
	safe_mode_state = PG(safe_mode);
	open_basedir = PG(open_basedir);

	env_location = getenv("PHPRC");
	if (!env_location) {
		env_location="";
	}
	if (php_ini_path_override) {
		php_ini_search_path = php_ini_path_override;
		free_ini_search_path = 0;
	} else {
		char *default_location;
		int free_default_location;

#ifdef PHP_WIN32
		default_location = (char *) emalloc(512);
	
		if (!GetWindowsDirectory(default_location,255)) {
			default_location[0]=0;
		}
		free_default_location=1;
#else
		default_location = PHP_CONFIG_FILE_PATH;
		free_default_location=0;
#endif
		php_ini_search_path = (char *) emalloc(sizeof(".")+strlen(env_location)+strlen(default_location)+2+1);
		free_ini_search_path = 1;
		if(env_location && env_location[0]) {
			sprintf(php_ini_search_path, ".%c%s%c%s", ZEND_PATHS_SEPARATOR, env_location, ZEND_PATHS_SEPARATOR, default_location);
		} else {
			sprintf(php_ini_search_path, ".%c%s", ZEND_PATHS_SEPARATOR, default_location);
		}
		if (free_default_location) {
			efree(default_location);
		}
	}

	PG(safe_mode) = 0;
	PG(open_basedir) = NULL;
	
	fh.handle.fp = php_fopen_with_path("php.ini", "r", php_ini_search_path, &php_ini_opened_path);
	if (free_ini_search_path) {
		efree(php_ini_search_path);
	}
	PG(safe_mode) = safe_mode_state;
	PG(open_basedir) = open_basedir;

	if (!fh.handle.fp) {
		return SUCCESS;  /* having no configuration file is ok */
	}
	fh.type = ZEND_HANDLE_FP;
	fh.filename = php_ini_opened_path;

	zend_parse_ini_file(&fh, 1, php_config_ini_parser_cb, &extension_lists);
	
	if (php_ini_opened_path) {
		zval tmp;
		
		tmp.value.str.len = strlen(php_ini_opened_path);
		tmp.value.str.val = zend_strndup(php_ini_opened_path, tmp.value.str.len);
		tmp.type = IS_STRING;
		zend_hash_update(&configuration_hash, "cfg_file_path", sizeof("cfg_file_path"),(void *) &tmp,sizeof(zval), NULL);
		persist_alloc(php_ini_opened_path);
	}
	
	return SUCCESS;
}
Пример #28
0
static void php_browscap_parser_cb(zval *arg1, zval *arg2, zval *arg3, int callback_type, void *arg) /* {{{ */
{
	browser_data *bdata = arg;
	int persistent = bdata->htab->u.flags & HASH_FLAG_PERSISTENT;
	
	if (!arg1) {
		return;
	}

	switch (callback_type) {
		case ZEND_INI_PARSER_ENTRY:
			if (Z_TYPE(bdata->current_section) != IS_UNDEF && arg2) {
				zval new_property;
				zend_string *new_key;

				/* parent entry can not be same as current section -> causes infinite loop! */
				if (!strcasecmp(Z_STRVAL_P(arg1), "parent") && 
					bdata->current_section_name != NULL &&
					!strcasecmp(bdata->current_section_name, Z_STRVAL_P(arg2))
				) {
					zend_error(E_CORE_ERROR, "Invalid browscap ini file: "
						"'Parent' value cannot be same as the section name: %s "
						"(in file %s)", bdata->current_section_name, INI_STR("browscap"));
					return;
				}

				/* Set proper value for true/false settings */
				if ((Z_STRLEN_P(arg2) == 2 && !strncasecmp(Z_STRVAL_P(arg2), "on", sizeof("on") - 1)) ||
					(Z_STRLEN_P(arg2) == 3 && !strncasecmp(Z_STRVAL_P(arg2), "yes", sizeof("yes") - 1)) ||
					(Z_STRLEN_P(arg2) == 4 && !strncasecmp(Z_STRVAL_P(arg2), "true", sizeof("true") - 1))
				) {
					ZVAL_NEW_STR(&new_property, zend_string_init("1", sizeof("1")-1, persistent));
				} else if (
					(Z_STRLEN_P(arg2) == 2 && !strncasecmp(Z_STRVAL_P(arg2), "no", sizeof("no") - 1)) ||
					(Z_STRLEN_P(arg2) == 3 && !strncasecmp(Z_STRVAL_P(arg2), "off", sizeof("off") - 1)) ||
					(Z_STRLEN_P(arg2) == 4 && !strncasecmp(Z_STRVAL_P(arg2), "none", sizeof("none") - 1)) ||
					(Z_STRLEN_P(arg2) == 5 && !strncasecmp(Z_STRVAL_P(arg2), "false", sizeof("false") - 1))
				) {
					// TODO: USE STR_EMPTY_ALLOC()?
					ZVAL_NEW_STR(&new_property, zend_string_init("", sizeof("")-1, persistent));
				} else { /* Other than true/false setting */
					ZVAL_STR(&new_property, zend_string_dup(Z_STR_P(arg2), persistent));
				}
				new_key = zend_string_dup(Z_STR_P(arg1), persistent);
				zend_str_tolower(new_key->val, new_key->len);
				zend_hash_update(Z_ARRVAL(bdata->current_section), new_key, &new_property);
				zend_string_release(new_key);
			}
			break;
		case ZEND_INI_PARSER_SECTION: {
				zval processed;
				zval unprocessed;

				/*printf("'%s' (%d)\n",$1.value.str.val,$1.value.str.len + 1);*/
				if (persistent) {
					ZVAL_NEW_PERSISTENT_ARR(&bdata->current_section);
				} else {
					ZVAL_NEW_ARR(&bdata->current_section);
				}
				zend_hash_init(Z_ARRVAL(bdata->current_section), 0, NULL,
						(dtor_func_t) (persistent?browscap_entry_dtor_persistent
												 :browscap_entry_dtor_request),
						persistent);
				if (bdata->current_section_name) {
					pefree(bdata->current_section_name, persistent);
				}
				bdata->current_section_name = pestrndup(Z_STRVAL_P(arg1),
						Z_STRLEN_P(arg1), persistent);

				zend_hash_update(bdata->htab, Z_STR_P(arg1), &bdata->current_section);

				ZVAL_STR(&processed, Z_STR_P(arg1));
				ZVAL_STR(&unprocessed, zend_string_dup(Z_STR_P(arg1), persistent));

				convert_browscap_pattern(&processed, persistent);
				zend_hash_str_update(Z_ARRVAL(bdata->current_section), "browser_name_regex", sizeof("browser_name_regex")-1, &processed);
				zend_hash_str_update(Z_ARRVAL(bdata->current_section), "browser_name_pattern", sizeof("browser_name_pattern")-1, &unprocessed);
			}
			break;
	}
}
Пример #29
0
static int fcgi_read_request(fcgi_request *req)
{
	fcgi_header hdr;
	int len, padding;
	unsigned char buf[FCGI_MAX_LENGTH+8];

	req->keep = 0;
	req->closed = 0;
	req->in_len = 0;
	req->out_hdr = NULL;
	req->out_pos = req->out_buf;
	ALLOC_HASHTABLE(req->env);
	zend_hash_init(req->env, 0, NULL, (void (*)(void *)) fcgi_free_var, 0);

	if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
	    hdr.version < FCGI_VERSION_1) {
		return 0;
	}

	len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
	padding = hdr.paddingLength;

	while (hdr.type == FCGI_STDIN && len == 0) {
		if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
		    hdr.version < FCGI_VERSION_1) {
			return 0;
		}

		len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
		padding = hdr.paddingLength;
	}

	if (len + padding > FCGI_MAX_LENGTH) {
		return 0;
	}

	req->id = (hdr.requestIdB1 << 8) + hdr.requestIdB0;

	if (hdr.type == FCGI_BEGIN_REQUEST && len == sizeof(fcgi_begin_request)) {
		char *val;

		if (safe_read(req, buf, len+padding) != len+padding) {
			return 0;
		}

		req->keep = (((fcgi_begin_request*)buf)->flags & FCGI_KEEP_CONN);
		switch ((((fcgi_begin_request*)buf)->roleB1 << 8) + ((fcgi_begin_request*)buf)->roleB0) {
			case FCGI_RESPONDER:
				val = estrdup("RESPONDER");
				zend_hash_update(req->env, "FCGI_ROLE", sizeof("FCGI_ROLE"), &val, sizeof(char*), NULL);
				break;
			case FCGI_AUTHORIZER:
				val = estrdup("AUTHORIZER");
				zend_hash_update(req->env, "FCGI_ROLE", sizeof("FCGI_ROLE"), &val, sizeof(char*), NULL);
				break;
			case FCGI_FILTER:
				val = estrdup("FILTER");
				zend_hash_update(req->env, "FCGI_ROLE", sizeof("FCGI_ROLE"), &val, sizeof(char*), NULL);
				break;
			default:
				return 0;
		}

		if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
		    hdr.version < FCGI_VERSION_1) {
			return 0;
		}

		len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
		padding = hdr.paddingLength;

		while (hdr.type == FCGI_PARAMS && len > 0) {
			if (len + padding > FCGI_MAX_LENGTH) {
				return 0;
			}

			if (safe_read(req, buf, len+padding) != len+padding) {
				req->keep = 0;
				return 0;
			}

			if (!fcgi_get_params(req, buf, buf+len)) {
				req->keep = 0;
				return 0;
			}

			if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
			    hdr.version < FCGI_VERSION_1) {
				req->keep = 0;
				return 0;
			}
			len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
			padding = hdr.paddingLength;
		}
	} else if (hdr.type == FCGI_GET_VALUES) {
		unsigned char *p = buf + sizeof(fcgi_header);
		HashPosition pos;
		char * str_index;
		uint str_length;
		ulong num_index;
		int key_type;
		zval ** value;

		if (safe_read(req, buf, len+padding) != len+padding) {
			req->keep = 0;
			return 0;
		}

		if (!fcgi_get_params(req, buf, buf+len)) {
			req->keep = 0;
			return 0;
		}

		zend_hash_internal_pointer_reset_ex(req->env, &pos);
		while ((key_type = zend_hash_get_current_key_ex(req->env, &str_index, &str_length, &num_index, 0, &pos)) != HASH_KEY_NON_EXISTENT) {
			int zlen;
			zend_hash_move_forward_ex(req->env, &pos);
			if (key_type != HASH_KEY_IS_STRING) {
				continue;
			}
			if (zend_hash_find(&fcgi_mgmt_vars, str_index, str_length, (void**) &value) != SUCCESS) {
				continue;
			}
			--str_length;
			zlen = Z_STRLEN_PP(value);
			if ((p + 4 + 4 + str_length + zlen) >= (buf + sizeof(buf))) {
				break;
			}
			if (str_length < 0x80) {
				*p++ = str_length;
			} else {
				*p++ = ((str_length >> 24) & 0xff) | 0x80;
				*p++ = (str_length >> 16) & 0xff;
				*p++ = (str_length >> 8) & 0xff;
				*p++ = str_length & 0xff;
			}
			if (zlen < 0x80) {
				*p++ = zlen;
			} else {
				*p++ = ((zlen >> 24) & 0xff) | 0x80;
				*p++ = (zlen >> 16) & 0xff;
				*p++ = (zlen >> 8) & 0xff;
				*p++ = zlen & 0xff;
			}
			memcpy(p, str_index, str_length);
			p += str_length;
			memcpy(p, Z_STRVAL_PP(value), zlen);
			p += zlen;
		}
		len = p - buf - sizeof(fcgi_header);
		len += fcgi_make_header((fcgi_header*)buf, FCGI_GET_VALUES_RESULT, 0, len);
		if (safe_write(req, buf, sizeof(fcgi_header)+len) != (int)sizeof(fcgi_header)+len) {
			req->keep = 0;
			return 0;
		}
		return 0;
	} else {
Пример #30
0
static zend_always_inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, zend_long elements, int objprops)
{
	while (elements-- > 0) {
		zval key, *data, d, *old_data;
		zend_ulong idx;

		ZVAL_UNDEF(&key);

		if (!php_var_unserialize_internal(&key, p, max, NULL)) {
			zval_ptr_dtor(&key);
			return 0;
		}

		data = NULL;
		ZVAL_UNDEF(&d);

		if (!objprops) {
			if (Z_TYPE(key) == IS_LONG) {
				idx = Z_LVAL(key);
numeric_key:
				if (UNEXPECTED((old_data = zend_hash_index_find(ht, idx)) != NULL)) {
					//??? update hash
					var_push_dtor(var_hash, old_data);
					data = zend_hash_index_update(ht, idx, &d);
				} else {
					data = zend_hash_index_add_new(ht, idx, &d);
				}
			} else if (Z_TYPE(key) == IS_STRING) {
				if (UNEXPECTED(ZEND_HANDLE_NUMERIC(Z_STR(key), idx))) {
					goto numeric_key;
				}
				if (UNEXPECTED((old_data = zend_hash_find(ht, Z_STR(key))) != NULL)) {
					//??? update hash
					var_push_dtor(var_hash, old_data);
					data = zend_hash_update(ht, Z_STR(key), &d);
				} else {
					data = zend_hash_add_new(ht, Z_STR(key), &d);
				}
			} else {
				zval_ptr_dtor(&key);
				return 0;
			}
		} else {
			if (EXPECTED(Z_TYPE(key) == IS_STRING)) {
string_key:
				{
					zend_property_info *existing_propinfo;
					zend_string *new_key, *unmangled;
					const char *unmangled_class = NULL; 
					const char *unmangled_prop;
					size_t unmangled_prop_len;

					if (UNEXPECTED(zend_unmangle_property_name_ex(Z_STR(key), &unmangled_class, &unmangled_prop, &unmangled_prop_len) == FAILURE)) {
						zval_ptr_dtor(&key);
						return 0;
					}

					unmangled = zend_string_init(unmangled_prop, unmangled_prop_len, 0);
					if (Z_TYPE_P(rval) == IS_OBJECT
							&& ((existing_propinfo = zend_hash_find_ptr(&Z_OBJCE_P(rval)->properties_info, unmangled)) != NULL) 
							&& (existing_propinfo->flags & ZEND_ACC_PPP_MASK)) {
						if (existing_propinfo->flags & ZEND_ACC_PROTECTED) {
							new_key = zend_mangle_property_name(
								"*", 1, ZSTR_VAL(unmangled), ZSTR_LEN(unmangled), Z_OBJCE_P(rval)->type & ZEND_INTERNAL_CLASS);
							zend_string_release(unmangled);
						} else if (existing_propinfo->flags & ZEND_ACC_PRIVATE) {
							if (unmangled_class != NULL && strcmp(unmangled_class, "*") != 0) {
								new_key = zend_mangle_property_name(
									unmangled_class, strlen(unmangled_class),
									ZSTR_VAL(unmangled), ZSTR_LEN(unmangled),
									Z_OBJCE_P(rval)->type & ZEND_INTERNAL_CLASS);
							} else {
								new_key = zend_mangle_property_name(
									ZSTR_VAL(existing_propinfo->ce->name), ZSTR_LEN(existing_propinfo->ce->name),
									ZSTR_VAL(unmangled), ZSTR_LEN(unmangled),
									Z_OBJCE_P(rval)->type & ZEND_INTERNAL_CLASS);
							}
							zend_string_release(unmangled);
						} else {
							ZEND_ASSERT(existing_propinfo->flags & ZEND_ACC_PUBLIC);
							new_key = unmangled;
						}
						zend_string_release(Z_STR(key));
						ZVAL_STR(&key, new_key);
					} else {
						zend_string_release(unmangled);
					}

					if ((old_data = zend_hash_find(ht, Z_STR(key))) != NULL) {
						if (Z_TYPE_P(old_data) == IS_INDIRECT) {
							old_data = Z_INDIRECT_P(old_data);
						}
						var_push_dtor(var_hash, old_data);
						data = zend_hash_update_ind(ht, Z_STR(key), &d);
					} else {
						data = zend_hash_add_new(ht, Z_STR(key), &d);
					}
				}
			} else if (Z_TYPE(key) == IS_LONG) {
				/* object properties should include no integers */
				convert_to_string(&key);
				goto string_key;
			} else {
				zval_ptr_dtor(&key);
				return 0;
			}
		}

		if (!php_var_unserialize_internal(data, p, max, var_hash)) {
			zval_ptr_dtor(&key);
			return 0;
		}

		var_push_dtor(var_hash, data);
		zval_ptr_dtor(&key);

		if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
			(*p)--;
			return 0;
		}
	}

	return 1;
}