示例#1
0
/* {{{ mysqlnd_vio::open_pipe */
static php_stream *
MYSQLND_METHOD(mysqlnd_vio, open_pipe)(MYSQLND_VIO * const vio, const MYSQLND_CSTRING scheme, const zend_bool persistent,
									   MYSQLND_STATS * const conn_stats, MYSQLND_ERROR_INFO * const error_info)
{
#if PHP_API_VERSION < 20100412
	unsigned int streams_options = ENFORCE_SAFE_MODE;
#else
	unsigned int streams_options = 0;
#endif
	dtor_func_t origin_dtor;
	php_stream * net_stream = NULL;

	DBG_ENTER("mysqlnd_vio::open_pipe");
	if (persistent) {
		streams_options |= STREAM_OPEN_PERSISTENT;
	}
	streams_options |= IGNORE_URL;
	net_stream = php_stream_open_wrapper(scheme.s + sizeof("pipe://") - 1, "r+", streams_options, NULL);
	if (!net_stream) {
		SET_CLIENT_ERROR(error_info, CR_CONNECTION_ERROR, UNKNOWN_SQLSTATE, "Unknown errror while connecting");
		DBG_RETURN(NULL);
	}
	/*
	  Streams are not meant for C extensions! Thus we need a hack. Every connected stream will
	  be registered as resource (in EG(regular_list). So far, so good. However, it won't be
	  unregistered until the script ends. So, we need to take care of that.
	*/
	origin_dtor = EG(regular_list).pDestructor;
	EG(regular_list).pDestructor = NULL;
	zend_hash_index_del(&EG(regular_list), net_stream->res->handle); /* ToDO: should it be res->handle, do streams register with addref ?*/
	EG(regular_list).pDestructor = origin_dtor;
	net_stream->res = NULL;

	DBG_RETURN(net_stream);
}
示例#2
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);
    }
}
示例#3
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;
}
/** {{{ 从文件载入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;
	}

	
}
示例#5
0
/* {{{ mysqlnd_debug::open */
static enum_func_status
MYSQLND_METHOD(mysqlnd_debug, open)(MYSQLND_DEBUG * self, zend_bool reopen)
{
	MYSQLND_ZTS(self);

	if (!self->file_name) {
		return FAIL;
	}

	self->stream = php_stream_open_wrapper(self->file_name,
										   reopen == TRUE || self->flags & MYSQLND_DEBUG_APPEND? "ab":"wb",
										   REPORT_ERRORS, NULL);
	return self->stream? PASS:FAIL;
}
示例#6
0
文件: tidy.c 项目: CooCoooo/php-src
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;
}
示例#7
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);
		}
	}
}
示例#8
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;
}
示例#9
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);    
}
示例#10
0
int php_imagick_read_image_using_php_streams(php_imagick_object *intern, int type, char *filename, int filename_len TSRMLS_DC)
{
	php_stream *stream;
	MagickBooleanType status;
	FILE *fp;
#if ZEND_MODULE_API_NO > 20060613 
	zend_error_handling error_handling;
#endif
	
#if ZEND_MODULE_API_NO > 20060613 
	zend_replace_error_handling(EH_THROW, php_imagick_exception_class_entry, &error_handling TSRMLS_CC);
#else
	php_set_error_handling(EH_THROW, php_imagick_exception_class_entry TSRMLS_CC);
#endif
	
	stream = php_stream_open_wrapper(filename, "rb", (ENFORCE_SAFE_MODE|IGNORE_PATH) & ~REPORT_ERRORS, NULL);

	if (!stream) {
		goto return_error;
	}
	
	if (php_stream_can_cast(stream, PHP_STREAM_AS_STDIO|PHP_STREAM_CAST_INTERNAL) == FAILURE) {
		goto return_error;
	}

	if (php_stream_cast(stream, PHP_STREAM_AS_STDIO|PHP_STREAM_CAST_INTERNAL, (void*)&fp, 0) == FAILURE) {
		goto return_error;
	}
	
#if ZEND_MODULE_API_NO > 20060613 
	zend_restore_error_handling(&error_handling TSRMLS_CC);
#else
	php_set_error_handling(EH_NORMAL, NULL TSRMLS_CC);
#endif

	if (type == 1) {
		status = MagickReadImageFile(intern->magick_wand, fp);
	} else {
		status = MagickPingImageFile(intern->magick_wand, fp);
	}
	
	if (status == MagickFalse) {
		php_stream_close(stream);
		return IMAGICK_READ_WRITE_UNDERLYING_LIBRARY;
	}
	
	if (php_stream_is(stream, PHP_STREAM_IS_STDIO)) {
		char *absolute = expand_filepath(filename, NULL TSRMLS_CC);
		MagickSetImageFilename(intern->magick_wand, absolute);
		efree(absolute);
	} else {
		/* Set to empty filename, otherwise it will point to MAGICK_TEMP/magick-XXXXX */
		MagickSetImageFilename(intern->magick_wand, "");
	}
	php_stream_close(stream);

	if (status == MagickFalse) {
		return IMAGICK_READ_WRITE_UNDERLYING_LIBRARY;
	}
	
	IMAGICK_CORRECT_ITERATOR_POSITION(intern);
	return IMAGICK_READ_WRITE_NO_ERROR;
	
return_error:
#if ZEND_MODULE_API_NO > 20060613 
	zend_restore_error_handling(&error_handling TSRMLS_CC);
#else
	php_set_error_handling(EH_NORMAL, NULL TSRMLS_CC);
#endif
	if (stream) php_stream_close(stream);
	return IMAGICK_READ_WRITE_UNDERLYING_LIBRARY;
}
示例#11
0
文件: gd_ctx.c 项目: 1HLtd/php-src
/* {{{ _php_image_output_ctx */
static void _php_image_output_ctx(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, void (*func_p)())
{
	zval *imgind;
	char *file = NULL;
	int file_len = 0;
	long quality, basefilter;
	gdImagePtr im;
	int argc = ZEND_NUM_ARGS();
	int q = -1, i;
	int f = -1;
	gdIOCtx *ctx = NULL;
	zval *to_zval = NULL;
	php_stream *stream;

	/* The third (quality) parameter for Wbmp stands for the threshold when called from image2wbmp().
	 * The third (quality) parameter for Wbmp and Xbm stands for the foreground color index when called
	 * from imagey<type>().
	 */
	if (image_type == PHP_GDIMG_TYPE_XBM) {
		if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rp!|ll", &imgind, &file, &file_len, &quality, &basefilter) == FAILURE) {
			return;
		}
	} else {
		/* PHP_GDIMG_TYPE_GIF
		 * PHP_GDIMG_TYPE_PNG 
		 * PHP_GDIMG_TYPE_JPG 
		 * PHP_GDIMG_TYPE_WBM 
		 * PHP_GDIMG_TYPE_WEBP 
		 * */
		if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|z/!ll", &imgind, &to_zval, &quality, &basefilter) == FAILURE) {
			return;
		}
	}

	ZEND_FETCH_RESOURCE(im, gdImagePtr, &imgind, -1, "Image", phpi_get_le_gd());

	if (argc >= 3) {
		q = quality; /* or colorindex for foreground of BW images (defaults to black) */
		if (argc == 4) {
			f = basefilter;
		}
	}

	if (argc > 1 && to_zval != NULL) {
		if (Z_TYPE_P(to_zval) == IS_RESOURCE) {
			php_stream_from_zval_no_verify(stream, &to_zval);
			if (stream == NULL) {
				RETURN_FALSE;
			}
		} else if (Z_TYPE_P(to_zval) == IS_STRING) {
			stream = php_stream_open_wrapper(Z_STRVAL_P(to_zval), "wb", REPORT_ERRORS|IGNORE_PATH|IGNORE_URL_WIN, NULL);
			if (stream == NULL) {
				RETURN_FALSE;
			}
		} else {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid 2nd parameter, it must a filename or a stream");
			RETURN_FALSE;
		}
	} else {
		ctx = emalloc(sizeof(gdIOCtx));
		ctx->putC = _php_image_output_putc;
		ctx->putBuf = _php_image_output_putbuf;
		ctx->gd_free = _php_image_output_ctxfree;

#if APACHE && defined(CHARSET_EBCDIC)
		/* XXX this is unlikely to work any more [email protected] */
		/* This is a binary file already: avoid EBCDIC->ASCII conversion */
		ap_bsetflag(php3_rqst->connection->client, B_EBCDIC2ASCII, 0);
#endif
	}

	if (!ctx)	{
		ctx = emalloc(sizeof(gdIOCtx));
		ctx->putC = _php_image_stream_putc;
		ctx->putBuf = _php_image_stream_putbuf;
		ctx->gd_free = _php_image_stream_ctxfree;
		ctx->data = (void *)stream;
	}

	switch(image_type) {
		case PHP_GDIMG_CONVERT_WBM:
			if(q<0||q>255) {
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'. It must be between 0 and 255", q);
			}
		case PHP_GDIMG_TYPE_JPG:
			(*func_p)(im, ctx, q);
			break;
		case PHP_GDIMG_TYPE_WEBP:
			if (q == -1) {
				q = 80;
			}
			(*func_p)(im, ctx, q);
			break;
		case PHP_GDIMG_TYPE_PNG:
			(*func_p)(im, ctx, q, f);
			break;
		case PHP_GDIMG_TYPE_XBM:
		case PHP_GDIMG_TYPE_WBM:
			if (argc < 3) {
				for(i=0; i < gdImageColorsTotal(im); i++) {
					if(!gdImageRed(im, i) && !gdImageGreen(im, i) && !gdImageBlue(im, i)) break;
				}
				q = i;
			}
			if (image_type == PHP_GDIMG_TYPE_XBM) {
				(*func_p)(im, file, q, ctx);
			} else {
				(*func_p)(im, q, ctx);
			}
			break;
		default:
			(*func_p)(im, ctx);
			break;
	}

	ctx->gd_free(ctx);

	RETURN_TRUE;
}
示例#12
0
int encrypt_file(const char *inputfile,
    const char *outputfile, int expire TSRMLS_DC)
{
    php_stream *output_stream = NULL;
    zval codes;
    int need_free_code = 0;
    char *inbuf, *outbuf;
    int inlen, outlen, dumplen, expireval;
    struct beast_ops *ops = beast_get_default_ops();

    /* Get php codes from script file */
    if (filter_code_comments((char *)inputfile, &codes) == -1) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR,
                              "Unable get codes from php file `%s'", inputfile);
        return -1;
    }

    need_free_code = 1;

    inlen = codes.value.str.len;
    inbuf = codes.value.str.val;

    /* PHP file size can not large than beast_max_filesize */
    if (inlen > beast_max_filesize) {
        return -1;
    }

    /* Open output file */
    output_stream = php_stream_open_wrapper((char *)outputfile, "w+",
        ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL);
    if (!output_stream) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR,
                                        "Unable to open file `%s'", outputfile);
        goto failed;
    }

    /* if computer is little endian, change file size to big endian */
    if (little_endian()) {
        dumplen   = swab32(inlen);
        expireval = swab32(expire);
    } else {
        dumplen   = inlen;
        expireval = expire;
    }

    php_stream_write(output_stream,
        encrypt_file_header_sign, encrypt_file_header_length);
    php_stream_write(output_stream, &dumplen, INT_SIZE);
    php_stream_write(output_stream, &expireval, INT_SIZE);

    if (ops->encrypt(inbuf, inlen, &outbuf, &outlen) == -1) {
        php_error_docref(NULL TSRMLS_CC, E_ERROR,
                                     "Unable to encrypt file `%s'", outputfile);
        goto failed;
    }

    php_stream_write(output_stream, outbuf, outlen);
    php_stream_close(output_stream);
    zval_dtor(&codes);
    if (ops->free)
        ops->free(outbuf);
    return 0;

failed:
    if (output_stream)
        php_stream_close(output_stream);
    if (need_free_code)
        zval_dtor(&codes);
    return -1;
}
示例#13
0
#include "php_cassandra.h"
#include <ext/standard/php_filestat.h>

zend_class_entry *cassandra_ssl_builder_ce = NULL;

static int
file_get_contents(char* path, char** output, int* len TSRMLS_DC)
{
    php_stream* stream = php_stream_open_wrapper(path, "rb",
                         USE_PATH|REPORT_ERRORS|ENFORCE_SAFE_MODE, NULL);

    if (!stream) {
        zend_throw_exception_ex(cassandra_runtime_exception_ce, 0 TSRMLS_CC,
                                "The path '%s' doesn't exist or is not readable", path);
        return 0;
    }

    *len = php_stream_copy_to_mem(stream, output, PHP_STREAM_COPY_ALL, 0);

    php_stream_close(stream);
    return 1;
}

PHP_METHOD(SSLOptionsBuilder, build)
{
    cassandra_ssl* ssl = NULL;
    int   len;
    char* contents;
    CassError rc;

    cassandra_ssl_builder* builder =
示例#14
0
/* {{{ mysqlnd_sha256_get_rsa_key */
static RSA *
mysqlnd_sha256_get_rsa_key(MYSQLND_CONN_DATA * conn,
						   const MYSQLND_OPTIONS * const options,
						   const MYSQLND_NET_OPTIONS * const net_options
						  )
{
	RSA * ret = NULL;
	const char * fname = (net_options->sha256_server_public_key && net_options->sha256_server_public_key[0] != '\0')?
								net_options->sha256_server_public_key:
								MYSQLND_G(sha256_server_public_key);
	php_stream * stream;
	DBG_ENTER("mysqlnd_sha256_get_rsa_key");
	DBG_INF_FMT("options_s256_pk=[%s] MYSQLND_G(sha256_server_public_key)=[%s]",
				 net_options->sha256_server_public_key? net_options->sha256_server_public_key:"n/a",
				 MYSQLND_G(sha256_server_public_key)? MYSQLND_G(sha256_server_public_key):"n/a");
	if (!fname || fname[0] == '\0') {
		MYSQLND_PACKET_SHA256_PK_REQUEST * pk_req_packet = NULL;
		MYSQLND_PACKET_SHA256_PK_REQUEST_RESPONSE * pk_resp_packet = NULL;

		do {
			DBG_INF("requesting the public key from the server");
			pk_req_packet = conn->protocol->m.get_sha256_pk_request_packet(conn->protocol, FALSE);
			if (!pk_req_packet) {
				SET_OOM_ERROR(*conn->error_info);
				break;
			}
			pk_resp_packet = conn->protocol->m.get_sha256_pk_request_response_packet(conn->protocol, FALSE);
			if (!pk_resp_packet) {
				SET_OOM_ERROR(*conn->error_info);
				PACKET_FREE(pk_req_packet);
				break;
			}

			if (! PACKET_WRITE(pk_req_packet, conn)) {
				DBG_ERR_FMT("Error while sending public key request packet");
				php_error(E_WARNING, "Error while sending public key request packet. PID=%d", getpid());
				CONN_SET_STATE(conn, CONN_QUIT_SENT);
				break;
			}
			if (FAIL == PACKET_READ(pk_resp_packet, conn) || NULL == pk_resp_packet->public_key) {
				DBG_ERR_FMT("Error while receiving public key");
				php_error(E_WARNING, "Error while receiving public key. PID=%d", getpid());
				CONN_SET_STATE(conn, CONN_QUIT_SENT);
				break;
			}
			DBG_INF_FMT("Public key(%d):\n%s", pk_resp_packet->public_key_len, pk_resp_packet->public_key);
			/* now extract the public key */
			{
				BIO * bio = BIO_new_mem_buf(pk_resp_packet->public_key, pk_resp_packet->public_key_len);
				ret = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL);
				BIO_free(bio);
			}
		} while (0);
		PACKET_FREE(pk_req_packet);
		PACKET_FREE(pk_resp_packet);

		DBG_INF_FMT("ret=%p", ret);
		DBG_RETURN(ret);

		SET_CLIENT_ERROR(*conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE,
			"sha256_server_public_key is not set for the connection or as mysqlnd.sha256_server_public_key");
		DBG_ERR("server_public_key is not set");
		DBG_RETURN(NULL);
	} else {
		zend_string * key_str;
		DBG_INF_FMT("Key in a file. [%s]", fname);
		stream = php_stream_open_wrapper((char *) fname, "rb", REPORT_ERRORS, NULL);

		if (stream) {
			if ((key_str = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0)) != NULL) {
				BIO * bio = BIO_new_mem_buf(key_str->val, key_str->len);
				ret = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL);
				BIO_free(bio);
				DBG_INF("Successfully loaded");
				DBG_INF_FMT("Public key:%*.s", key_str->len, key_str->val);
				zend_string_release(key_str);
			}
			php_stream_free(stream, PHP_STREAM_FREE_CLOSE);
		}
	}
	DBG_RETURN(ret);
}
示例#15
0
*                                                                            *
*  Encrypt a plain text file and output a cipher file                        *
*                                                                            *
*****************************************************************************/

int encrypt_file(const char *inputfile, const char *outputfile, 
    const char *key TSRMLS_DC)
{
    php_stream *input_stream, *output_stream;
    php_stream_statbuf stat_ssb;
    int file_size, block_count, i;
    char input[8], output[8];
    char header[8];

    /* Open input file */
    input_stream = php_stream_open_wrapper(inputfile, "r",
        ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL);
    if (!input_stream) {
        php_printf("PHP Fatal error: Unable to open `%s'", inputfile);
        return -1;
    }

    /* Get input file size */
    if (php_stream_stat(input_stream, &stat_ssb)) {
        php_stream_pclose(input_stream);
        return -1;
    }

    file_size = stat_ssb.sb.st_size;
    if (file_size <= 0) {
        php_stream_pclose(input_stream);
        return -1;
示例#16
0
out_free_output_string:
    free_string(&output_string);
out:
    return;
}
/* }}} */

static int load_mm_file(const char *filepath, mmfile_t *dest TSRMLS_DC)
{
    int retval;
    off_t filesize;
    void *ptr;
    php_stream *src;
    php_stream_statbuf stat;

    src = php_stream_open_wrapper((char *) filepath, "rb", REPORT_ERRORS, NULL);
    if (!src)
        goto out;

    retval = php_stream_stat(src, &stat);
    if (retval < 0)
        goto out_stream_close;

    filesize = stat.sb.st_size;

    retval = xdl_init_mmfile(dest, filesize, XDL_MMF_ATOMIC);
    if (retval < 0)
        goto out_stream_close;

    ptr = xdl_mmfile_writeallocate(dest, (long) filesize);
    if (!ptr)
示例#17
0
文件: dba.c 项目: Jille/php-src
/* {{{ php_dba_open
 */
static void php_dba_open(INTERNAL_FUNCTION_PARAMETERS, int persistent)
{
	zval *args = NULL;
	int ac = ZEND_NUM_ARGS();
	dba_mode_t modenr;
	dba_info *info, *other;
	dba_handler *hptr;
	char *key = NULL, *error = NULL;
	int keylen = 0;
	int i;
	int lock_mode, lock_flag, lock_dbf = 0;
	char *file_mode;
	char mode[4], *pmode, *lock_file_mode = NULL;
	int persistent_flag = persistent ? STREAM_OPEN_PERSISTENT : 0;
	zend_string *opened_path = NULL;
	char *lock_name;

	if (ac < 2) {
		WRONG_PARAM_COUNT;
	}

	/* we pass additional args to the respective handler */
	args = safe_emalloc(ac, sizeof(zval), 0);
	if (zend_get_parameters_array_ex(ac, args) != SUCCESS) {
		efree(args);
		WRONG_PARAM_COUNT;
	}

	/* we only take string arguments */
	for (i = 0; i < ac; i++) {
		if (Z_TYPE(args[i]) != IS_STRING) {
			convert_to_string_ex(&args[i]);
		} else if (Z_REFCOUNTED(args[i])) {
			Z_ADDREF(args[i]);
		}
		keylen += Z_STRLEN(args[i]);
	}

	if (persistent) {
		zend_resource *le;

		/* calculate hash */
		key = safe_emalloc(keylen, 1, 1);
		key[keylen] = '\0';
		keylen = 0;

		for(i = 0; i < ac; i++) {
			memcpy(key+keylen, Z_STRVAL(args[i]), Z_STRLEN(args[i]));
			keylen += Z_STRLEN(args[i]);
		}

		/* try to find if we already have this link in our persistent list */
		if ((le = zend_hash_str_find_ptr(&EG(persistent_list), key, keylen)) != NULL) {
			FREENOW;

			if (le->type != le_pdb) {
				RETURN_FALSE;
			}

			info = (dba_info *)le->ptr;

			GC_REFCOUNT(le)++;
			RETURN_RES(le);
			return;
		}
	}

	if (ac==2) {
		hptr = DBA_G(default_hptr);
		if (!hptr) {
			php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "No default handler selected");
			FREENOW;
			RETURN_FALSE;
		}
	} else {
		for (hptr = handler; hptr->name && strcasecmp(hptr->name, Z_STRVAL(args[2])); hptr++);
	}

	if (!hptr->name) {
		php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "No such handler: %s", Z_STRVAL(args[2]));
		FREENOW;
		RETURN_FALSE;
	}

	/* Check mode: [rwnc][fl]?t?
	 * r: Read
	 * w: Write
	 * n: Create/Truncate
	 * c: Create
	 *
	 * d: force lock on database file
	 * l: force lock on lck file
	 * -: ignore locking
	 *
	 * t: test open database, warning if locked
	 */
	strlcpy(mode, Z_STRVAL(args[1]), sizeof(mode));
	pmode = &mode[0];
	if (pmode[0] && (pmode[1]=='d' || pmode[1]=='l' || pmode[1]=='-')) { /* force lock on db file or lck file or disable locking */
		switch (pmode[1]) {
		case 'd':
			lock_dbf = 1;
			if ((hptr->flags & DBA_LOCK_ALL) == 0) {
				lock_flag = (hptr->flags & DBA_LOCK_ALL);
				break;
			}
			/* no break */
		case 'l':
			lock_flag = DBA_LOCK_ALL;
			if ((hptr->flags & DBA_LOCK_ALL) == 0) {
				php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_NOTICE, "Handler %s does locking internally", hptr->name);
			}
			break;
		default:
		case '-':
			if ((hptr->flags & DBA_LOCK_ALL) == 0) {
				php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Locking cannot be disabled for handler %s", hptr->name);
				FREENOW;
				RETURN_FALSE;
			}
			lock_flag = 0;
			break;
		}
	} else {
		lock_flag = (hptr->flags&DBA_LOCK_ALL);
		lock_dbf = 1;
	}
	switch (*pmode++) {
		case 'r':
			modenr = DBA_READER;
			lock_mode = (lock_flag & DBA_LOCK_READER) ? LOCK_SH : 0;
			file_mode = "r";
			break;
		case 'w':
			modenr = DBA_WRITER;
			lock_mode = (lock_flag & DBA_LOCK_WRITER) ? LOCK_EX : 0;
			file_mode = "r+b";
			break;
		case 'c':
			modenr = DBA_CREAT;
			lock_mode = (lock_flag & DBA_LOCK_CREAT) ? LOCK_EX : 0;
			if (lock_mode) {
				if (lock_dbf) {
					/* the create/append check will be done on the lock
					 * when the lib opens the file it is already created
					 */
					file_mode = "r+b";       /* read & write, seek 0 */
					lock_file_mode = "a+b";  /* append */
				} else {
					file_mode = "a+b";       /* append */
					lock_file_mode = "w+b";  /* create/truncate */
				}
			} else {
				file_mode = "a+b";
			}
			/* In case of the 'a+b' append mode, the handler is responsible
			 * to handle any rewind problems (see flatfile handler).
			 */
			break;
		case 'n':
			modenr = DBA_TRUNC;
			lock_mode = (lock_flag & DBA_LOCK_TRUNC) ? LOCK_EX : 0;
			file_mode = "w+b";
			break;
		default:
			php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Illegal DBA mode");
			FREENOW;
			RETURN_FALSE;
	}
	if (!lock_file_mode) {
		lock_file_mode = file_mode;
	}
	if (*pmode=='d' || *pmode=='l' || *pmode=='-') {
		pmode++; /* done already - skip here */
	}
	if (*pmode=='t') {
		pmode++;
		if (!lock_flag) {
			php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "You cannot combine modifiers - (no lock) and t (test lock)");
			FREENOW;
			RETURN_FALSE;
		}
		if (!lock_mode) {
			if ((hptr->flags & DBA_LOCK_ALL) == 0) {
				php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Handler %s uses its own locking which doesn't support mode modifier t (test lock)", hptr->name);
				FREENOW;
				RETURN_FALSE;
			} else {
				php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Handler %s doesn't uses locking for this mode which makes modifier t (test lock) obsolete", hptr->name);
				FREENOW;
				RETURN_FALSE;
			}
		} else {
			lock_mode |= LOCK_NB; /* test =: non blocking */
		}
	}
	if (*pmode) {
		php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Illegal DBA mode");
		FREENOW;
		RETURN_FALSE;
	}

	info = pemalloc(sizeof(dba_info), persistent);
	memset(info, 0, sizeof(dba_info));
	info->path = pestrdup(Z_STRVAL(args[0]), persistent);
	info->mode = modenr;
	info->argc = ac - 3;
	info->argv = args + 3;
	info->flags = (hptr->flags & ~DBA_LOCK_ALL) | (lock_flag & DBA_LOCK_ALL) | (persistent ? DBA_PERSISTENT : 0);
	info->lock.mode = lock_mode;

	/* if any open call is a locking call:
	 * check if we already habe a locking call open that should block this call
	 * the problem is some systems would allow read during write
	 */
	if (hptr->flags & DBA_LOCK_ALL) {
		if ((other = php_dba_find(info->path)) != NULL) {
			if (   ( (lock_mode&LOCK_EX)        && (other->lock.mode&(LOCK_EX|LOCK_SH)) )
			    || ( (other->lock.mode&LOCK_EX) && (lock_mode&(LOCK_EX|LOCK_SH))        )
			   ) {
				error = "Unable to establish lock (database file already open)"; /* force failure exit */
			}
		}
	}

	if (!error && lock_mode) {
		if (lock_dbf) {
			lock_name = Z_STRVAL(args[0]);
		} else {
			spprintf(&lock_name, 0, "%s.lck", info->path);
			if (!strcmp(file_mode, "r")) {
				/* when in read only mode try to use existing .lck file first */
				/* do not log errors for .lck file while in read ony mode on .lck file */
				lock_file_mode = "rb";
				info->lock.fp = php_stream_open_wrapper(lock_name, lock_file_mode, STREAM_MUST_SEEK|IGNORE_PATH|persistent_flag, &opened_path);
			}
			if (!info->lock.fp) {
				/* when not in read mode or failed to open .lck file read only. now try again in create(write) mode and log errors */
				lock_file_mode = "a+b";
			} else {
				if (opened_path) {
					info->lock.name = pestrndup(opened_path->val, opened_path->len, persistent);
					zend_string_release(opened_path);
				}
			}
		}
		if (!info->lock.fp) {
			info->lock.fp = php_stream_open_wrapper(lock_name, lock_file_mode, STREAM_MUST_SEEK|REPORT_ERRORS|IGNORE_PATH|persistent_flag, &opened_path);
			if (info->lock.fp) {
				if (lock_dbf) {
					/* replace the path info with the real path of the opened file */
					pefree(info->path, persistent);
					info->path = pestrndup(opened_path->val, opened_path->len, persistent);
				}
				/* now store the name of the lock */
				info->lock.name = pestrndup(opened_path->val, opened_path->len, persistent);
				zend_string_release(opened_path);
			}
		}
		if (!lock_dbf) {
			efree(lock_name);
		}
		if (!info->lock.fp) {
			dba_close(info);
			/* stream operation already wrote an error message */
			FREENOW;
			RETURN_FALSE;
		}
		if (!php_stream_supports_lock(info->lock.fp)) {
			error = "Stream does not support locking";
		}
		if (php_stream_lock(info->lock.fp, lock_mode)) {
			error = "Unable to establish lock"; /* force failure exit */
		}
	}

	/* centralised open stream for builtin */
	if (!error && (hptr->flags&DBA_STREAM_OPEN)==DBA_STREAM_OPEN) {
		if (info->lock.fp && lock_dbf) {
			info->fp = info->lock.fp; /* use the same stream for locking and database access */
		} else {
			info->fp = php_stream_open_wrapper(info->path, file_mode, STREAM_MUST_SEEK|REPORT_ERRORS|IGNORE_PATH|persistent_flag, NULL);
		}
		if (!info->fp) {
			dba_close(info);
			/* stream operation already wrote an error message */
			FREENOW;
			RETURN_FALSE;
		}
		if (hptr->flags & (DBA_NO_APPEND|DBA_CAST_AS_FD)) {
			/* Needed because some systems do not allow to write to the original
			 * file contents with O_APPEND being set.
			 */
			if (SUCCESS != php_stream_cast(info->fp, PHP_STREAM_AS_FD, (void*)&info->fd, 1)) {
				php_error_docref(NULL, E_WARNING, "Could not cast stream");
				dba_close(info);
				FREENOW;
				RETURN_FALSE;
#ifdef F_SETFL
			} else if (modenr == DBA_CREAT) {
				int flags = fcntl(info->fd, F_SETFL);
				fcntl(info->fd, F_SETFL, flags & ~O_APPEND);
#endif
			}

		}
	}

	if (error || hptr->open(info, &error) != SUCCESS) {
		dba_close(info);
		php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Driver initialization failed for handler: %s%s%s", hptr->name, error?": ":"", error?error:"");
		FREENOW;
		RETURN_FALSE;
	}

	info->hnd = hptr;
	info->argc = 0;
	info->argv = NULL;

	if (persistent) {
		zend_resource new_le;

		new_le.type = le_pdb;
		new_le.ptr = info;
		if (zend_hash_str_update_mem(&EG(persistent_list), key, keylen, &new_le, sizeof(zend_resource)) == NULL) {
			dba_close(info);
			php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Could not register persistent resource");
			FREENOW;
			RETURN_FALSE;
		}
	}

	RETVAL_RES(zend_register_resource(info, (persistent ? le_pdb : le_db)));
	FREENOW;
}
示例#18
0
    
	php_stream *stream;
	php_stream_statbuf ssbuf;
	zend_bool owned_stream = 0;

	PHP_CAIRO_ERROR_HANDLING(FALSE)
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l",
				&stream_zval, &load_flags) == FAILURE)
	{
		PHP_CAIRO_RESTORE_ERRORS(FALSE)
		return;
	}
	PHP_CAIRO_RESTORE_ERRORS(FALSE)

	if(Z_TYPE_P(stream_zval) == IS_STRING) {
		stream = php_stream_open_wrapper(Z_STRVAL_P(stream_zval), "rb", REPORT_ERRORS|ENFORCE_SAFE_MODE, NULL);
		owned_stream = 1;
	} else if(Z_TYPE_P(stream_zval) == IS_RESOURCE)  {
		php_stream_from_zval(stream, &stream_zval);	
	} else {
		zend_error(E_WARNING, "cairo_ft_font_face_create expects parameter 1 to be a string or a stream resource");
		RETURN_NULL();
	}

	if(!stream) {
		RETURN_NULL();
	}

	if(php_stream_stat(stream, &ssbuf) != 0) {
		if(owned_stream) {
			php_stream_close(stream);
示例#19
0
文件: xdiff.c 项目: a-tze/php5-xdiff
out_free_output_string:
	free_string(&output_string);
out:
	return;
}
/* }}} */

static int load_mm_file(const char *filepath, mmfile_t *dest TSRMLS_DC)
{
	int retval;
	off_t filesize;
	void *ptr;
	php_stream *src;
	php_stream_statbuf stat;

	src = php_stream_open_wrapper((char *) filepath, "rb", REPORT_ERRORS | ENFORCE_SAFE_MODE, NULL);
	if (!src)
		goto out;

	retval = php_stream_stat(src, &stat);
	if (retval < 0)
		goto out_stream_close;

	filesize = stat.sb.st_size;

	retval = xdl_init_mmfile(dest, filesize, XDL_MMF_ATOMIC);
	if (retval < 0)
		goto out_stream_close;

	ptr = xdl_mmfile_writeallocate(dest, (long) filesize);
	if (!ptr)
示例#20
0
/* {{{ mysqlnd_sha256_get_rsa_key */
static RSA *
mysqlnd_sha256_get_rsa_key(MYSQLND_CONN_DATA * conn,
						   const MYSQLND_SESSION_OPTIONS * const session_options,
						   const MYSQLND_PFC_DATA * const pfc_data
						  )
{
	RSA * ret = NULL;
	const char * fname = (pfc_data->sha256_server_public_key && pfc_data->sha256_server_public_key[0] != '\0')?
								pfc_data->sha256_server_public_key:
								MYSQLND_G(sha256_server_public_key);
	php_stream * stream;
	DBG_ENTER("mysqlnd_sha256_get_rsa_key");
	DBG_INF_FMT("options_s256_pk=[%s] MYSQLND_G(sha256_server_public_key)=[%s]",
				 pfc_data->sha256_server_public_key? pfc_data->sha256_server_public_key:"n/a",
				 MYSQLND_G(sha256_server_public_key)? MYSQLND_G(sha256_server_public_key):"n/a");
	if (!fname || fname[0] == '\0') {
		MYSQLND_PACKET_SHA256_PK_REQUEST pk_req_packet;
		MYSQLND_PACKET_SHA256_PK_REQUEST_RESPONSE pk_resp_packet;

		do {
			DBG_INF("requesting the public key from the server");
			conn->payload_decoder_factory->m.init_sha256_pk_request_packet(&pk_req_packet);
			conn->payload_decoder_factory->m.init_sha256_pk_request_response_packet(&pk_resp_packet);

			if (! PACKET_WRITE(conn, &pk_req_packet)) {
				DBG_ERR_FMT("Error while sending public key request packet");
				php_error(E_WARNING, "Error while sending public key request packet. PID=%d", getpid());
				SET_CONNECTION_STATE(&conn->state, CONN_QUIT_SENT);
				break;
			}
			if (FAIL == PACKET_READ(conn, &pk_resp_packet) || NULL == pk_resp_packet.public_key) {
				DBG_ERR_FMT("Error while receiving public key");
				php_error(E_WARNING, "Error while receiving public key. PID=%d", getpid());
				SET_CONNECTION_STATE(&conn->state, CONN_QUIT_SENT);
				break;
			}
			DBG_INF_FMT("Public key(%d):\n%s", pk_resp_packet.public_key_len, pk_resp_packet.public_key);
			/* now extract the public key */
			{
				BIO * bio = BIO_new_mem_buf(pk_resp_packet.public_key, pk_resp_packet.public_key_len);
				ret = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL);
				BIO_free(bio);
			}
		} while (0);
		PACKET_FREE(&pk_req_packet);
		PACKET_FREE(&pk_resp_packet);

		DBG_INF_FMT("ret=%p", ret);
		DBG_RETURN(ret);

		SET_CLIENT_ERROR(conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE,
			"sha256_server_public_key is not set for the connection or as mysqlnd.sha256_server_public_key");
		DBG_ERR("server_public_key is not set");
		DBG_RETURN(NULL);
	} else {
		zend_string * key_str;
		DBG_INF_FMT("Key in a file. [%s]", fname);
		stream = php_stream_open_wrapper((char *) fname, "rb", REPORT_ERRORS, NULL);

		if (stream) {
			if ((key_str = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0)) != NULL) {
				BIO * bio = BIO_new_mem_buf(ZSTR_VAL(key_str), ZSTR_LEN(key_str));
				ret = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL);
				BIO_free(bio);
				DBG_INF("Successfully loaded");
				DBG_INF_FMT("Public key:%*.s", ZSTR_LEN(key_str), ZSTR_VAL(key_str));
				zend_string_release(key_str);
			}
			php_stream_close(stream);
		}
	}
	DBG_RETURN(ret);
}
示例#21
0
/* {{{ _php_image_output_ctx */
static void _php_image_output_ctx(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, void (*func_p)())
{
	zval *imgind;
	char *file = NULL;
	size_t file_len = 0;
	zend_long quality, basefilter;
	zend_bool compressed = 1;
	gdImagePtr im;
	int argc = ZEND_NUM_ARGS();
	int q = -1, i;
	int f = -1;
	gdIOCtx *ctx = NULL;
	zval *to_zval = NULL;
	php_stream *stream;
	int close_stream = 1;

	/* The third (quality) parameter for Wbmp stands for the foreground when called from image2wbmp().
	 * The third (quality) parameter for Wbmp and Xbm stands for the foreground color index when called
	 * from imagey<type>().
	 */
	switch (image_type) {
		case PHP_GDIMG_TYPE_XBM:
			if (zend_parse_parameters(argc, "rp!|ll", &imgind, &file, &file_len, &quality, &basefilter) == FAILURE) {
				return;
			}
			break;
		case PHP_GDIMG_TYPE_BMP:
			if (zend_parse_parameters(argc, "r|z!b", &imgind, &to_zval, &compressed) == FAILURE) {
				return;
			}
			break;
		default:
			/* PHP_GDIMG_TYPE_GIF
			 * PHP_GDIMG_TYPE_PNG
			 * PHP_GDIMG_TYPE_JPG
			 * PHP_GDIMG_TYPE_WBM
			 * PHP_GDIMG_TYPE_WEBP
			 * */
			if (zend_parse_parameters(argc, "r|z!ll", &imgind, &to_zval, &quality, &basefilter) == FAILURE) {
				return;
			}
	}

	if ((im = (gdImagePtr)zend_fetch_resource(Z_RES_P(imgind), "Image", phpi_get_le_gd())) == NULL) {
		RETURN_FALSE;
	}

	if (image_type != PHP_GDIMG_TYPE_BMP && argc >= 3) {
		q = quality; /* or colorindex for foreground of BW images (defaults to black) */
		if (argc == 4) {
			f = basefilter;
		}
	}

	if (argc > 1 && to_zval != NULL) {
		if (Z_TYPE_P(to_zval) == IS_RESOURCE) {
			php_stream_from_zval_no_verify(stream, to_zval);
			if (stream == NULL) {
				RETURN_FALSE;
			}
			close_stream = 0;
		} else if (Z_TYPE_P(to_zval) == IS_STRING) {
			if (CHECK_ZVAL_NULL_PATH(to_zval)) {
				php_error_docref(NULL, E_WARNING, "Invalid 2nd parameter, filename must not contain null bytes");
				RETURN_FALSE;
			}

			stream = php_stream_open_wrapper(Z_STRVAL_P(to_zval), "wb", REPORT_ERRORS|IGNORE_PATH|IGNORE_URL_WIN, NULL);
			if (stream == NULL) {
				RETURN_FALSE;
			}
		} else {
			php_error_docref(NULL, E_WARNING, "Invalid 2nd parameter, it must a filename or a stream");
			RETURN_FALSE;
		}
	} else if (argc > 1 && file != NULL) {
		stream = php_stream_open_wrapper(file, "wb", REPORT_ERRORS|IGNORE_PATH|IGNORE_URL_WIN, NULL);
		if (stream == NULL) {
			RETURN_FALSE;
		}
	} else {
		ctx = ecalloc(1, sizeof(gdIOCtx));
		ctx->putC = _php_image_output_putc;
		ctx->putBuf = _php_image_output_putbuf;
		ctx->gd_free = _php_image_output_ctxfree;
	}

	if (!ctx)	{
		ctx = ecalloc(1, sizeof(gdIOCtx));
		ctx->putC = _php_image_stream_putc;
		ctx->putBuf = _php_image_stream_putbuf;
		if (close_stream) {
			ctx->gd_free = _php_image_stream_ctxfreeandclose;
		} else {
			ctx->gd_free = _php_image_stream_ctxfree;
		}
		ctx->data = (void *)stream;
	}

	switch(image_type) {
		case PHP_GDIMG_CONVERT_WBM:
			if(q<0||q>255) {
				php_error_docref(NULL, E_WARNING, "Invalid threshold value '%d'. It must be between 0 and 255", q);
			}
		case PHP_GDIMG_TYPE_JPG:
			(*func_p)(im, ctx, q);
			break;
		case PHP_GDIMG_TYPE_WEBP:
			if (q == -1) {
				q = 80;
			}
			(*func_p)(im, ctx, q);
			break;
		case PHP_GDIMG_TYPE_PNG:
			(*func_p)(im, ctx, q, f);
			break;
		case PHP_GDIMG_TYPE_XBM:
		case PHP_GDIMG_TYPE_WBM:
			if (argc < 3) {
				for(i=0; i < gdImageColorsTotal(im); i++) {
					if(!gdImageRed(im, i) && !gdImageGreen(im, i) && !gdImageBlue(im, i)) break;
				}
				q = i;
			}
			if (image_type == PHP_GDIMG_TYPE_XBM) {
				(*func_p)(im, file ? file : "", q, ctx);
			} else {
				(*func_p)(im, q, ctx);
			}
			break;
		case PHP_GDIMG_TYPE_BMP:
			(*func_p)(im, ctx, (int) compressed);
			break;
		default:
			(*func_p)(im, ctx);
			break;
	}

	ctx->gd_free(ctx);

	RETURN_TRUE;
}