Exemplo n.º 1
0
/* {{{ Gets absolute filename of the file.
	   Returns null if format is virtual 
	   Filename can be passed with or without format indicator */
char *php_imagick_get_absolute_filename(char *filename, int filename_len TSRMLS_DC)
{
	int chr_pos = php_imagick_format_indicator(filename, filename_len TSRMLS_CC);

	if (chr_pos == -1) {
		/* There was no recognised format in the filename, try to access as is */
		return expand_filepath(filename, NULL TSRMLS_CC);
	}
	
	/* the was a format but is it virtual?? */
	if (php_imagick_is_virtual_format(filename, filename_len TSRMLS_CC)) {
		/* virtual format has no filename */
		return NULL;
	}
	
	return expand_filepath(filename + chr_pos + 1, NULL TSRMLS_CC);
}
Exemplo n.º 2
0
static char *make_filename_safe(const char *filename)
{
	if (*filename && memcmp(filename, ":memory:", sizeof(":memory:"))) {
		char *fullpath = expand_filepath(filename, NULL);

		if (!fullpath) {
			return NULL;
		}

		if (php_check_open_basedir(fullpath)) {
			efree(fullpath);
			return NULL;
		}
		return fullpath;
	}
	return estrdup(filename);
}
Exemplo n.º 3
0
/* {{{ proto bool GmagickDraw::setFont(string font_name)
	Sets the fully-sepecified font to use when annotating with text.
*/
PHP_METHOD(gmagickdraw, setfont)
{
	php_gmagickdraw_object *internd;
	char *font, *absolute;
	int font_len, error = 0;

	/* Parse parameters given to function */
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &font, &font_len) == FAILURE) {
		return;
	}

	/* Check that no empty string is passed */
	if (font_len == 0) {
		GMAGICK_THROW_EXCEPTION_WITH_MESSAGE(GMAGICKDRAW_CLASS, "Can not set empty font", 2);
	}

	internd = (php_gmagickdraw_object *)zend_object_store_get_object(getThis() TSRMLS_CC);

	/* And if it wasn't */
	if (!check_configured_font(font, font_len TSRMLS_CC)) {

		if (!(absolute = expand_filepath(font, NULL TSRMLS_CC))) {
			GMAGICK_THROW_EXCEPTION_WITH_MESSAGE(GMAGICKDRAW_CLASS, "Unable to set font", 2);
		}

		/* Do a safe-mode check for the font */
		GMAGICK_SAFE_MODE_CHECK(absolute, error);
		GMAGICKDRAW_CHECK_READ_OR_WRITE_ERROR(internd, absolute, error, GMAGICK_FREE_FILENAME);

		if (VCWD_ACCESS(absolute, F_OK|R_OK)) {
			zend_throw_exception_ex(php_gmagickdraw_exception_class_entry, 2 TSRMLS_CC,
				"The given font is not found in the GraphicsMagick configuration and the file (%s) is not accessible", absolute);

			efree(absolute);
			return;
		}

		DrawSetFont(internd->drawing_wand, absolute);
		efree(absolute);

	} else {
		DrawSetFont(internd->drawing_wand, font);
	}

	GMAGICK_CHAIN_METHOD;
}
Exemplo n.º 4
0
/* _xmlreader_get_valid_file_path and _xmlreader_get_relaxNG should be made a
	common function in libxml extension as code is common to a few xml extensions */
char *_xmlreader_get_valid_file_path(char *source, char *resolved_path, int resolved_path_len ) {
	xmlURI *uri;
	xmlChar *escsource;
	char *file_dest;
	int isFileUri = 0;

	uri = xmlCreateURI();
	escsource = xmlURIEscapeStr((xmlChar *)source, (xmlChar *)":");
	xmlParseURIReference(uri, (const char *)escsource);
	xmlFree(escsource);

	if (uri->scheme != NULL) {
		/* absolute file uris - libxml only supports localhost or empty host */
		if (strncasecmp(source, "file:///",8) == 0) {
			isFileUri = 1;
#ifdef PHP_WIN32
			source += 8;
#else
			source += 7;
#endif
		} else if (strncasecmp(source, "file://localhost/",17) == 0) {
			isFileUri = 1;
#ifdef PHP_WIN32
			source += 17;
#else
			source += 16;
#endif
		}
	}

	file_dest = source;

	if ((uri->scheme == NULL || isFileUri)) {
		if (!VCWD_REALPATH(source, resolved_path) && !expand_filepath(source, resolved_path)) {
			xmlFreeURI(uri);
			return NULL;
		}
		file_dest = resolved_path;
	}

	xmlFreeURI(uri);

	return file_dest;
}
Exemplo n.º 5
0
static php_vedis_t *
php_vedis_new(char *storage, int storage_len, zend_bool is_persistent TSRMLS_DC)
{
    php_vedis_t *vedis;
    char *filepath = NULL, *stragepath = NULL;

    vedis = pecalloc(1, sizeof(php_vedis_t), is_persistent);

    if (!storage || storage_len <= 0) {
        stragepath = NULL;
    } else if (strcmp(storage, ":mem:") != 0) {
        if (!(filepath = expand_filepath(storage, NULL TSRMLS_CC))) {
            pefree(vedis, is_persistent);
            return NULL;
        }
        stragepath = filepath;
    } else {
        stragepath = storage;
    }

    if (vedis_open(&(vedis->store), stragepath) != VEDIS_OK) {
        if (filepath) {
            efree(filepath);
        }
        pefree(vedis, is_persistent);
        return NULL;
    }

    if (filepath) {
        efree(filepath);
    }

    vedis->storage = storage;
    vedis->is_persistent = is_persistent;
    vedis->pid = getpid();

    return vedis;
}
void zend_accel_blacklist_load(zend_blacklist *blacklist, char *filename)
{
	char buf[MAXPATHLEN+1], real_path[MAXPATHLEN+1];
	FILE *fp;
	int path_length;
	TSRMLS_FETCH();

	if ((fp=fopen(filename, "r"))==NULL) {
		zend_accel_error(ACCEL_LOG_WARNING, "Cannot load blacklist file: %s\n", filename);
		return;
	}

	zend_accel_error(ACCEL_LOG_DEBUG,"Loading blacklist file:  '%s'", filename);

	memset(buf, 0, sizeof(buf));
	memset(real_path, 0, sizeof(real_path));

	while (fgets(buf, MAXPATHLEN, fp)!=NULL) {
		char *path_dup, *pbuf;
		path_length = strlen(buf);
		if (path_length > 0 && buf[path_length-1]=='\n') {
			buf[--path_length] = 0;
			if (path_length > 0 && buf[path_length-1]=='\r') {
				buf[--path_length] = 0;
			}
		}

		/* Strip ctrl-m prefix */
		pbuf = &buf[0];
		while(*pbuf == '\r') {
			*pbuf++ = 0;
			path_length--;
		}

		/* strip \" */
		if( pbuf[0] == '\"' && pbuf[path_length-1]== '\"' ){
			*pbuf++ = 0;
			path_length-=2;
		}

		if (path_length==0) {
			continue;
		}

		path_dup = zend_strndup(pbuf, path_length);
		expand_filepath(path_dup, real_path TSRMLS_CC);
		path_length = strlen(real_path);

		free(path_dup);

		zend_accel_blacklist_allocate(blacklist);
		blacklist->entries[blacklist->pos].path_length = path_length;
		blacklist->entries[blacklist->pos].path = (char *) malloc(path_length+1);
		if (!blacklist->entries[blacklist->pos].path) {
			zend_accel_error(ACCEL_LOG_ERROR, "malloc() failed\n");
			return;
		}
		blacklist->entries[blacklist->pos].id = blacklist->pos;
		memcpy(blacklist->entries[blacklist->pos].path, real_path, path_length+1);
		blacklist->pos++;
	}
	fclose(fp);
	zend_accel_blacklist_update_regexp(blacklist);
}
Exemplo n.º 7
0
/* {{{ php_check_specific_open_basedir
	When open_basedir is not NULL, check if the given filename is located in
	open_basedir. Returns -1 if error or not in the open_basedir, else 0.
	When open_basedir is NULL, always return 0.
*/
PHPAPI int php_check_specific_open_basedir(const char *basedir, const char *path)
{
	char resolved_name[MAXPATHLEN];
	char resolved_basedir[MAXPATHLEN];
	char local_open_basedir[MAXPATHLEN];
	char path_tmp[MAXPATHLEN];
	char *path_file;
	int resolved_basedir_len;
	int resolved_name_len;
	int path_len;
	int nesting_level = 0;

	/* Special case basedir==".": Use script-directory */
	if (strcmp(basedir, ".") || !VCWD_GETCWD(local_open_basedir, MAXPATHLEN)) {
		/* Else use the unmodified path */
		strlcpy(local_open_basedir, basedir, sizeof(local_open_basedir));
	}

	path_len = (int)strlen(path);
	if (path_len > (MAXPATHLEN - 1)) {
		/* empty and too long paths are invalid */
		return -1;
	}

	/* normalize and expand path */
	if (expand_filepath(path, resolved_name) == NULL) {
		return -1;
	}

	path_len = (int)strlen(resolved_name);
	memcpy(path_tmp, resolved_name, path_len + 1); /* safe */

	while (VCWD_REALPATH(path_tmp, resolved_name) == NULL) {
#if defined(PHP_WIN32) || defined(HAVE_SYMLINK)
#if defined(PHP_WIN32)
		if (EG(windows_version_info).dwMajorVersion > 5) {
#endif
			if (nesting_level == 0) {
				int ret;
				char buf[MAXPATHLEN];

				ret = php_sys_readlink(path_tmp, buf, MAXPATHLEN - 1);
				if (ret < 0) {
					/* not a broken symlink, move along.. */
				} else {
					/* put the real path into the path buffer */
					memcpy(path_tmp, buf, ret);
					path_tmp[ret] = '\0';
				}
			}
#if defined(PHP_WIN32)
		}
#endif
#endif

#if defined(PHP_WIN32) || defined(NETWARE)
		path_file = strrchr(path_tmp, DEFAULT_SLASH);
		if (!path_file) {
			path_file = strrchr(path_tmp, '/');
		}
#else
		path_file = strrchr(path_tmp, DEFAULT_SLASH);
#endif
		if (!path_file) {
			/* none of the path components exist. definitely not in open_basedir.. */
			return -1;
		} else {
			path_len = path_file - path_tmp + 1;
#if defined(PHP_WIN32) || defined(NETWARE)
			if (path_len > 1 && path_tmp[path_len - 2] == ':') {
				if (path_len != 3) {
					return -1;
				}
				/* this is c:\ */
				path_tmp[path_len] = '\0';
			} else {
				path_tmp[path_len - 1] = '\0';
			}
#else
			path_tmp[path_len - 1] = '\0';
#endif
		}
		nesting_level++;
	}

	/* Resolve open_basedir to resolved_basedir */
	if (expand_filepath(local_open_basedir, resolved_basedir) != NULL) {
		int basedir_len = (int)strlen(basedir);
		/* Handler for basedirs that end with a / */
		resolved_basedir_len = (int)strlen(resolved_basedir);
#if defined(PHP_WIN32) || defined(NETWARE)
		if (basedir[basedir_len - 1] == PHP_DIR_SEPARATOR || basedir[basedir_len - 1] == '/') {
#else
		if (basedir[basedir_len - 1] == PHP_DIR_SEPARATOR) {
#endif
			if (resolved_basedir[resolved_basedir_len - 1] != PHP_DIR_SEPARATOR) {
				resolved_basedir[resolved_basedir_len] = PHP_DIR_SEPARATOR;
				resolved_basedir[++resolved_basedir_len] = '\0';
			}
		} else {
				resolved_basedir[resolved_basedir_len++] = PHP_DIR_SEPARATOR;
				resolved_basedir[resolved_basedir_len] = '\0';
		}

		resolved_name_len = (int)strlen(resolved_name);
		if (path_tmp[path_len - 1] == PHP_DIR_SEPARATOR) {
			if (resolved_name[resolved_name_len - 1] != PHP_DIR_SEPARATOR) {
				resolved_name[resolved_name_len] = PHP_DIR_SEPARATOR;
				resolved_name[++resolved_name_len] = '\0';
			}
		}

		/* Check the path */
#if defined(PHP_WIN32) || defined(NETWARE)
		if (strncasecmp(resolved_basedir, resolved_name, resolved_basedir_len) == 0) {
#else
		if (strncmp(resolved_basedir, resolved_name, resolved_basedir_len) == 0) {
#endif
			if (resolved_name_len > resolved_basedir_len &&
				resolved_name[resolved_basedir_len - 1] != PHP_DIR_SEPARATOR) {
				return -1;
			} else {
				/* File is in the right directory */
				return 0;
			}
		} else {
			/* /openbasedir/ and /openbasedir are the same directory */
			if (resolved_basedir_len == (resolved_name_len + 1) && resolved_basedir[resolved_basedir_len - 1] == PHP_DIR_SEPARATOR) {
#if defined(PHP_WIN32) || defined(NETWARE)
				if (strncasecmp(resolved_basedir, resolved_name, resolved_name_len) == 0) {
#else
				if (strncmp(resolved_basedir, resolved_name, resolved_name_len) == 0) {
#endif
					return 0;
				}
			}
			return -1;
		}
	} else {
		/* Unable to resolve the real path, return -1 */
		return -1;
	}
}
/* }}} */

PHPAPI int php_check_open_basedir(const char *path)
{
	return php_check_open_basedir_ex(path, 1);
}

/* {{{ php_check_open_basedir
 */
PHPAPI int php_check_open_basedir_ex(const char *path, int warn)
{
	/* Only check when open_basedir is available */
	if (PG(open_basedir) && *PG(open_basedir)) {
		char *pathbuf;
		char *ptr;
		char *end;

		/* Check if the path is too long so we can give a more useful error
		* message. */
		if (strlen(path) > (MAXPATHLEN - 1)) {
			php_error_docref(NULL, E_WARNING, "File name is longer than the maximum allowed path length on this platform (%d): %s", MAXPATHLEN, path);
			errno = EINVAL;
			return -1;
		}

		pathbuf = estrdup(PG(open_basedir));

		ptr = pathbuf;

		while (ptr && *ptr) {
			end = strchr(ptr, DEFAULT_DIR_SEPARATOR);
			if (end != NULL) {
				*end = '\0';
				end++;
			}

			if (php_check_specific_open_basedir(ptr, path) == 0) {
				efree(pathbuf);
				return 0;
			}

			ptr = end;
		}
		if (warn) {
			php_error_docref(NULL, E_WARNING, "open_basedir restriction in effect. File(%s) is not within the allowed path(s): (%s)", path, PG(open_basedir));
		}
		efree(pathbuf);
		errno = EPERM; /* we deny permission to open it */
		return -1;
	}

	/* Nothing to check... */
	return 0;
}
/* }}} */

/* {{{ php_fopen_and_set_opened_path
 */
static FILE *php_fopen_and_set_opened_path(const char *path, const char *mode, zend_string **opened_path)
{
	FILE *fp;

	if (php_check_open_basedir((char *)path)) {
		return NULL;
	}
	fp = VCWD_FOPEN(path, mode);
	if (fp && opened_path) {
		//TODO :avoid reallocation
		char *tmp = expand_filepath_with_mode(path, NULL, NULL, 0, CWD_EXPAND);
		if (tmp) {
			*opened_path = zend_string_init(tmp, strlen(tmp), 0);
			efree(tmp);
		}
	}
	return fp;
}
Exemplo n.º 8
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;
}
Exemplo n.º 9
0
/* {{{ php_init_config
 */
int php_init_config(void)
{
	char *php_ini_file_name = NULL;
	char *php_ini_search_path = NULL;
	int php_ini_scanned_path_len;
	char *open_basedir;
	int free_ini_search_path = 0;
	zend_file_handle fh;

	zend_hash_init(&configuration_hash, 8, NULL, config_zval_dtor, 1);

	if (sapi_module.ini_defaults) {
		sapi_module.ini_defaults(&configuration_hash);
	}

	zend_llist_init(&extension_lists.engine, sizeof(char *), (llist_dtor_func_t) free_estring, 1);
	zend_llist_init(&extension_lists.functions, sizeof(char *), (llist_dtor_func_t) free_estring, 1);

	open_basedir = PG(open_basedir);

	if (sapi_module.php_ini_path_override) {
		php_ini_file_name = sapi_module.php_ini_path_override;
		php_ini_search_path = sapi_module.php_ini_path_override;
		free_ini_search_path = 0;
	} else if (!sapi_module.php_ini_ignore) {
		int search_path_size;
		char *default_location;
		char *env_location;
		static const char paths_separator[] = { ZEND_PATHS_SEPARATOR, 0 };
#ifdef PHP_WIN32
		char *reg_location;
		char phprc_path[MAXPATHLEN];
#endif

		env_location = getenv("PHPRC");

#ifdef PHP_WIN32
		if (!env_location) {
			char dummybuf;
			int size;

			SetLastError(0);

			/*If the given bugger is not large enough to hold the data, the return value is 
			the buffer size,  in characters, required to hold the string and its terminating 
			null character. We use this return value to alloc the final buffer. */
			size = GetEnvironmentVariableA("PHPRC", &dummybuf, 0);
			if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
				/* The environment variable doesn't exist. */
				env_location = "";
			} else {
				if (size == 0) {
					env_location = "";
				} else {
					size = GetEnvironmentVariableA("PHPRC", phprc_path, size);
					if (size == 0) {
						env_location = "";
					} else {
						env_location = phprc_path;
					}
				}
			}
		}
#else
		if (!env_location) {
			env_location = "";
		}
#endif
		/*
		 * Prepare search path
		 */

		search_path_size = MAXPATHLEN * 4 + (int)strlen(env_location) + 3 + 1;
		php_ini_search_path = (char *) emalloc(search_path_size);
		free_ini_search_path = 1;
		php_ini_search_path[0] = 0;

		/* Add environment location */
		if (env_location[0]) {
			if (*php_ini_search_path) {
				strlcat(php_ini_search_path, paths_separator, search_path_size);
			}
			strlcat(php_ini_search_path, env_location, search_path_size);
			php_ini_file_name = env_location;
		}

#ifdef PHP_WIN32
		/* Add registry location */
		reg_location = GetIniPathFromRegistry();
		if (reg_location != NULL) {
			if (*php_ini_search_path) {
				strlcat(php_ini_search_path, paths_separator, search_path_size);
			}
			strlcat(php_ini_search_path, reg_location, search_path_size);
			efree(reg_location);
		}
#endif

		/* Add cwd (not with CLI) */
		if (!sapi_module.php_ini_ignore_cwd) {
			if (*php_ini_search_path) {
				strlcat(php_ini_search_path, paths_separator, search_path_size);
			}
			strlcat(php_ini_search_path, ".", search_path_size);
		}

		if (PG(php_binary)) {
			char *separator_location, *binary_location;

			binary_location = estrdup(PG(php_binary));
			separator_location = strrchr(binary_location, DEFAULT_SLASH);

			if (separator_location && separator_location != binary_location) {
				*(separator_location) = 0;
			}
			if (*php_ini_search_path) {
				strlcat(php_ini_search_path, paths_separator, search_path_size);
			}
			strlcat(php_ini_search_path, binary_location, search_path_size);
			efree(binary_location);
		}

		/* Add default location */
#ifdef PHP_WIN32
		default_location = (char *) emalloc(MAXPATHLEN + 1);

		if (0 < GetWindowsDirectory(default_location, MAXPATHLEN)) {
			if (*php_ini_search_path) {
				strlcat(php_ini_search_path, paths_separator, search_path_size);
			}
			strlcat(php_ini_search_path, default_location, search_path_size);
		}

		/* For people running under terminal services, GetWindowsDirectory will
		 * return their personal Windows directory, so lets add the system
		 * windows directory too */
		if (0 < GetSystemWindowsDirectory(default_location, MAXPATHLEN)) {
			if (*php_ini_search_path) {
				strlcat(php_ini_search_path, paths_separator, search_path_size);
			}
			strlcat(php_ini_search_path, default_location, search_path_size);
		}
		efree(default_location);

#else
		default_location = PHP_CONFIG_FILE_PATH;
		if (*php_ini_search_path) {
			strlcat(php_ini_search_path, paths_separator, search_path_size);
		}
		strlcat(php_ini_search_path, default_location, search_path_size);
#endif
	}

	PG(open_basedir) = NULL;

	/*
	 * Find and open actual ini file
	 */

	memset(&fh, 0, sizeof(fh));

	/* If SAPI does not want to ignore all ini files OR an overriding file/path is given.
	 * This allows disabling scanning for ini files in the PHP_CONFIG_FILE_SCAN_DIR but still
	 * load an optional ini file. */
	if (!sapi_module.php_ini_ignore || sapi_module.php_ini_path_override) {

		/* Check if php_ini_file_name is a file and can be opened */
		if (php_ini_file_name && php_ini_file_name[0]) {
			zend_stat_t statbuf;

			if (!VCWD_STAT(php_ini_file_name, &statbuf)) {
				if (!((statbuf.st_mode & S_IFMT) == S_IFDIR)) {
					fh.handle.fp = VCWD_FOPEN(php_ini_file_name, "r");
					if (fh.handle.fp) {
						fh.filename = php_ini_opened_path = expand_filepath(php_ini_file_name, NULL);
					}
				}
			}
		}

		/* Otherwise search for php-%sapi-module-name%.ini file in search path */
		if (!fh.handle.fp) {
			const char *fmt = "php-%s.ini";
			char *ini_fname;
			spprintf(&ini_fname, 0, fmt, sapi_module.name);
			fh.handle.fp = php_fopen_with_path(ini_fname, "r", php_ini_search_path, &php_ini_opened_path);
			efree(ini_fname);
			if (fh.handle.fp) {
				fh.filename = php_ini_opened_path;
			}
		}

		/* If still no ini file found, search for php.ini file in search path */
		if (!fh.handle.fp) {
			fh.handle.fp = php_fopen_with_path("php.ini", "r", php_ini_search_path, &php_ini_opened_path);
			if (fh.handle.fp) {
				fh.filename = php_ini_opened_path;
			}
		}
	}

	if (free_ini_search_path) {
		efree(php_ini_search_path);
	}

	PG(open_basedir) = open_basedir;

	if (fh.handle.fp) {
		fh.type = ZEND_HANDLE_FP;
		RESET_ACTIVE_INI_HASH();

		zend_parse_ini_file(&fh, 1, ZEND_INI_SCANNER_NORMAL, (zend_ini_parser_cb_t) php_ini_parser_cb, &configuration_hash);

		{
			zval tmp;

			ZVAL_NEW_STR(&tmp, zend_string_init(fh.filename, strlen(fh.filename), 1));
			zend_hash_str_update(&configuration_hash, "cfg_file_path", sizeof("cfg_file_path")-1, &tmp);
			if (php_ini_opened_path) {
				efree(php_ini_opened_path);
			}
			php_ini_opened_path = zend_strndup(Z_STRVAL(tmp), Z_STRLEN(tmp));
		}
	}

	/* Check for PHP_INI_SCAN_DIR environment variable to override/set config file scan directory */
	php_ini_scanned_path = getenv("PHP_INI_SCAN_DIR");
	if (!php_ini_scanned_path) {
		/* Or fall back using possible --with-config-file-scan-dir setting (defaults to empty string!) */
		php_ini_scanned_path = PHP_CONFIG_FILE_SCAN_DIR;
	}
	php_ini_scanned_path_len = (int)strlen(php_ini_scanned_path);

	/* Scan and parse any .ini files found in scan path if path not empty. */
	if (!sapi_module.php_ini_ignore && php_ini_scanned_path_len) {
		struct dirent **namelist;
		int ndir, i;
		zend_stat_t sb;
		char ini_file[MAXPATHLEN];
		char *p;
		zend_file_handle fh2;
		zend_llist scanned_ini_list;
		zend_llist_element *element;
		int l, total_l = 0;
		char *bufpath, *debpath, *endpath;
		int lenpath;

		zend_llist_init(&scanned_ini_list, sizeof(char *), (llist_dtor_func_t) free_estring, 1);
		memset(&fh2, 0, sizeof(fh2));

		bufpath = estrdup(php_ini_scanned_path);
		for (debpath = bufpath ; debpath ; debpath=endpath) {
			endpath = strchr(debpath, DEFAULT_DIR_SEPARATOR);
			if (endpath) {
				*(endpath++) = 0;
			}
			if (!debpath[0]) {
				/* empty string means default builtin value
				   to allow "/foo/phd.d:" or ":/foo/php.d" */
				debpath = PHP_CONFIG_FILE_SCAN_DIR;
			}
			lenpath = (int)strlen(debpath);

			if (lenpath > 0 && (ndir = php_scandir(debpath, &namelist, 0, php_alphasort)) > 0) {

				for (i = 0; i < ndir; i++) {

					/* check for any file with .ini extension */
					if (!(p = strrchr(namelist[i]->d_name, '.')) || (p && strcmp(p, ".ini"))) {
						free(namelist[i]);
						continue;
					}
					/* Reset active ini section */
					RESET_ACTIVE_INI_HASH();

					if (IS_SLASH(debpath[lenpath - 1])) {
						snprintf(ini_file, MAXPATHLEN, "%s%s", debpath, namelist[i]->d_name);
					} else {
						snprintf(ini_file, MAXPATHLEN, "%s%c%s", debpath, DEFAULT_SLASH, namelist[i]->d_name);
					}
					if (VCWD_STAT(ini_file, &sb) == 0) {
						if (S_ISREG(sb.st_mode)) {
							if ((fh2.handle.fp = VCWD_FOPEN(ini_file, "r"))) {
								fh2.filename = ini_file;
								fh2.type = ZEND_HANDLE_FP;

								if (zend_parse_ini_file(&fh2, 1, ZEND_INI_SCANNER_NORMAL, (zend_ini_parser_cb_t) php_ini_parser_cb, &configuration_hash) == SUCCESS) {
									/* Here, add it to the list of ini files read */
									l = (int)strlen(ini_file);
									total_l += l + 2;
									p = estrndup(ini_file, l);
									zend_llist_add_element(&scanned_ini_list, &p);
								}
							}
						}
					}
					free(namelist[i]);
				}
				free(namelist);
			}
		}
		efree(bufpath);

		if (total_l) {
			int php_ini_scanned_files_len = (php_ini_scanned_files) ? (int)strlen(php_ini_scanned_files) + 1 : 0;
			php_ini_scanned_files = (char *) realloc(php_ini_scanned_files, php_ini_scanned_files_len + total_l + 1);
			if (!php_ini_scanned_files_len) {
				*php_ini_scanned_files = '\0';
			}
			total_l += php_ini_scanned_files_len;
			for (element = scanned_ini_list.head; element; element = element->next) {
				if (php_ini_scanned_files_len) {
					strlcat(php_ini_scanned_files, ",\n", total_l);
				}
				strlcat(php_ini_scanned_files, *(char **)element->data, total_l);
				strlcat(php_ini_scanned_files, element->next ? ",\n" : "\n", total_l);
			}
		}
		zend_llist_destroy(&scanned_ini_list);
	} else {
		/* Make sure an empty php_ini_scanned_path ends up as NULL */
		php_ini_scanned_path = NULL;
	}

	if (sapi_module.ini_entries) {
		/* Reset active ini section */
		RESET_ACTIVE_INI_HASH();
		zend_parse_ini_string(sapi_module.ini_entries, 1, ZEND_INI_SCANNER_NORMAL, (zend_ini_parser_cb_t) php_ini_parser_cb, &configuration_hash);
	}

	return SUCCESS;
}
Exemplo n.º 10
0
//-----------------------------------------------------------------------------
// name: start_vm()
// desc: ...
//-----------------------------------------------------------------------------
t_CKBOOL miniAudicle::start_vm()
{
    char buffer[1024];
    time_t t;
    
    // allocate status buffers
    // allocate alternating buffers for VM status messages
    num_status_bufs = 4;
    status_bufs = new Chuck_VM_Status * [num_status_bufs];
    for( size_t i = 0; i < num_status_bufs; i++ )
        status_bufs[i] = new Chuck_VM_Status;
    status_bufs_read = 0;
    status_bufs_write = 0;
    
    // clear shred management structures
    last_result.clear();
    
    while( !otf_docids.empty() )
        otf_docids.pop();
    
    map< t_CKUINT, vector< t_CKUINT > * >::iterator iter = documents.begin(),
        end = documents.end();
    for( ; iter != end; iter++ )
        iter->second->clear();
    
    shreds.clear();
    
    // clear the class name existence map
    class_names->clear();
    
    time(&t);
    strncpy( buffer, ctime(&t), 24 );
    buffer[24] = '\0';

    // log
    EM_log( CK_LOG_SYSTEM, "-------( %s )-------", buffer );
    EM_log( CK_LOG_SYSTEM, "starting chuck virtual machine..." );
    // push log
    EM_pushlog();
    
    if( m_chuck == NULL )
    {
        // log
        EM_log( CK_LOG_INFO, "allocating VM..." );
        t_CKBOOL enable_audio = vm_options.enable_audio;
        t_CKBOOL vm_halt = FALSE;
        t_CKBOOL force_srate = TRUE;
        t_CKUINT srate = vm_options.srate;
        t_CKUINT buffer_size = vm_options.buffer_size;
        t_CKUINT num_buffers = NUM_BUFFERS_DEFAULT;
        t_CKUINT dac = vm_options.dac;
        t_CKUINT adc = vm_options.adc;
        t_CKBOOL set_priority = FALSE;
        t_CKBOOL block = vm_options.enable_block;
        t_CKUINT output_channels = vm_options.num_outputs;
        t_CKUINT input_channels = vm_options.num_inputs;
        t_CKUINT adaptive_size = 0;
        
        // lets make up some magic numbers...
        vm_sleep_time = vm_options.buffer_size * 1000000 / vm_options.srate;
        vm_sleep_max = 20;
        vm_status_timeouts_max = vm_options.buffer_size / 100;
        
        vm_status_timeouts = 0;

        // check buffer size
        // buffer_size = next_power_2( buffer_size-1 );
        // audio, boost
        if( !set_priority && !block ) priority = priority_low;
        if( !set_priority && !enable_audio ) priority = 0x7fffffff;
        // set priority
        // Chuck_VM::our_priority = priority;
        // set watchdog
#ifdef __MACOSX_CORE__
        g_do_watchdog = TRUE;
        g_watchdog_timeout = .5;
#else
        g_do_watchdog = FALSE;
#endif
        
        std::list<std::string> library_paths = vm_options.library_paths;
        std::list<std::string> named_chugins = vm_options.named_chugins;
        // normalize paths
        for(std::list<std::string>::iterator i = library_paths.begin();
            i != library_paths.end(); i++)
            *i = expand_filepath(*i);
        for(std::list<std::string>::iterator j = named_chugins.begin();
            j != named_chugins.end(); j++)
            *j = expand_filepath(*j);
        
        m_chuck = new ChucK();
        
        m_chuck->setParam(CHUCK_PARAM_SAMPLE_RATE, srate);
        m_chuck->setParam(CHUCK_PARAM_INPUT_CHANNELS, input_channels);
        m_chuck->setParam(CHUCK_PARAM_OUTPUT_CHANNELS, output_channels);
        m_chuck->setParam(CHUCK_PARAM_VM_ADAPTIVE, adaptive_size);
        m_chuck->setParam(CHUCK_PARAM_VM_HALT, vm_halt);
        m_chuck->setParam(CHUCK_PARAM_USER_CHUGINS, named_chugins);
        m_chuck->setParam(CHUCK_PARAM_USER_CHUGIN_DIRECTORIES, library_paths);

        if( !m_chuck->init() )
        {
            fprintf( stderr, "[chuck]: failed to init chuck engine\n" );
            // pop
            EM_poplog();
            return FALSE;
        }

        // allocate the vm - needs the type system
        vm = m_chuck->vm();
        
        //--------------------------- AUDIO I/O SETUP ---------------------------------
        
        // push
        EM_pushlog();
        // log
        EM_log( CK_LOG_SYSTEM, "probing '%s' audio subsystem...", enable_audio ? "real-time" : "fake-time" );
        
        ChuckAudio::m_dac_n = dac;
        ChuckAudio::m_adc_n = adc;
        
        // probe / init (this shouldn't start audio yet...
        // moved here 1.3.1.2; to main ge: 1.3.5.3)
        if( !ChuckAudio::initialize( output_channels, input_channels, srate, buffer_size, num_buffers, audio_cb, m_chuck, force_srate ) )
        {
            EM_log( CK_LOG_SYSTEM,
                   "cannot initialize audio device (use --silent/-s for non-realtime)" );
            // pop
            EM_poplog();
            // done
            return FALSE;
        }
        
        // log
        EM_log( CK_LOG_SYSTEM, "real-time audio: %s", enable_audio ? "YES" : "NO" );
        EM_log( CK_LOG_SYSTEM, "mode: %s", block ? "BLOCKING" : "CALLBACK" );
        EM_log( CK_LOG_SYSTEM, "sample rate: %ld", srate );
        EM_log( CK_LOG_SYSTEM, "buffer size: %ld", buffer_size );
        
        if( enable_audio )
        {
            EM_log( CK_LOG_SYSTEM, "num buffers: %ld", num_buffers );
            EM_log( CK_LOG_SYSTEM, "adc: %ld dac: %d", adc, dac );
            EM_log( CK_LOG_SYSTEM, "adaptive block processing: %ld", adaptive_size > 1 ? adaptive_size : 0 );
        }
        EM_log( CK_LOG_SYSTEM, "channels in: %ld out: %ld", input_channels, output_channels );
        
        // pop
        EM_poplog();
        
        // allocate the compiler
        compiler = m_chuck->compiler();
        
#ifdef __MA_IMPORT_MAUI__
        // import api
        init_maui( compiler->env() );
#endif
        for(list<t_CKBOOL (*)(Chuck_Env *)>::iterator i = vm_options.query_funcs.begin(); i != vm_options.query_funcs.end(); i++)
            (*i)( compiler->env() );
        
        if(!ChuckAudio::start())
        {
            EM_log( CK_LOG_SYSTEM, "error starting audio (use --silent/-s for non-realtime)" );
            // pop
            EM_poplog();
            // done
            return FALSE;
        }
        
        // pop log
        EM_poplog();
        EM_log( CK_LOG_SYSTEM, "running audio" );
    }
    
    vm_on = TRUE;
    // pop
    EM_poplog();
    
    return vm_on;
}
Exemplo n.º 11
0
PHPAPI int php_checkuid_ex(const char *filename, const char *fopen_mode, int mode, int flags)
{
	struct stat sb;
	int ret, nofile=0;
	long uid=0L, gid=0L, duid=0L, dgid=0L;
	char path[MAXPATHLEN];
	char *s, filenamecopy[MAXPATHLEN];
	TSRMLS_FETCH();

	path[0] = '\0';

	if (!filename) {
		return 0; /* path must be provided */
	}

	if (strlcpy(filenamecopy, filename, MAXPATHLEN)>=MAXPATHLEN) {
		return 0;
	}
	filename=(char *)&filenamecopy;

	if (fopen_mode) {
		if (fopen_mode[0] == 'r') {
			mode = CHECKUID_DISALLOW_FILE_NOT_EXISTS;
		} else {
			mode = CHECKUID_CHECK_FILE_AND_DIR;
		}
	}
		
	/* First we see if the file is owned by the same user...
	 * If that fails, passthrough and check directory...
	 */
	if (mode != CHECKUID_ALLOW_ONLY_DIR) {
#if HAVE_BROKEN_GETCWD
		char ftest[MAXPATHLEN];

		strcpy(ftest, filename);
		if (VCWD_GETCWD(ftest, sizeof(ftest)) == NULL) {
			strcpy(path, filename);
		} else
#endif
		expand_filepath(filename, path TSRMLS_CC);

		ret = VCWD_STAT(path, &sb);
		if (ret < 0) {
			if (mode == CHECKUID_DISALLOW_FILE_NOT_EXISTS) {
				if ((flags & CHECKUID_NO_ERRORS) == 0) {
					php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to access %s", filename);
				}
				return 0;
			} else if (mode == CHECKUID_ALLOW_FILE_NOT_EXISTS) {
				if ((flags & CHECKUID_NO_ERRORS) == 0) {
					php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to access %s", filename);
				}
				return 1;
			} 
			nofile = 1;
		} else {
			uid = sb.st_uid;
			gid = sb.st_gid;
			if (uid == php_getuid()) {
				return 1;
 			} else if (PG(safe_mode_gid) && gid == php_getgid()) {
 				return 1;
			}
		}

		/* Trim off filename */
		if ((s = strrchr(path, DEFAULT_SLASH))) {
			if (*(s + 1) == '\0' && s != path) { /* make sure that the / is not the last character */
				*s = '\0';
				s = strrchr(path, DEFAULT_SLASH);
			}
			if (s) {
				if (s == path) {
					path[1] = '\0';
				} else {
					*s = '\0';
				}
			}
		}
	} else { /* CHECKUID_ALLOW_ONLY_DIR */
		s = strrchr(filename, DEFAULT_SLASH);

		if (s == filename) {
			/* root dir */
			path[0] = DEFAULT_SLASH;
			path[1] = '\0';
		} else if (s && *(s + 1) != '\0') { /* make sure that the / is not the last character */
			*s = '\0';
			VCWD_REALPATH(filename, path);
			*s = DEFAULT_SLASH;
		} else {
			/* Under Solaris, getcwd() can fail if there are no
			 * read permissions on a component of the path, even
			 * though it has the required x permissions */
			path[0] = '.';
			path[1] = '\0';
			VCWD_GETCWD(path, sizeof(path));
 		}
	} /* end CHECKUID_ALLOW_ONLY_DIR */
	
	if (mode != CHECKUID_ALLOW_ONLY_FILE) {
		/* check directory */
		ret = VCWD_STAT(path, &sb);
		if (ret < 0) {
			if ((flags & CHECKUID_NO_ERRORS) == 0) {
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to access %s", filename);
			}
			return 0;
		}
		duid = sb.st_uid;
		dgid = sb.st_gid;
		if (duid == php_getuid()) {
			return 1;
 		} else if (PG(safe_mode_gid) && dgid == php_getgid()) {
 			return 1;
		} else {
			if (SG(rfc1867_uploaded_files)) {
				if (zend_hash_exists(SG(rfc1867_uploaded_files), (char *) filename, strlen(filename)+1)) {
					return 1;
				}
			}
		}
	}

	if (mode == CHECKUID_ALLOW_ONLY_DIR) {
		uid = duid;
		gid = dgid;
		if (s) {
			*s = 0;
		}
	}
	
	if (nofile) {
		uid = duid;
		gid = dgid;
		filename = path;
	}

	if ((flags & CHECKUID_NO_ERRORS) == 0) {
		if (PG(safe_mode_gid)) {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "SAFE MODE Restriction in effect.  The script whose uid/gid is %ld/%ld is not allowed to access %s owned by uid/gid %ld/%ld", php_getuid(), php_getgid(), filename, uid, gid);
		} else {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "SAFE MODE Restriction in effect.  The script whose uid is %ld is not allowed to access %s owned by uid %ld", php_getuid(), filename, uid);
		}			
	}

	return 0;
}
Exemplo n.º 12
0
/* {{{ proto object ffmpeg_movie(string filename)
   Constructor for ffmpeg_movie objects
 */
FFMPEG_PHP_CONSTRUCTOR(ffmpeg_movie, __construct)
{
    int hashkey_length = 0, filename_len;
    char *filename = NULL, *fullpath = NULL, *hashkey = NULL;
	zend_bool persistent = 0;
    ff_movie_context *ffmovie_ctx = NULL;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &filename, &filename_len, &persistent) != SUCCESS) {
		return;
    }

	if (persistent && !INI_BOOL("ffmpeg.allow_persistent")) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Persistent movies have been disabled in php.ini");
		RETURN_FALSE;
    }

    if (persistent) {
        zend_rsrc_list_entry *le;
        /* resolve the fully-qualified path name to use as the hash key */
        fullpath = expand_filepath(filename, NULL TSRMLS_CC);

        hashkey_length = sizeof("ffmpeg-php_")-1 + filename_len;
        hashkey = (char *) emalloc(hashkey_length+1);
        snprintf(hashkey, hashkey_length, "ffmpeg-php_%s", filename);

        /* do we have an existing persistent movie? */
        if (SUCCESS == zend_hash_find(&EG(persistent_list), hashkey, hashkey_length+1, (void**)&le)) {
            int type;

            if (Z_TYPE_P(le) != le_ffmpeg_pmovie) {
                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to retrieve persistent resource");
				efree(hashkey);
				RETURN_FALSE;
            }
            ffmovie_ctx = (ff_movie_context*)le->ptr;

            /* sanity check to ensure that the resource is still a valid
             * regular resource number */
            if (zend_list_find(ffmovie_ctx->rsrc_id, &type) == ffmovie_ctx) {
                /* add a reference to the persistent movie */
                zend_list_addref(ffmovie_ctx->rsrc_id);
            } else {
                //php_error_docref(NULL TSRMLS_CC, E_ERROR,
                //"Not a valid persistent movie resource");
                ffmovie_ctx->rsrc_id = ZEND_REGISTER_RESOURCE(NULL,
                        ffmovie_ctx, le_ffmpeg_pmovie);
            }

        } else { /* no existing persistant movie, create one */
            zend_rsrc_list_entry new_le;
            ffmovie_ctx = _php_alloc_ffmovie_ctx(1);

            if (_php_open_movie_file(ffmovie_ctx, filename)) {
                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can't open movie file %s", filename);
                ZVAL_BOOL(getThis(), 0);
                RETURN_FALSE;
            }

            Z_TYPE(new_le) = le_ffmpeg_pmovie;
            new_le.ptr = ffmovie_ctx;

            if (FAILURE == zend_hash_update(&EG(persistent_list), hashkey,
                        hashkey_length+1, (void *)&new_le, sizeof(zend_rsrc_list_entry),
                        NULL)) {
                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to register persistent resource");
				RETURN_FALSE;
            }

            ffmovie_ctx->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, ffmovie_ctx, le_ffmpeg_pmovie);
        }

    } else {
        ffmovie_ctx = _php_alloc_ffmovie_ctx(0);

        if (_php_open_movie_file(ffmovie_ctx, filename)) {
            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can't open movie file %s", filename);
            ZVAL_BOOL(getThis(), 0);
            RETURN_FALSE;
        }

        /* pass NULL for resource result since we're not returning the resource
           directly, but adding it to the returned object. */
        ffmovie_ctx->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, ffmovie_ctx, le_ffmpeg_movie);
    }

    object_init_ex(getThis(), ffmpeg_movie_class_entry_ptr);
    add_property_resource(getThis(), "ffmpeg_movie", ffmovie_ctx->rsrc_id);

    if (fullpath) {
        efree(fullpath);
    }
    if (hashkey) {
        efree(hashkey);
    }
}
Exemplo n.º 13
0
//-----------------------------------------------------------------------------
// name: start_vm()
// desc: ...
//-----------------------------------------------------------------------------
t_CKBOOL miniAudicle::start_vm()
{
    char buffer[1024];
    time_t t;
    
    // allocate status buffers
    // allocate alternating buffers for VM status messages
    num_status_bufs = 4;
    status_bufs = new Chuck_VM_Status * [num_status_bufs];
    for( size_t i = 0; i < num_status_bufs; i++ )
        status_bufs[i] = new Chuck_VM_Status;
    status_bufs_read = 0;
    status_bufs_write = 0;
    
    // clear shred management structures
    last_result.clear();
    
    while( !otf_docids.empty() )
        otf_docids.pop();
    
    map< t_CKUINT, vector< t_CKUINT > * >::iterator iter = documents.begin(),
        end = documents.end();
    for( ; iter != end; iter++ )
        iter->second->clear();
    
    shreds.clear();
    
    // clear the class name existence map
    class_names->clear();
    
    time(&t);
    strncpy( buffer, ctime(&t), 24 );
    buffer[24] = '\0';

    // log
    EM_log( CK_LOG_SYSTEM, "-------( %s )-------", buffer );
    EM_log( CK_LOG_SYSTEM, "starting chuck virtual machine..." );
    // push log
    EM_pushlog();
    
    if( vm == NULL )
    {
        // log
        EM_log( CK_LOG_INFO, "allocating VM..." );
        t_CKBOOL enable_audio = vm_options.enable_audio;
        t_CKBOOL vm_halt = FALSE;
        t_CKUINT srate = vm_options.srate;
        t_CKUINT buffer_size = vm_options.buffer_size;
        t_CKUINT num_buffers = NUM_BUFFERS_DEFAULT;
        t_CKUINT dac = vm_options.dac;
        t_CKUINT adc = vm_options.adc;
        t_CKBOOL set_priority = FALSE;
        t_CKBOOL block = vm_options.enable_block;
        t_CKUINT output_channels = vm_options.num_outputs;
        t_CKUINT input_channels = vm_options.num_inputs;
        
        // lets make up some magic numbers...
        vm_sleep_time = vm_options.buffer_size * 1000000 / vm_options.srate;
        vm_sleep_max = 20;
        vm_status_timeouts_max = vm_options.buffer_size / 100;
        
        vm_status_timeouts = 0;

        // check buffer size
        // buffer_size = next_power_2( buffer_size-1 );
        // audio, boost
        if( !set_priority && !block ) priority = priority_low;
        if( !set_priority && !enable_audio ) priority = 0x7fffffff;
        // set priority
        Chuck_VM::our_priority = priority;
        // set watchdog
#ifdef __MACOSX_CORE__
        g_do_watchdog = TRUE;
        g_watchdog_timeout = .5;
#else
        g_do_watchdog = FALSE;
#endif
        
        // allocate the vm - needs the type system
        vm = g_vm = new Chuck_VM;

        if( !vm->initialize( enable_audio, vm_halt, srate, buffer_size,
                             num_buffers, dac, adc, output_channels, 
                             input_channels, block ) )
        {
            fprintf( stderr, "[chuck]: %s\n", vm->last_error() );
            // pop
            EM_poplog();
            return FALSE;
        }
            
        // log
        EM_log( CK_LOG_INFO, "allocating compiler..." );

        // allocate the compiler
        g_compiler = compiler = new Chuck_Compiler;
        
        
        std::list<std::string> library_paths = vm_options.library_paths;
        std::list<std::string> named_chugins = vm_options.named_chugins;
        // normalize paths
        for(std::list<std::string>::iterator i = library_paths.begin();
            i != library_paths.end(); i++)
            *i = expand_filepath(*i);
        for(std::list<std::string>::iterator j = named_chugins.begin();
            j != named_chugins.end(); j++)
            *j = expand_filepath(*j);
        
        // initialize the compiler
        compiler->initialize( vm, library_paths, named_chugins );
        // enable dump
        compiler->emitter->dump = FALSE;
        // set auto depend
        compiler->set_auto_depend( FALSE );

        // vm synthesis subsystem - needs the type system
        if( !vm->initialize_synthesis() )
        {
            fprintf( stderr, "[chuck]: %s\n", vm->last_error() );
            // pop
            EM_poplog();
            return FALSE;
        }
        
#ifdef __MA_IMPORT_MAUI__
        // import api
        init_maui( compiler->env );
#endif
        for(list<t_CKBOOL (*)(Chuck_Env *)>::iterator i = vm_options.query_funcs.begin(); i != vm_options.query_funcs.end(); i++)
            (*i)( compiler->env );

        // reset the parser
        reset_parse();
        
        Chuck_VM_Code * code = NULL;
        Chuck_VM_Shred * shred = NULL;
        
        // whether or not chug should be enabled (added 1.3.0.0)
        EM_log( CK_LOG_SEVERE, "pre-loading ChucK libs..." );
        EM_pushlog();
        
        // iterate over list of ck files that the compiler found
        for( std::list<std::string>::iterator fck = compiler->m_cklibs_to_preload.begin();
            fck != compiler->m_cklibs_to_preload.end(); fck++)
        {
            // the filename
            std::string filename = *fck;
            
            // log
            EM_log( CK_LOG_SEVERE, "preloading '%s'...", filename.c_str() );
            // push indent
            EM_pushlog();
            
            // SPENCERTODO: what to do for full path
            std::string full_path = filename;
            
            // parse, type-check, and emit
            if( compiler->go( filename, NULL, NULL, full_path ) )
            {
                // TODO: how to compilation handle?
                //return 1;
                
                // get the code
                code = compiler->output();
                // name it - TODO?
                // code->name += string(argv[i]);
                
                // spork it
                shred = vm->spork( code, NULL );
            }
            
            // pop indent
            EM_poplog();
        }
        
        // clear the list of chuck files to preload
        compiler->m_cklibs_to_preload.clear();
        
        // pop log
        EM_poplog();
        
        // load user namespace
        compiler->env->load_user_namespace();
        
        // start the vm handler threads
#ifndef __PLATFORM_WIN32__
        pthread_create( &vm_tid, NULL, vm_cb, NULL );
#else
        vm_tid = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)vm_cb, NULL, 0, 0 );
#endif
    }

    // check it
    if( !g_forked && vm_options.enable_network )
    {
        // start tcp server
        g_sock = ck_tcp_create( 1 );
        if( !g_sock || !ck_bind( g_sock, g_port ) || !ck_listen( g_sock, 10 ) )
        {
            fprintf( stderr, "[chuck]: cannot bind to tcp port %li...\n", g_port );
            ck_close( g_sock );
            g_sock = NULL;
        }
        else
        {
#ifndef __PLATFORM_WIN32__
            pthread_create( &otf_tid, NULL, otf_cb, NULL );
#else
            otf_tid = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)otf_cb, NULL, 0, 0 );
#endif
        }
        
        g_forked = TRUE;
    }
    
    vm_on = TRUE;
    // pop
    EM_poplog();
    
    return vm_on;
}
Exemplo n.º 14
0
/* {{{ proto object ffmpeg_movie(string filename) 
   Constructor for ffmpeg_movie objects
 */
FFMPEG_PHP_CONSTRUCTOR(ffmpeg_movie, __construct)
{
    int persistent = 0, hashkey_length = 0;
    char *filename = NULL, *fullpath = NULL, *hashkey = NULL;
    zval ***argv;
    ff_movie_context *ffmovie_ctx = NULL;

    /* retrieve arguments */ 
    argv = (zval ***) safe_emalloc(sizeof(zval **), ZEND_NUM_ARGS(), 0);

    if (zend_get_parameters_array_ex(ZEND_NUM_ARGS(), argv) != SUCCESS) {
        efree(argv);
        php_error_docref(NULL TSRMLS_CC, E_ERROR,
                "Error parsing arguments");
    }

    switch (ZEND_NUM_ARGS()) {
        case 2:
            convert_to_boolean_ex(argv[1]);

            if (! INI_BOOL("ffmpeg.allow_persistent") && Z_LVAL_PP(argv[1])) {
                zend_error(E_WARNING, 
                        "Persistent movies have been disabled in php.ini");
                break;
            } 

            persistent = Z_LVAL_PP(argv[1]);

            /* fallthru */
        case 1:
            convert_to_string_ex(argv[0]);
            filename = Z_STRVAL_PP(argv[0]);
            break;
        default:
            WRONG_PARAM_COUNT;
    } 

    if (persistent) {
        list_entry *le;
        /* resolve the fully-qualified path name to use as the hash key */
        fullpath = expand_filepath(filename, NULL TSRMLS_CC);

        hashkey_length = sizeof("ffmpeg-php_")-1 + 
            strlen(SAFE_STRING(filename));
        hashkey = (char *) emalloc(hashkey_length+1);
        snprintf(hashkey, hashkey_length, "ffmpeg-php_%s",
			SAFE_STRING(filename));

        
        /* do we have an existing persistent movie? */
        if (SUCCESS == zend_hash_find(&EG(persistent_list), hashkey, 
                    hashkey_length+1, (void**)&le)) {
            int type;
            
            if (Z_TYPE_P(le) != le_ffmpeg_pmovie) {
                php_error_docref(NULL TSRMLS_CC, E_ERROR, 
                        "Failed to retrieve persistent resource");
            }
            ffmovie_ctx = (ff_movie_context*)le->ptr;
           
            /* sanity check to ensure that the resource is still a valid 
             * regular resource number */
            if (zend_list_find(ffmovie_ctx->rsrc_id, &type) == ffmovie_ctx) {
                /* add a reference to the persistent movie */
                zend_list_addref(ffmovie_ctx->rsrc_id);
            } else {
                //php_error_docref(NULL TSRMLS_CC, E_ERROR, 
                //"Not a valid persistent movie resource");
                ffmovie_ctx->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, 
                        ffmovie_ctx, le_ffmpeg_pmovie);
            }
            
        } else { /* no existing persistant movie, create one */
            list_entry new_le;
            ffmovie_ctx = _php_alloc_ffmovie_ctx(1);

            if (_php_open_movie_file(ffmovie_ctx, filename)) {
                zend_error(E_WARNING, "Can't open movie file %s", filename);
                efree(argv);
                ZVAL_BOOL(getThis(), 0);
                RETURN_FALSE;
            }

            Z_TYPE(new_le) = le_ffmpeg_pmovie;
            new_le.ptr = ffmovie_ctx;

            if (FAILURE == zend_hash_update(&EG(persistent_list), hashkey, 
                        hashkey_length+1, (void *)&new_le, sizeof(list_entry),
                        NULL)) {
                php_error_docref(NULL TSRMLS_CC, E_WARNING, 
                        "Failed to register persistent resource");
            }
            
            ffmovie_ctx->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, ffmovie_ctx, 
                    le_ffmpeg_pmovie);
        }
        
    } else {
        ffmovie_ctx = _php_alloc_ffmovie_ctx(0);
        
        if (_php_open_movie_file(ffmovie_ctx, Z_STRVAL_PP(argv[0]))) {
            zend_error(E_WARNING, "Can't open movie file %s", 
                    Z_STRVAL_PP(argv[0]));
            efree(argv);
            ZVAL_BOOL(getThis(), 0);
            RETURN_FALSE;
        }
        
        /* pass NULL for resource result since we're not returning the resource
           directly, but adding it to the returned object. */
        ffmovie_ctx->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, ffmovie_ctx, 
                le_ffmpeg_movie);
    }

    object_init_ex(getThis(), ffmpeg_movie_class_entry_ptr);
    add_property_resource(getThis(), "ffmpeg_movie", ffmovie_ctx->rsrc_id);

    efree(argv);
    if (fullpath) {
        efree(fullpath);
    }
    if (hashkey) {
        efree(hashkey);
    }
}