Пример #1
0
/* {{{ dba_close
 */
static void dba_close(dba_info *info)
{
	if (info->hnd) {
		info->hnd->close(info);
	}
	if (info->path) {
		pefree(info->path, info->flags&DBA_PERSISTENT);
	}
	if (info->fp && info->fp != info->lock.fp) {
		if (info->flags & DBA_PERSISTENT) {
			php_stream_pclose(info->fp);
		} else {
			php_stream_close(info->fp);
		}
	}
	if (info->lock.fp) {
		if (info->flags & DBA_PERSISTENT) {
			php_stream_pclose(info->lock.fp);
		} else {
			php_stream_close(info->lock.fp);
		}
	}
	if (info->lock.name) {
		pefree(info->lock.name, info->flags&DBA_PERSISTENT);
	}
	pefree(info, info->flags&DBA_PERSISTENT);
}
Пример #2
0
static zval* _jsr_file_get_contents()
{
  TSRMLS_FETCH();
  
  zval *payload;

  MAKE_STD_ZVAL(payload);

  zend_bool use_include_path = 0;
  php_stream *stream;
  int len;
  long offset = -1;
  long maxlen = PHP_STREAM_COPY_ALL;
  zval *zcontext = NULL;
  php_stream_context *context = NULL;

  char *contents;

  

  context = php_stream_context_from_zval(zcontext, 0);

  stream = php_stream_open_wrapper_ex("php://input", "rb",
        (use_include_path ? USE_PATH : 0) | ENFORCE_SAFE_MODE | REPORT_ERRORS,
        NULL, context);
  
  if (!stream) {
    ZVAL_NULL(payload);
    php_stream_close(stream);
    return payload;
  }

  if (offset > 0 && php_stream_seek(stream, offset, SEEK_SET) < 0) {
    php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to seek to position %ld in the stream", offset);
    php_stream_close(stream);
    ZVAL_NULL(payload);
    return payload;
  }

  if ((len = php_stream_copy_to_mem(stream, &contents, maxlen, 0)) > 0) {
#if PHP_API_VERSION < 20100412
    if (PG(magic_quotes_runtime)) {
      contents = php_addslashes(contents, len, &len, 1 TSRMLS_CC); 
    }
#endif
    ZVAL_STRINGL(payload, contents, len, 1);
    php_stream_close(stream);
    return payload;
  } else if (len == 0) {
    ZVAL_STRING(payload, "", 0);
    php_stream_close(stream);
    return payload;
  } else {
    ZVAL_NULL(payload);
    php_stream_close(stream);
    return payload;
  }
  
}
Пример #3
0
/** {{{ 从文件载入js代码 */
PHP_METHOD(HyperMobile, loadjsfromfile) {
	char *filename;
	int filename_len;
	char *contents;//,*err;
	php_stream *stream;
	int len;
	zval *self,*value;
		/* Parse arguments */
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &filename, &filename_len) == FAILURE) {
		return;
	}
	self=getThis();

	if (strlen(filename) != filename_len) {
		RETURN_FALSE;
	}

	stream = php_stream_open_wrapper(filename, "rb",
				ENFORCE_SAFE_MODE | REPORT_ERRORS,
				NULL);
	if (!stream) {
		RETURN_FALSE;
	}


	if ((len = php_stream_copy_to_mem(stream, &contents, PHP_STREAM_COPY_ALL, 0)) > 0) {

		if (PG(magic_quotes_runtime)) {
			contents = php_addslashes(contents, len, &len, 1 TSRMLS_CC); /* 1 = free source string */
		}
		php_stream_close(stream);
		//
		MAKE_STD_ZVAL(value);
		ZVAL_STRING(value,contents,0);
		zend_update_property(Z_OBJCE_P(self),self,ZEND_STRL("js_content"),value TSRMLS_CC);
		RETURN_TRUE;
	} else if (len == 0) {
		php_stream_close(stream);
		MAKE_STD_ZVAL(value);
		// err = ;
		ZVAL_STRING(value,"file content is empty",0);
		zend_update_property(Z_OBJCE_P(self),self,ZEND_STRL("err_msg"),value TSRMLS_CC);
		zend_update_property_bool(Z_OBJCE_P(self),self,ZEND_STRL("error"),1 TSRMLS_CC);
		RETURN_FALSE;
	} else {
		php_stream_close(stream);
		MAKE_STD_ZVAL(value);
		ZVAL_STRING(value,"unknown error",0);
		zend_update_property(Z_OBJCE_P(self),self,ZEND_STRL("err_msg"),value TSRMLS_CC);
		zend_update_property_bool(Z_OBJCE_P(self),self,ZEND_STRL("error"),1 TSRMLS_CC);
		RETURN_FALSE;
	}

	
}
Пример #4
0
static void cli_register_file_handles(void) /* {{{ */
{
	zval zin, zout, zerr;
	php_stream *s_in, *s_out, *s_err;
	php_stream_context *sc_in=NULL, *sc_out=NULL, *sc_err=NULL;
	zend_constant ic, oc, ec;

	s_in  = php_stream_open_wrapper_ex("php://stdin",  "rb", 0, NULL, sc_in);
	s_out = php_stream_open_wrapper_ex("php://stdout", "wb", 0, NULL, sc_out);
	s_err = php_stream_open_wrapper_ex("php://stderr", "wb", 0, NULL, sc_err);

	if (s_in==NULL || s_out==NULL || s_err==NULL) {
		if (s_in) php_stream_close(s_in);
		if (s_out) php_stream_close(s_out);
		if (s_err) php_stream_close(s_err);
		return;
	}

#if PHP_DEBUG
	/* do not close stdout and stderr */
	s_out->flags |= PHP_STREAM_FLAG_NO_CLOSE;
	s_err->flags |= PHP_STREAM_FLAG_NO_CLOSE;
#endif

	s_in_process = s_in;

	php_stream_to_zval(s_in,  &zin);
	php_stream_to_zval(s_out, &zout);
	php_stream_to_zval(s_err, &zerr);

	ZVAL_COPY_VALUE(&ic.value, &zin);
	ic.flags = CONST_CS;
	ic.name = zend_string_init("STDIN", sizeof("STDIN")-1, 1);
	ic.module_number = 0;
	zend_register_constant(&ic);

	ZVAL_COPY_VALUE(&oc.value, &zout);
	oc.flags = CONST_CS;
	oc.name = zend_string_init("STDOUT", sizeof("STDOUT")-1, 1);
	oc.module_number = 0;
	zend_register_constant(&oc);

	ZVAL_COPY_VALUE(&ec.value, &zerr);
	ec.flags = CONST_CS;
	ec.name = zend_string_init("STDERR", sizeof("STDERR")-1, 1);
	ec.module_number = 0;
	zend_register_constant(&ec);
}
Пример #5
0
/* {{{ ftp_close
 */
ftpbuf_t*
ftp_close(ftpbuf_t *ftp)
{
	if (ftp == NULL) {
		return NULL;
	}
	if (ftp->data) {
		data_close(ftp, ftp->data);
	}
	if (ftp->stream && ftp->closestream) {
			php_stream_close(ftp->stream);
	}
	if (ftp->fd != -1) {
#ifdef HAVE_FTP_SSL
		if (ftp->ssl_active) {
			SSL_shutdown(ftp->ssl_handle);
			SSL_free(ftp->ssl_handle);
		}
#endif
		closesocket(ftp->fd);
	}
	ftp_gc(ftp);
	efree(ftp);
	return NULL;
}
Пример #6
0
void zephir_file_get_contents(zval *return_value, zval *filename)
{
	zend_string *contents;
	php_stream *stream;
	long maxlen = PHP_STREAM_COPY_ALL;
	zval *zcontext = NULL;
	php_stream_context *context = NULL;

	if (Z_TYPE_P(filename) != IS_STRING) {
		php_error_docref(NULL, E_WARNING, "Invalid arguments supplied for zephir_file_get_contents()");
		RETVAL_FALSE;
		return;
	}

	context = php_stream_context_from_zval(zcontext, 0);

	stream = php_stream_open_wrapper_ex(Z_STRVAL_P(filename), "rb", 0 | REPORT_ERRORS, NULL, context);
	if (!stream) {
		RETURN_FALSE;
	}

	if ((contents = php_stream_copy_to_mem(stream, maxlen, 0)) != NULL) {
		RETVAL_STR(contents);
	} else {
		RETVAL_EMPTY_STRING();
	}

	php_stream_close(stream);
}
Пример #7
0
/* {{{ proto int readgzfile(string filename [, int use_include_path])
   Output a .gz-file */
static PHP_FUNCTION(readgzfile)
{
	char *filename;
	size_t filename_len;
	int flags = REPORT_ERRORS;
	php_stream *stream;
	size_t size;
	zend_long use_include_path = 0;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|l", &filename, &filename_len, &use_include_path) == FAILURE) {
		return;
	}

	if (use_include_path) {
		flags |= USE_PATH;
	}

	stream = php_stream_gzopen(NULL, filename, "rb", flags, NULL, NULL STREAMS_CC);

	if (!stream) {
		RETURN_FALSE;
	}
	size = php_stream_passthru(stream);
	php_stream_close(stream);
	RETURN_LONG(size);
}
Пример #8
0
/* {{{ php_stream_ftp_stream_close
 */
static int php_stream_ftp_stream_close(php_stream_wrapper *wrapper, php_stream *stream)
{
	php_stream *controlstream = stream->wrapperthis;
	int ret = 0;
	
	if (controlstream) {
		if (strpbrk(stream->mode, "wa+")) {
			char tmp_line[512];
			int result;

			/* For write modes close data stream first to signal EOF to server */
			result = GET_FTP_RESULT(controlstream);
			if (result != 226 && result != 250) {
				php_error_docref(NULL, E_WARNING, "FTP server error %d:%s", result, tmp_line);
				ret = EOF;
			}
		}

		php_stream_write_string(controlstream, "QUIT\r\n");
		php_stream_close(controlstream);
		stream->wrapperthis = NULL;
	}

	return ret;
}
Пример #9
0
/* {{{ ftp_close
 */
ftpbuf_t*
ftp_close(ftpbuf_t *ftp)
{
	if (ftp == NULL) {
		return NULL;
	}
	if (ftp->data) {
		data_close(ftp, ftp->data);
	}
	if (ftp->stream && ftp->closestream) {
		TSRMLS_FETCH();
		php_stream_close(ftp->stream);
	}
	if (ftp->fd != -1) {
#if HAVE_OPENSSL_EXT
		if (ftp->ssl_active) {
			SSL_shutdown(ftp->ssl_handle);
			SSL_free(ftp->ssl_handle);
		}
#endif		
		closesocket(ftp->fd);
	}	
	ftp_gc(ftp);
	efree(ftp);
	return NULL;
}
Пример #10
0
static void php_hash_do_hash(INTERNAL_FUNCTION_PARAMETERS, int isfilename, zend_bool raw_output_default) /* {{{ */
{
	char *algo, *data, *digest;
	int algo_len, data_len;
	zend_bool raw_output = raw_output_default;
	const php_hash_ops *ops;
	void *context;
	php_stream *stream = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|b", &algo, &algo_len, &data, &data_len, &raw_output) == FAILURE) {
		return;
	}

	ops = php_hash_fetch_ops(algo, algo_len);
	if (!ops) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown hashing algorithm: %s", algo);
		RETURN_FALSE;
	}
	if (isfilename) {
		if (CHECK_NULL_PATH(data, data_len)) {
			RETURN_FALSE;
		}
		stream = php_stream_open_wrapper_ex(data, "rb", REPORT_ERRORS, NULL, DEFAULT_CONTEXT);
		if (!stream) {
			/* Stream will report errors opening file */
			RETURN_FALSE;
		}
	}

	context = emalloc(ops->context_size);
	ops->hash_init(context);

	if (isfilename) {
		char buf[1024];
		int n;

		while ((n = php_stream_read(stream, buf, sizeof(buf))) > 0) {
			ops->hash_update(context, (unsigned char *) buf, n);
		}
		php_stream_close(stream);
	} else {
		ops->hash_update(context, (unsigned char *) data, data_len);
	}

	digest = emalloc(ops->digest_size + 1);
	ops->hash_final((unsigned char *) digest, context);
	efree(context);

	if (raw_output) {
		digest[ops->digest_size] = 0;
		RETURN_STRINGL(digest, ops->digest_size, 0);
	} else {
		char *hex_digest = safe_emalloc(ops->digest_size, 2, 1);

		php_hash_bin2hex(hex_digest, (unsigned char *) digest, ops->digest_size);
		hex_digest[2 * ops->digest_size] = 0;
		efree(digest);
		RETURN_STRINGL(hex_digest, 2 * ops->digest_size, 0);
	}
}
Пример #11
0
/**
 * Gets HTTP raw request body
 *
 * @return string
 */
PHP_METHOD(Phalcon_Http_Request, getRawBody)
{
	zval raw = {}, *zcontext = NULL;
	zend_string *content;
	php_stream_context *context;
	php_stream *stream;
	long int maxlen;

	phalcon_read_property(&raw, getThis(), SL("_rawBody"), PH_NOISY);
	if (Z_TYPE(raw) == IS_STRING) {
		RETURN_CTORW(&raw);
	}

	context = php_stream_context_from_zval(zcontext, 0);
	stream = php_stream_open_wrapper_ex("php://input", "rb", REPORT_ERRORS, NULL, context);
	maxlen    = PHP_STREAM_COPY_ALL;

	if (!stream) {
		RETURN_FALSE;
	}

	content = php_stream_copy_to_mem(stream, maxlen, 0);
	if (content != NULL) {
		RETVAL_STR(content);
		phalcon_update_property_zval(getThis(), SL("_rawBody"), return_value);
	} else {
		RETVAL_FALSE;
	}

	php_stream_close(stream);
}
Пример #12
0
ZEND_METHOD(hprose_bytes_io, load) {
    php_stream *stream;
    char *filename;
#if PHP_MAJOR_VERSION < 7
    char *buf;
#else
    zend_string *s;
#endif
    length_t len;
    HPROSE_OBJECT_INTERN(bytes_io);
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &filename, &len) == FAILURE) {
        return;
    }
    stream = php_stream_open_wrapper(filename, "rb", REPORT_ERRORS, NULL);
    if (stream == NULL) {
        RETURN_FALSE;
    }
#if PHP_MAJOR_VERSION < 7
    if ((len = php_stream_copy_to_mem(stream, &buf, PHP_STREAM_COPY_ALL, HB_PERSISTENT_P(intern->_this))) > 0) {
        hprose_bytes_io_close(intern->_this);
        intern->_this->buf = buf;
        HB_CAP_P(intern->_this) = len;
        HB_LEN_P(intern->_this) = len;
        HB_POS_P(intern->_this) = 0;
        intern->mark = -1;
    }
#else
    if ((s = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, HB_PERSISTENT_P(intern->_this))) != NULL) {
        hprose_bytes_io_close(intern->_this);
        intern->_this->s = s;
        HB_CAP_P(intern->_this) = HB_LEN_P(intern->_this);
        HB_POS_P(intern->_this) = 0;
        intern->mark = -1;
    }
#endif
    else if (len == 0) {
        hprose_bytes_io_close(intern->_this);
        intern->mark = -1;
    }
    else {
        php_stream_close(stream);
        RETURN_FALSE;
    }
    php_stream_close(stream);
    RETURN_TRUE;
}
Пример #13
0
static int stream_cookie_closer(void *cookie)
{
    php_stream *stream = (php_stream*)cookie;
    TSRMLS_FETCH();

    /* prevent recursion */
    stream->fclose_stdiocast = PHP_STREAM_FCLOSE_NONE;
    return php_stream_close(stream);
}
Пример #14
0
/**
 * override __call()
 * it require two parameters, func_name and args
 **/
PHP_METHOD(McpackHessianClient, __call) {
	zend_class_entry *ce;
	zval *p_this, *args, *params, *result, *method, *tmp;
	char *func_name, *ret_str = NULL;
	int func_name_len = 0;
	size_t return_len = 0, max_len = 1024 * 1024 * 1024;

	p_this = getThis();
	if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, p_this, 
		"Osz", &ce, mcphessian_ce_ptr, &func_name, &func_name_len, &args) == FAILURE) {
		php_error(E_WARNING, "parse parameters error.");
		RETURN_NULL();
	}

	// init params
	MAKE_STD_ZVAL(params);
	array_init(params);
	add_assoc_string(params, "jsonrpc", "2.0", 0);
	add_assoc_string(params, "method", func_name, 0);
	add_assoc_zval(params, "params", args);
	add_assoc_string(params, "id", "123456", 0);
	zval *pack = array2mcpack(params);

	// post data
	zval *z_url = zend_read_property(mcphessian_ce_ptr, p_this, ZEND_STRL("url"), 1 TSRMLS_CC);
	convert_to_string(z_url);
	char *url = Z_STRVAL_P(z_url);
	php_stream_context *context = php_stream_context_alloc();
	MAKE_STD_ZVAL(method);
	ZVAL_STRING(method, "POST", 0);
	php_stream_context_set_option(context, "http", "method", method);
	php_stream_context_set_option(context, "http", "content", pack);

	// read data from stream
	php_stream *stream = php_stream_open_wrapper_ex(url, "rb", REPORT_ERRORS, NULL, context);
	if (stream) {
		ret_str = php_stream_get_line(stream, NULL, max_len, &return_len);
	} else {
		php_error(E_WARNING, "failed to open stream %s.", url);
		RETURN_NULL();
	}
	MAKE_STD_ZVAL(tmp);
	ZVAL_STRINGL(tmp, ret_str, return_len, 0);
	result = mcpack2array(tmp);
	php_stream_close(stream);
	efree(ret_str);

	// get result from array
	zval **ret_val;
	if (zend_hash_exists(Z_ARRVAL_P(result), "result", 7)) {
		zend_hash_find(Z_ARRVAL_P(result), "result", 7, (void **)&ret_val);
		RETURN_ZVAL(*ret_val, 1, 0);
	} else {
		php_error(E_WARNING, "return value illegal.");
		RETURN_NULL();
	}
}
Пример #15
0
void php_mail_log_to_file(char *filename, char *message, size_t message_size TSRMLS_DC) {
    /* Write 'message' to the given file. */
    uint flags = IGNORE_URL_WIN | REPORT_ERRORS | STREAM_DISABLE_OPEN_BASEDIR;
    php_stream *stream = php_stream_open_wrapper(filename, "a", flags, NULL);
    if (stream) {
        php_stream_write(stream, message, message_size);
        php_stream_close(stream);
    }
}
Пример #16
0
/**
 * Prints out HTTP response to the client
 *
 * @return Phalcon\Http\ResponseInterface
 */
PHP_METHOD(Phalcon_Http_Response, send){

	zval *sent, *headers, *cookies, *content, *file;

	PHALCON_MM_GROW();

	PHALCON_OBS_VAR(sent);
	phalcon_read_property_this(&sent, this_ptr, SL("_sent"), PH_NOISY_CC);
	if (PHALCON_IS_FALSE(sent)) {
	
		/** 
		 * Send headers
		 */
		PHALCON_OBS_VAR(headers);
		phalcon_read_property_this(&headers, this_ptr, SL("_headers"), PH_NOISY_CC);
		if (Z_TYPE_P(headers) == IS_OBJECT) {
			phalcon_call_method_noret(headers, "send");
		}
	
		PHALCON_OBS_VAR(cookies);
		phalcon_read_property_this(&cookies, this_ptr, SL("_cookies"), PH_NOISY_CC);
		if (Z_TYPE_P(cookies) == IS_OBJECT) {
			phalcon_call_method_noret(cookies, "send");
		}
	
		/** 
		 * Output the response body
		 */
		PHALCON_OBS_VAR(content);
		phalcon_read_property_this(&content, this_ptr, SL("_content"), PH_NOISY_CC);
		if (Z_STRLEN_P(content)) {
			zend_print_zval(content, 0);
		}
		else {
			PHALCON_OBS_VAR(file);
			phalcon_read_property_this(&file, this_ptr, SL("_file"), PH_NOISY_CC);

			if (Z_STRLEN_P(file)) {
				php_stream *stream;

				stream = php_stream_open_wrapper(Z_STRVAL_P(file), "rb", REPORT_ERRORS, NULL);
				if (stream != NULL) {
					php_stream_passthru(stream);
					php_stream_close(stream);
				}
			}
		}

		phalcon_update_property_bool(this_ptr, SL("_sent"), 1 TSRMLS_CC);
	
		RETURN_THIS();
	}
	
	PHALCON_THROW_EXCEPTION_STR(phalcon_http_response_exception_ce, "Response was already sent");
	return;
}
Пример #17
0
static void _php_image_stream_ctxfreeandclose(struct gdIOCtx *ctx) /* {{{ */
{

	if(ctx->data) {
		php_stream_close((php_stream *) ctx->data);
		ctx->data = NULL;
	}
	if(ctx) {
		efree(ctx);
	}
} /* }}} */
Пример #18
0
static void _php_image_stream_ctxfree(struct gdIOCtx *ctx)
{
	TSRMLS_FETCH();

	if(ctx->data) {
		php_stream_close((php_stream *) ctx->data);
		ctx->data = NULL;
	}
	if(ctx) {
		efree(ctx);
	}
}
Пример #19
0
/* {{{ mysqlnd_local_infile_end */
static
void mysqlnd_local_infile_end(void * ptr)
{
	MYSQLND_INFILE_INFO	*info = (MYSQLND_INFILE_INFO *)ptr;

	if (info) {
		/* php_stream_close segfaults on NULL */
		if (info->fd) {
			php_stream_close(info->fd);
			info->fd = NULL;
		}
		mnd_efree(info);
	}
}
Пример #20
0
static zend_string *php_tidy_file_to_mem(char *filename, zend_bool use_include_path)
{
	php_stream *stream;
	zend_string *data = NULL;

	if (!(stream = php_stream_open_wrapper(filename, "rb", (use_include_path ? USE_PATH : 0), NULL))) {
		return NULL;
	}
	if ((data = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0)) == NULL) {
		data = ZSTR_EMPTY_ALLOC();
	}
	php_stream_close(stream);

	return data;
}
Пример #21
0
void php_yar_socket_close(yar_transport_interface_t* self) /* {{{ */ {
	yar_socket_data_t *data = (yar_socket_data_t *)self->data;

	if (!data) {
		return;
	}

	if (!data->persistent && data->stream) {
		php_stream_close(data->stream);
	}

	efree(data);
	efree(self);

	return;
}
Пример #22
0
Файл: jam.c Проект: brzuchal/jam
static void php_jam_display_error_page(char *filename) 
{
	php_stream *stream = php_stream_open_wrapper(filename, "r", ENFORCE_SAFE_MODE & ~REPORT_ERRORS, NULL);
	
	if (stream) {
		char *buff;
		size_t buff_size;
		
		buff_size = php_stream_copy_to_mem(stream, &buff, PHP_STREAM_COPY_ALL, 0);
		php_stream_close(stream);
		
		if (buff_size) {
			PHPWRITE(buff, buff_size);
			efree(buff);
		}
	}
}
Пример #23
0
static int php_gziop_close(php_stream *stream, int close_handle)
{
	struct php_gz_stream_data_t *self = (struct php_gz_stream_data_t *) stream->abstract;
	int ret = EOF;

	if (close_handle) {
		if (self->gz_file) {
			ret = gzclose(self->gz_file);
			self->gz_file = NULL;
		}
		if (self->stream) {
			php_stream_close(self->stream);
			self->stream = NULL;
		}
	}
	efree(self);

	return ret;
}
Пример #24
0
/* {{{ markdown_init_from_stream */
static int markdown_init_from_stream(zval* obj, zval *zstream, long flags TSRMLS_DC)
{
	discount_object *dobj = zend_object_store_get_object(obj TSRMLS_CC);
	MMIOT			*mmiot;
	php_stream		*stream;
	int				close;
	FILE			*f;
	int				ret;

	if (dobj->markdoc != NULL) {
		zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC,
			"This object has already been initialized.");
		return FAILURE;
	}

	if (markdown_check_input_flags((mkd_flag_t) flags TSRMLS_CC) == FAILURE) {
		return FAILURE;
	}

	if (markdowndoc_get_file(zstream, 0, &stream, &close, &f TSRMLS_CC) == FAILURE) {
		return FAILURE;
	}

	mmiot = mkd_in(f, (mkd_flag_t) flags);
	if (mmiot == NULL) {
		zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC,
			"Error initializing markdown document: call to the library routine "
			"mkd_in() failed");
		ret = FAILURE;
	} else {
		dobj->markdoc = mmiot;
		ret = SUCCESS;
	}

	if (close) {
		php_stream_close(stream);
	}
	return ret;
}
Пример #25
0
ZEND_METHOD(hprose_bytes_io, save) {
    php_stream *stream;
    char *filename;
    length_t len;
    int32_t numbytes = 0;
    HPROSE_THIS(bytes_io);
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &filename, &len) == FAILURE) {
        return;
    }
    stream = php_stream_open_wrapper(filename, "wb", REPORT_ERRORS, NULL);
    if (stream == NULL) {
        RETURN_FALSE;
    }
    if (HB_INITED_P(_this) && HB_LEN_P(_this)) {
        numbytes = php_stream_write(stream, HB_BUF_P(_this), HB_LEN_P(_this));
        if (numbytes != HB_LEN_P(_this)) {
            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Only %d of %d bytes written, possibly out of free disk space", numbytes, HB_LEN_P(_this));
            numbytes = -1;
        }
    }
    php_stream_close(stream);
    RETURN_LONG(numbytes);    
}
Пример #26
0
/* {{{ proto array gzfile(string filename [, int use_include_path])
   Read and uncompress entire .gz-file into an array */
static PHP_FUNCTION(gzfile)
{
	char *filename;
	size_t filename_len;
	int flags = REPORT_ERRORS;
	char buf[8192] = {0};
	register int i = 0;
	zend_long use_include_path = 0;
	php_stream *stream;

	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "p|l", &filename, &filename_len, &use_include_path)) {
		return;
	}

	if (use_include_path) {
		flags |= USE_PATH;
	}

	/* using a stream here is a bit more efficient (resource wise) than php_gzopen_wrapper */
	stream = php_stream_gzopen(NULL, filename, "rb", flags, NULL, NULL STREAMS_CC);

	if (!stream) {
		/* Error reporting is already done by stream code */
		RETURN_FALSE;
	}

	/* Initialize return array */
	array_init(return_value);

	/* Now loop through the file and do the magic quotes thing if needed */
	memset(buf, 0, sizeof(buf));

	while (php_stream_gets(stream, buf, sizeof(buf) - 1) != NULL) {
		add_index_string(return_value, i++, buf);
	}
	php_stream_close(stream);
}
Пример #27
0
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;
    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, have_header = 0;

    if (redirect_max < 1) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Circular redirect, aborting.");
        return NULL;
    }

    if (strpbrk(mode, "aw+")) {
        php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP wrapper does not support writeable connections.");
        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"))) {
        php_url_free(resource);
        return php_stream_open_wrapper_ex(path, mode, ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL, context);
    }

    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;

    stream = php_stream_sock_open_host(resource->host, resource->port, SOCK_STREAM, NULL, 0);
    if (stream == NULL) {
        eol_detect = 0;
        goto out;
    }

    /* 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);

#ifdef HAVE_OPENSSL_EXT
    if (use_ssl)	{

        if (context) {
            /* set the CN we expect to be on the remote cert.
             * You still need to have enabled verification (verify_peer) in the context for
             * this to have an effect */
            zval *cn;

            ALLOC_INIT_ZVAL(cn);
            ZVAL_STRING(cn, resource->host, 1);
            php_stream_context_set_option(context, "ssl", "CN_match", cn);
        }

        if (php_stream_sock_ssl_activate(stream, 1) == FAILURE)	{
            php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Unable to activate SSL mode");
            php_stream_close(stream);
            stream = NULL;
            goto out;
        }
    }
#endif

    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 = (char *)emalloc(scratch_len);
            strlcpy(scratch, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval) + 1);
            strcat(scratch, " ");
        }
    }

    if (!scratch) {
        scratch_len = strlen(path) + 32;
        scratch = (char *)emalloc(scratch_len);
        strcpy(scratch, "GET ");
    }

    /* 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 */
    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_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) {
            /* Output trimmed headers with \r\n at the end */
            php_stream_write(stream, tmp, strlen(tmp));
            php_stream_write(stream, "\r\n", sizeof("\r\n") - 1);

            /* 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;
            }
        }
        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 = (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) && 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) || (!use_ssl && resource->port != 80))	{
            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) {
        ua_str = Z_STRVAL_PP(ua_zval);
    } else if (FG(user_agent)) {
        ua_str = FG(user_agent);
    }

    if (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 = (char *)emalloc(ua_len + 1);
            if ((ua_len = snprintf(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);
            }
        }
    }

    php_stream_write(stream, "\r\n", sizeof("\r\n")-1);

    /* Request content, such as for POST requests */
    if (context && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_STRLEN_PP(tmpzval) > 0) {
        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);
    }

    location[0] = '\0';

    /*
     * We need to read the HTTP response header one-by-one, because
     * the original author did not know about MSG_PEEK.
     * The chunk_size will be reset later, once we have read the
     * header completely.
     */
    if (options & STREAM_WILL_CAST)
        chunk_size = php_stream_set_chunk_size(stream, 1);

    if (!header_init && FAILURE == zend_hash_find(EG(active_symbol_table),
            "http_response_header", sizeof("http_response_header"), (void **) &response_header)) {
        header_init = 1;
    }

    if (header_init) {
        zval *tmp;
        MAKE_STD_ZVAL(tmp);
        array_init(tmp);
        ZEND_SET_SYMBOL(EG(active_symbol_table), "http_response_header", tmp);

        zend_hash_find(EG(active_symbol_table),
                       "http_response_header", sizeof("http_response_header"), (void **) &response_header);
    }


    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 TSRMLS_CC) != NULL) {
            zval *http_response;
            int response_code;

            MAKE_STD_ZVAL(http_response);
            ZVAL_NULL(http_response);

            if (tmp_line_len > 9) {
                response_code = atoi(tmp_line + 9);
            } else {
                response_code = 0;
            }
            switch(response_code) {
            case 200:
            case 302:
            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);
            }

            Z_STRLEN_P(http_response) = tmp_line_len;
            Z_STRVAL_P(http_response) = estrndup(tmp_line, Z_STRLEN_P(http_response));
            if (Z_STRVAL_P(http_response)[Z_STRLEN_P(http_response)-1]=='\n') {
                Z_STRVAL_P(http_response)[Z_STRLEN_P(http_response)-1]=0;
                Z_STRLEN_P(http_response)--;
                if (Z_STRVAL_P(http_response)[Z_STRLEN_P(http_response)-1]=='\r') {
                    Z_STRVAL_P(http_response)[Z_STRLEN_P(http_response)-1]=0;
                    Z_STRLEN_P(http_response)--;
                }
            }
            Z_TYPE_P(http_response) = IS_STRING;
            zend_hash_next_index_insert(Z_ARRVAL_PP(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 = (char *)emalloc(HTTP_HEADER_BLOCK_SIZE);

    while (!body && !php_stream_eof(stream))	{

        if (php_stream_gets(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL)	{
            char *p;
            int found_eol = 0;
            int http_header_line_length;

            http_header_line[HTTP_HEADER_BLOCK_SIZE-1] = '\0';

            p = http_header_line;
            while(*p) {
                while(*p == '\n' || *p == '\r')	{
                    *p = '\0';
                    p--;
                    found_eol = 1;
                }
                if (found_eol)
                    break;
                p++;
            }
            http_header_line_length = p-http_header_line+1;

            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_PP(response_header), &http_header, sizeof(zval *), NULL);
            }
        } else {
            break;
        }
    }

    if (!reqok || location[0] != '\0')	{
        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')	{

            zval *entry, **entryp;
            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));
            }
            stream = php_stream_url_wrap_http_ex(NULL, new_path, mode, options, opened_path, context, --redirect_max, 0 STREAMS_CC TSRMLS_CC);
            if (stream && stream->wrapperdata)	{
                entryp = &entry;
                MAKE_STD_ZVAL(entry);
                ZVAL_EMPTY_STRING(entry);
                zend_hash_next_index_insert(Z_ARRVAL_PP(response_header), entryp, sizeof(zval *), NULL);
                zend_hash_internal_pointer_reset(Z_ARRVAL_P(stream->wrapperdata));
                while (zend_hash_get_current_data(Z_ARRVAL_P(stream->wrapperdata), (void **)&entryp) == SUCCESS) {
                    zval_add_ref(entryp);
                    zend_hash_next_index_insert(Z_ARRVAL_PP(response_header), entryp, sizeof(zval *), NULL);
                    zend_hash_move_forward(Z_ARRVAL_P(stream->wrapperdata));
                }
                zval_dtor(stream->wrapperdata);
                FREE_ZVAL(stream->wrapperdata);
            }
        } else {
            php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed! %s", tmp_line);
        }
    }
out:
    if (http_header_line)
        efree(http_header_line);
    if (scratch)
        efree(scratch);
    php_url_free(resource);

    if (stream) {
        if (header_init) {
            stream->wrapperdata = *response_header;
            zval_add_ref(response_header);
        }
        php_stream_notify_progress_init(context, 0, file_size);
        /* Restore original chunk size now that we're done with headers (if applicable) */
        if (options & STREAM_WILL_CAST)
            php_stream_set_chunk_size(stream, chunk_size);

        /* restore the users auto-detect-line-endings setting */
        stream->flags |= eol_detect;

        /* as far as streams are concerned, we are now at the start of
         * the stream */
        stream->position = 0;
    }

    return stream;
}
Пример #28
0
static void php_hash_do_hash_hmac(INTERNAL_FUNCTION_PARAMETERS, int isfilename, zend_bool raw_output_default) /* {{{ */
{
	char *algo, *data, *digest, *key, *K;
	int algo_len, data_len, key_len, i;
	zend_bool raw_output = raw_output_default;
	const php_hash_ops *ops;
	void *context;
	php_stream *stream = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss|b", &algo, &algo_len, &data, &data_len, 
																  &key, &key_len, &raw_output) == FAILURE) {
		return;
	}

	ops = php_hash_fetch_ops(algo, algo_len);
	if (!ops) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown hashing algorithm: %s", algo);
		RETURN_FALSE;
	}
	if (isfilename) {
		stream = php_stream_open_wrapper_ex(data, "rb", REPORT_ERRORS, NULL, DEFAULT_CONTEXT);
		if (!stream) {
			/* Stream will report errors opening file */
			RETURN_FALSE;
		}
	}

	context = emalloc(ops->context_size);
	ops->hash_init(context);

	K = emalloc(ops->block_size);
	memset(K, 0, ops->block_size);

	if (key_len > ops->block_size) {
		/* Reduce the key first */
		ops->hash_update(context, (unsigned char *) key, key_len);
		ops->hash_final((unsigned char *) K, context);
		/* Make the context ready to start over */
		ops->hash_init(context);
	} else {
		memcpy(K, key, key_len);
	}
			
	/* XOR ipad */
	for(i=0; i < ops->block_size; i++) {
		K[i] ^= 0x36;
	}
	ops->hash_update(context, (unsigned char *) K, ops->block_size);

	if (isfilename) {
		char buf[1024];
		int n;

		while ((n = php_stream_read(stream, buf, sizeof(buf))) > 0) {
			ops->hash_update(context, (unsigned char *) buf, n);
		}
		php_stream_close(stream);
	} else {
		ops->hash_update(context, (unsigned char *) data, data_len);
	}

	digest = emalloc(ops->digest_size + 1);
	ops->hash_final((unsigned char *) digest, context);

	/* Convert K to opad -- 0x6A = 0x36 ^ 0x5C */
	for(i=0; i < ops->block_size; i++) {
		K[i] ^= 0x6A;
	}

	/* Feed this result into the outter hash */
	ops->hash_init(context);
	ops->hash_update(context, (unsigned char *) K, ops->block_size);
	ops->hash_update(context, (unsigned char *) digest, ops->digest_size);
	ops->hash_final((unsigned char *) digest, context);

	/* Zero the key */
	memset(K, 0, ops->block_size);
	efree(K);
	efree(context);

	if (raw_output) {
		digest[ops->digest_size] = 0;
		RETURN_STRINGL(digest, ops->digest_size, 0);
	} else {
		char *hex_digest = safe_emalloc(ops->digest_size, 2, 1);

		php_hash_bin2hex(hex_digest, (unsigned char *) digest, ops->digest_size);
		hex_digest[2 * ops->digest_size] = 0;
		efree(digest);
		RETURN_STRINGL(hex_digest, 2 * ops->digest_size, 0);
	}
}
Пример #29
0
/* {{{ php_stream_cast */
PHPAPI int _php_stream_cast(php_stream *stream, int castas, void **ret, int show_err)
{
	int flags = castas & PHP_STREAM_CAST_MASK;
	castas &= ~PHP_STREAM_CAST_MASK;

	/* synchronize our buffer (if possible) */
	if (ret && castas != PHP_STREAM_AS_FD_FOR_SELECT) {
		php_stream_flush(stream);
		if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) {
			zend_off_t dummy;

			stream->ops->seek(stream, stream->position, SEEK_SET, &dummy);
			stream->readpos = stream->writepos = 0;
		}
	}

	/* filtered streams can only be cast as stdio, and only when fopencookie is present */

	if (castas == PHP_STREAM_AS_STDIO) {
		if (stream->stdiocast) {
			if (ret) {
				*(FILE**)ret = stream->stdiocast;
			}
			goto exit_success;
		}

		/* if the stream is a stdio stream let's give it a chance to respond
		 * first, to avoid doubling up the layers of stdio with an fopencookie */
		if (php_stream_is(stream, PHP_STREAM_IS_STDIO) &&
			stream->ops->cast &&
			!php_stream_is_filtered(stream) &&
			stream->ops->cast(stream, castas, ret) == SUCCESS
		) {
			goto exit_success;
		}

#if HAVE_FOPENCOOKIE
		/* if just checking, say yes we can be a FILE*, but don't actually create it yet */
		if (ret == NULL) {
			goto exit_success;
		}

		{
			char fixed_mode[5];
			php_stream_mode_sanitize_fdopen_fopencookie(stream, fixed_mode);
			*(FILE**)ret = fopencookie(stream, fixed_mode, PHP_STREAM_COOKIE_FUNCTIONS);
		}

		if (*ret != NULL) {
			zend_off_t pos;

			stream->fclose_stdiocast = PHP_STREAM_FCLOSE_FOPENCOOKIE;

			/* If the stream position is not at the start, we need to force
			 * the stdio layer to believe it's real location. */
			pos = php_stream_tell(stream);
			if (pos > 0) {
				zend_fseek(*ret, pos, SEEK_SET);
			}

			goto exit_success;
		}

		/* must be either:
			a) programmer error
			b) no memory
			-> lets bail
		*/
		php_error_docref(NULL, E_ERROR, "fopencookie failed");
		return FAILURE;
#endif

		if (!php_stream_is_filtered(stream) && stream->ops->cast && stream->ops->cast(stream, castas, NULL) == SUCCESS) {
			if (FAILURE == stream->ops->cast(stream, castas, ret)) {
				return FAILURE;
			}
			goto exit_success;
		} else if (flags & PHP_STREAM_CAST_TRY_HARD) {
			php_stream *newstream;

			newstream = php_stream_fopen_tmpfile();
			if (newstream) {
				int retcopy = php_stream_copy_to_stream_ex(stream, newstream, PHP_STREAM_COPY_ALL, NULL);

				if (retcopy != SUCCESS) {
					php_stream_close(newstream);
				} else {
					int retcast = php_stream_cast(newstream, castas | flags, (void **)ret, show_err);

					if (retcast == SUCCESS) {
						rewind(*(FILE**)ret);
					}

					/* do some specialized cleanup */
					if ((flags & PHP_STREAM_CAST_RELEASE)) {
						php_stream_free(stream, PHP_STREAM_FREE_CLOSE_CASTED);
					}

					/* TODO: we probably should be setting .stdiocast and .fclose_stdiocast or
					 * we may be leaking the FILE*. Needs investigation, though. */
					return retcast;
				}
			}
		}
	}

	if (php_stream_is_filtered(stream)) {
		php_error_docref(NULL, E_WARNING, "cannot cast a filtered stream on this system");
		return FAILURE;
	} else if (stream->ops->cast && stream->ops->cast(stream, castas, ret) == SUCCESS) {
		goto exit_success;
	}

	if (show_err) {
		/* these names depend on the values of the PHP_STREAM_AS_XXX defines in php_streams.h */
		static const char *cast_names[4] = {
			"STDIO FILE*",
			"File Descriptor",
			"Socket Descriptor",
			"select()able descriptor"
		};

		php_error_docref(NULL, E_WARNING, "cannot represent a stream of type %s as a %s", stream->ops->label, cast_names[castas]);
	}

	return FAILURE;

exit_success:

	if ((stream->writepos - stream->readpos) > 0 &&
		stream->fclose_stdiocast != PHP_STREAM_FCLOSE_FOPENCOOKIE &&
		(flags & PHP_STREAM_CAST_INTERNAL) == 0
	) {
		/* the data we have buffered will be lost to the third party library that
		 * will be accessing the stream.  Emit a warning so that the end-user will
		 * know that they should try something else */

		php_error_docref(NULL, E_WARNING, ZEND_LONG_FMT " bytes of buffered data lost during stream conversion!", (zend_long)(stream->writepos - stream->readpos));
	}

	if (castas == PHP_STREAM_AS_STDIO && ret) {
		stream->stdiocast = *(FILE**)ret;
	}

	if (flags & PHP_STREAM_CAST_RELEASE) {
		php_stream_free(stream, PHP_STREAM_FREE_CLOSE_CASTED);
	}

	return SUCCESS;

}
Пример #30
0
static void php_hash_do_hash(INTERNAL_FUNCTION_PARAMETERS, int isfilename, zend_bool raw_output_default) /* {{{ */
{
	zend_string *digest;
	char *algo, *data;
	size_t algo_len, data_len;
	zend_bool raw_output = raw_output_default;
	const php_hash_ops *ops;
	void *context;
	php_stream *stream = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|b", &algo, &algo_len, &data, &data_len, &raw_output) == FAILURE) {
		return;
	}

	ops = php_hash_fetch_ops(algo, algo_len);
	if (!ops) {
		php_error_docref(NULL, E_WARNING, "Unknown hashing algorithm: %s", algo);
		RETURN_FALSE;
	}
	if (isfilename) {
		if (CHECK_NULL_PATH(data, data_len)) {
			php_error_docref(NULL, E_WARNING, "Invalid path");
			RETURN_FALSE;
		}
		stream = php_stream_open_wrapper_ex(data, "rb", REPORT_ERRORS, NULL, FG(default_context));
		if (!stream) {
			/* Stream will report errors opening file */
			RETURN_FALSE;
		}
	}

	context = emalloc(ops->context_size);
	ops->hash_init(context);

	if (isfilename) {
		char buf[1024];
		size_t n;

		while ((n = php_stream_read(stream, buf, sizeof(buf))) > 0) {
			ops->hash_update(context, (unsigned char *) buf, n);
		}
		php_stream_close(stream);
	} else {
		ops->hash_update(context, (unsigned char *) data, data_len);
	}

	digest = zend_string_alloc(ops->digest_size, 0);
	ops->hash_final((unsigned char *) ZSTR_VAL(digest), context);
	efree(context);

	if (raw_output) {
		ZSTR_VAL(digest)[ops->digest_size] = 0;
		RETURN_NEW_STR(digest);
	} else {
		zend_string *hex_digest = zend_string_safe_alloc(ops->digest_size, 2, 0, 0);

		php_hash_bin2hex(ZSTR_VAL(hex_digest), (unsigned char *) ZSTR_VAL(digest), ops->digest_size);
		ZSTR_VAL(hex_digest)[2 * ops->digest_size] = 0;
		zend_string_release(digest);
		RETURN_NEW_STR(hex_digest);
	}
}