/* {{{ cli_seek_file_begin */ static int cli_seek_file_begin(zend_file_handle *file_handle, char *script_file, int *lineno) { int c; *lineno = 1; file_handle->type = ZEND_HANDLE_FP; file_handle->opened_path = NULL; file_handle->free_filename = 0; if (!(file_handle->handle.fp = VCWD_FOPEN(script_file, "rb"))) { php_printf("Could not open input file: %s\n", script_file); return FAILURE; } file_handle->filename = script_file; /* #!php support */ c = fgetc(file_handle->handle.fp); if (c == '#' && (c = fgetc(file_handle->handle.fp)) == '!') { while (c != '\n' && c != '\r' && c != EOF) { c = fgetc(file_handle->handle.fp); /* skip to end of line */ } /* handle situations where line is terminated by \r\n */ if (c == '\r') { if (fgetc(file_handle->handle.fp) != '\n') { zend_long pos = zend_ftell(file_handle->handle.fp); zend_fseek(file_handle->handle.fp, pos - 1, SEEK_SET); } } *lineno = 2; } else { rewind(file_handle->handle.fp); } return SUCCESS; }
/* {{{ mlfi_connect() */ static sfsistat mlfi_connect(SMFICTX *ctx, char *hostname, _SOCK_ADDR *hostaddr) { zend_file_handle file_handle; zval function_name, retval, *param[1]; int status; TSRMLS_FETCH(); /* request startup */ if (php_request_startup(TSRMLS_C)==FAILURE) { SG(headers_sent) = 1; SG(request_info).no_headers = 1; php_request_shutdown((void *) 0); return SMFIS_TEMPFAIL; } /* disable headers */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; if (filename == NULL) { php_printf("No input file specified"); return SMFIS_TEMPFAIL; } if (!(file_handle.handle.fp = VCWD_FOPEN(filename, "rb"))) { php_printf("Could not open input file: %s\n", filename); return SMFIS_TEMPFAIL; } file_handle.type = ZEND_HANDLE_FP; file_handle.filename = filename; file_handle.free_filename = 0; file_handle.opened_path = NULL; php_execute_script(&file_handle TSRMLS_CC); /* call userland */ INIT_ZVAL(function_name); ALLOC_ZVAL(param[0]); INIT_PZVAL(param[0]); ZVAL_STRING(&function_name, "milter_connect", 0); ZVAL_STRING(param[0], hostname, 1); /* set the milter context for possible use in API functions */ MG(ctx) = ctx; MG(state) = MLFI_CONNECT; status = call_user_function(CG(function_table), NULL, &function_name, &retval, 1, param TSRMLS_CC); MG(state) = MLFI_NONE; zval_ptr_dtor(param); if (status == SUCCESS && Z_TYPE(retval) == IS_LONG) { return Z_LVAL(retval); } return SMFIS_CONTINUE; }
/* {{{ php_parse_user_ini_file */ PHPAPI int php_parse_user_ini_file(const char *dirname, char *ini_filename, HashTable *target_hash) { zend_stat_t sb; char ini_file[MAXPATHLEN]; zend_file_handle fh; snprintf(ini_file, MAXPATHLEN, "%s%c%s", dirname, DEFAULT_SLASH, ini_filename); if (VCWD_STAT(ini_file, &sb) == 0) { if (S_ISREG(sb.st_mode)) { memset(&fh, 0, sizeof(fh)); if ((fh.handle.fp = VCWD_FOPEN(ini_file, "r"))) { fh.filename = ini_file; fh.type = ZEND_HANDLE_FP; /* Reset active ini section */ RESET_ACTIVE_INI_HASH(); if (zend_parse_ini_file(&fh, 1, ZEND_INI_SCANNER_NORMAL, (zend_ini_parser_cb_t) php_ini_parser_cb, target_hash) == SUCCESS) { /* FIXME: Add parsed file to the list of user files read? */ return SUCCESS; } return FAILURE; } } } return FAILURE; }
/* {{{ Init Milter */ static int mlfi_init() { int ret = 0; zend_file_handle file_handle; zval function_name, retval; int status; TSRMLS_FETCH(); /* request startup */ if (php_request_startup(TSRMLS_C)==FAILURE) { SG(headers_sent) = 1; SG(request_info).no_headers = 1; php_request_shutdown((void *) 0); return -1; } /* disable headers */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; if (filename == NULL) { php_printf("No input file specified"); return SMFIS_TEMPFAIL; } if (!(file_handle.handle.fp = VCWD_FOPEN(filename, "rb"))) { php_printf("Could not open input file: %s\n", filename); return SMFIS_TEMPFAIL; } file_handle.type = ZEND_HANDLE_FP; file_handle.filename = filename; file_handle.free_filename = 0; file_handle.opened_path = NULL; php_execute_script(&file_handle TSRMLS_CC); /* call userland */ INIT_ZVAL(function_name); ZVAL_STRING(&function_name, "milter_init", 0); /* set the milter context for possible use in API functions */ MG(state) = MLFI_INIT; status = call_user_function(CG(function_table), NULL, &function_name, &retval, 0, NULL TSRMLS_CC); MG(state) = MLFI_NONE; MG(initialized) = 1; if (status == SUCCESS && Z_TYPE(retval) == IS_LONG) { ret = Z_LVAL(retval); } php_request_shutdown((void *) 0); return ret; }
/* com.typelib_file is the path to a file containing a * list of typelibraries to register *persistently*. * lines starting with ; are comments * append #cis to end of typelib name to cause its constants * to be loaded case insensitively */ static PHP_INI_MH(OnTypeLibFileUpdate) { FILE *typelib_file; char *typelib_name_buffer; char *strtok_buf = NULL; int cached; if (!new_value || !new_value[0] || (typelib_file = VCWD_FOPEN(new_value, "r"))==NULL) { return FAILURE; } typelib_name_buffer = (char *) emalloc(sizeof(char)*1024); while (fgets(typelib_name_buffer, 1024, typelib_file)) { ITypeLib *pTL; char *typelib_name; char *modifier, *ptr; int mode = CONST_CS | CONST_PERSISTENT; /* CONST_PERSISTENT is ok here */ if (typelib_name_buffer[0]==';') { continue; } typelib_name = php_strtok_r(typelib_name_buffer, "\r\n", &strtok_buf); /* get rid of newlines */ if (typelib_name == NULL) { continue; } typelib_name = php_strtok_r(typelib_name, "#", &strtok_buf); modifier = php_strtok_r(NULL, "#", &strtok_buf); if (modifier != NULL) { if (!strcmp(modifier, "cis") || !strcmp(modifier, "case_insensitive")) { mode &= ~CONST_CS; } } /* Remove leading/training white spaces on search_string */ while (isspace(*typelib_name)) {/* Ends on '\0' in worst case */ typelib_name ++; } ptr = typelib_name + strlen(typelib_name) - 1; while ((ptr != typelib_name) && isspace(*ptr)) { *ptr = '\0'; ptr--; } if ((pTL = php_com_load_typelib_via_cache(typelib_name, COMG(code_page), &cached TSRMLS_CC)) != NULL) { if (!cached) { php_com_import_typelib(pTL, mode, COMG(code_page) TSRMLS_CC); } ITypeLib_Release(pTL); } } efree(typelib_name_buffer); fclose(typelib_file); return SUCCESS; }
static int browscap_read_file(char *filename, browser_data *browdata, int persistent) /* {{{ */ { zend_file_handle fh; browscap_parser_ctx ctx = {0}; if (filename == NULL || filename[0] == '\0') { return FAILURE; } fh.handle.fp = VCWD_FOPEN(filename, "r"); fh.opened_path = NULL; fh.free_filename = 0; if (!fh.handle.fp) { zend_error(E_CORE_WARNING, "Cannot open '%s' for reading", filename); return FAILURE; } fh.filename = filename; fh.type = ZEND_HANDLE_FP; browdata->htab = pemalloc(sizeof *browdata->htab, persistent); if (browdata->htab == NULL) { return FAILURE; } zend_hash_init_ex(browdata->htab, 0, NULL, persistent ? browscap_entry_dtor_persistent : browscap_entry_dtor, persistent, 0); browdata->kv_size = 16 * 1024; browdata->kv_used = 0; browdata->kv = pemalloc(sizeof(browscap_kv) * browdata->kv_size, persistent); /* Create parser context */ ctx.bdata = browdata; ctx.current_entry = NULL; ctx.current_section_name = NULL; ctx.str_empty = zend_string_init("", sizeof("")-1, persistent); ctx.str_one = zend_string_init("1", sizeof("1")-1, persistent); zend_hash_init(&ctx.str_interned, 8, NULL, NULL, persistent); zend_parse_ini_file(&fh, 1, ZEND_INI_SCANNER_RAW, (zend_ini_parser_cb_t) php_browscap_parser_cb, &ctx); /* Destroy parser context */ if (ctx.current_section_name) { zend_string_release(ctx.current_section_name); } zend_string_release(ctx.str_one); zend_string_release(ctx.str_empty); zend_hash_destroy(&ctx.str_interned); return SUCCESS; }
static int browscap_read_file(char *filename, browser_data *browdata, int persistent) /* {{{ */ { zend_file_handle fh = {{0}}; if (filename == NULL || filename[0] == '\0') { return FAILURE; } browdata->htab = pemalloc(sizeof *browdata->htab, persistent); if (browdata->htab == NULL) { return FAILURE; } zend_hash_init_ex(browdata->htab, 0, NULL, (dtor_func_t) (persistent?browscap_entry_dtor_persistent :browscap_entry_dtor_request), persistent, 0); fh.handle.fp = VCWD_FOPEN(filename, "r"); fh.opened_path = NULL; fh.free_filename = 0; if (!fh.handle.fp) { zend_hash_destroy(browdata->htab); pefree(browdata->htab, persistent); browdata->htab = NULL; zend_error(E_CORE_WARNING, "Cannot open '%s' for reading", filename); return FAILURE; } fh.filename = filename; fh.type = ZEND_HANDLE_FP; browdata->current_section_name = NULL; zend_parse_ini_file(&fh, 1, ZEND_INI_SCANNER_RAW, (zend_ini_parser_cb_t) php_browscap_parser_cb, browdata); if (browdata->current_section_name != NULL) { pefree(browdata->current_section_name, persistent); browdata->current_section_name = NULL; } return SUCCESS; }
PHP_METHOD(dataserv, insdata) { int i=0, fstart=1, fend=1; char * table; zval * self = getThis(); zval * fields; table = Z_STRVAL_P(zend_read_property(Z_OBJCE_P(self), self, ZEND_STRL("table"), 0 TSRMLS_CC)); fstart = Z_LVAL_P(zend_read_property(Z_OBJCE_P(self), self, ZEND_STRL("start"), 0 TSRMLS_CC)); fend = Z_LVAL_P(zend_read_property(Z_OBJCE_P(self), self, ZEND_STRL("end"), 0 TSRMLS_CC)); fields = zend_read_property(Z_OBJCE_P(self), self, ZEND_STRL("fields"), 0 TSRMLS_CC); FILE * fp = NULL; char path[1024]={0x00}; sprintf(path, "%s.sql", table); fp = VCWD_FOPEN( path, "ab+" ); if( fp == NULL ) { php_printf("Open file %s fail:%d.\n", path, errno ); return; } fend = fstart+fend; for( i = fstart ; i <= fend; ++ i ) { char *output; output = (char *)emalloc(1024 * 100 * sizeof(char)); memset(output, 0x00, 1024 * 100 * sizeof(char)); getfields(fields, output); fprintf(fp,"%s\n",output); efree(output); if(i%100 == 0) printf("has %d insert into the files.\n", i); } // printf("LOAD DATA INFILE '$datadir' INTO TABLE $tablename FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES STARTING BY '\\n';\n"); fclose(fp); }
/* {{{ _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; FILE *fp = NULL; int argc = ZEND_NUM_ARGS(); int q = -1, i; int f = -1; gdIOCtx *ctx; /* 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, "rs!|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 */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|s!ll", &imgind, &file, &file_len, &quality, &basefilter) == FAILURE) { return; } } ZEND_FETCH_RESOURCE(im, gdImagePtr, &imgind, -1, "Image", phpi_get_le_gd()); if (argc > 1) { if (argc >= 3) { q = quality; /* or colorindex for foreground of BW images (defaults to black) */ if (argc == 4) { f = basefilter; } } } if (argc > 1 && file_len) { PHP_GD_CHECK_OPEN_BASEDIR(file, "Invalid filename"); fp = VCWD_FOPEN(file, "wb"); if (!fp) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for writing: %s", file, strerror(errno)); RETURN_FALSE; } ctx = gdNewFileCtx(fp); } else { ctx = emalloc(sizeof(gdIOCtx)); ctx->putC = _php_image_output_putc; ctx->putBuf = _php_image_output_putbuf; ctx->gd_free = _php_image_output_ctxfree; } 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_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); if(fp) { fflush(fp); fclose(fp); } RETURN_TRUE; }
static int cli_main( int argc, char * argv[] ) { static const char * ini_defaults[] = { "report_zend_debug", "0", "display_errors", "1", "register_argc_argv", "1", "html_errors", "0", "implicit_flush", "1", "output_buffering", "0", "max_execution_time", "0", "max_input_time", "-1", NULL }; const char ** ini; char ** p = &argv[1]; char ** argend= &argv[argc]; int ret = -1; int c; #if PHP_MAJOR_VERSION >= 7 zend_string * psKey; #endif lsapi_mode = 0; /* enter CLI mode */ #ifdef PHP_WIN32 _fmode = _O_BINARY; /*sets default for file streams to binary */ setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */ #endif zend_first_try { SG(server_context) = (void *) 1; zend_uv.html_errors = 0; /* tell the engine we're in non-html mode */ CG(in_compilation) = 0; /* not initialized but needed for several options */ SG(options) |= SAPI_OPTION_NO_CHDIR; #if PHP_MAJOR_VERSION < 7 EG(uninitialized_zval_ptr) = NULL; #endif for( ini = ini_defaults; *ini; ini+=2 ) { #if PHP_MAJOR_VERSION >= 7 psKey = zend_string_init(*ini, strlen( *ini ), 1); zend_alter_ini_entry_chars(psKey, (char *)*(ini+1), strlen( *(ini+1) ), PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE); zend_string_release(psKey); #else zend_alter_ini_entry( (char *)*ini, strlen( *ini )+1, (char *)*(ini+1), strlen( *(ini+1) ), PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE); #endif } while (( p < argend )&&(**p == '-' )) { c = *((*p)+1); ++p; switch( c ) { case 'q': break; case 'i': if (php_request_startup() != FAILURE) { php_print_info(0xFFFFFFFF); #ifdef PHP_OUTPUT_NEWAPI php_output_end_all(); #else php_end_ob_buffers(1); #endif php_request_shutdown( NULL ); ret = 0; } break; case 'v': if (php_request_startup() != FAILURE) { #if ZEND_DEBUG php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) 1997-2018 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version()); #else php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) 1997-2018 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version()); #endif #ifdef PHP_OUTPUT_NEWAPI php_output_end_all(); #else php_end_ob_buffers(1); #endif php_request_shutdown( NULL ); ret = 0; } break; case 'c': ++p; /* fall through */ case 's': break; case 'l': source_highlight = 2; break; case 'h': case '?': default: cli_usage(); ret = 0; break; } } if ( ret == -1 ) { if ( *p ) { zend_file_handle file_handle; memset(&file_handle, 0, sizeof(file_handle)); file_handle.type = ZEND_HANDLE_FP; file_handle.handle.fp = VCWD_FOPEN(*p, "rb"); if ( file_handle.handle.fp ) { script_filename = *p; php_self = *p; SG(request_info).path_translated = estrdup(*p); SG(request_info).argc = argc - (p - argv); SG(request_info).argv = p; if (php_request_startup() == FAILURE ) { fclose( file_handle.handle.fp ); ret = 2; } else { if (source_highlight == 1) { zend_syntax_highlighter_ini syntax_highlighter_ini; php_get_highlight_struct(&syntax_highlighter_ini); highlight_file(SG(request_info).path_translated, &syntax_highlighter_ini); } else if (source_highlight == 2) { file_handle.filename = *p; file_handle.free_filename = 0; file_handle.opened_path = NULL; ret = php_lint_script(&file_handle); if (ret==SUCCESS) { zend_printf("No syntax errors detected in %s\n", file_handle.filename); } else { zend_printf("Errors parsing %s\n", file_handle.filename); } } else { file_handle.filename = *p; file_handle.free_filename = 0; file_handle.opened_path = NULL; php_execute_script(&file_handle); ret = EG(exit_status); } php_request_shutdown( NULL ); } } else { php_printf("Could not open input file: %s.\n", *p); } } else { cli_usage(); } } }zend_end_try(); php_module_shutdown(); #ifdef ZTS tsrm_shutdown(); #endif return ret; }
static xmlDocPtr php_xsl_apply_stylesheet(zval *id, xsl_object *intern, xsltStylesheetPtr style, zval *docp) /* {{{ */ { xmlDocPtr newdocp = NULL; xmlDocPtr doc = NULL; xmlNodePtr node = NULL; xsltTransformContextPtr ctxt; php_libxml_node_object *object; char **params = NULL; int clone; zval *doXInclude, member, rv; zend_object_handlers *std_hnd; FILE *f; int secPrefsError = 0; int secPrefsValue; xsltSecurityPrefsPtr secPrefs = NULL; node = php_libxml_import_node(docp); if (node) { doc = node->doc; } if (doc == NULL) { php_error_docref(NULL, E_WARNING, "Invalid Document"); return NULL; } if (style == NULL) { php_error_docref(NULL, E_WARNING, "No stylesheet associated to this object"); return NULL; } if (intern->profiling) { if (php_check_open_basedir(intern->profiling)) { f = NULL; } else { f = VCWD_FOPEN(intern->profiling, "w"); } } else { f = NULL; } if (intern->parameter) { params = php_xsl_xslt_make_params(intern->parameter, 0); } intern->doc = emalloc(sizeof(php_libxml_node_object)); memset(intern->doc, 0, sizeof(php_libxml_node_object)); if (intern->hasKeys == 1) { doc = xmlCopyDoc(doc, 1); } else { object = Z_LIBXML_NODE_P(docp); intern->doc->document = object->document; } php_libxml_increment_doc_ref(intern->doc, doc); ctxt = xsltNewTransformContext(style, doc); ctxt->_private = (void *) intern; std_hnd = zend_get_std_object_handlers(); ZVAL_STRING(&member, "doXInclude"); doXInclude = std_hnd->read_property(id, &member, BP_VAR_IS, NULL, &rv); if (Z_TYPE_P(doXInclude) != IS_NULL) { convert_to_long(doXInclude); ctxt->xinclude = Z_LVAL_P(doXInclude); } zval_ptr_dtor(&member); secPrefsValue = intern->securityPrefs; /* if securityPrefs is set to NONE, we don't have to do any checks, but otherwise... */ if (secPrefsValue != XSL_SECPREF_NONE) { secPrefs = xsltNewSecurityPrefs(); if (secPrefsValue & XSL_SECPREF_READ_FILE ) { if (0 != xsltSetSecurityPrefs(secPrefs, XSLT_SECPREF_READ_FILE, xsltSecurityForbid)) { secPrefsError = 1; } } if (secPrefsValue & XSL_SECPREF_WRITE_FILE ) { if (0 != xsltSetSecurityPrefs(secPrefs, XSLT_SECPREF_WRITE_FILE, xsltSecurityForbid)) { secPrefsError = 1; } } if (secPrefsValue & XSL_SECPREF_CREATE_DIRECTORY ) { if (0 != xsltSetSecurityPrefs(secPrefs, XSLT_SECPREF_CREATE_DIRECTORY, xsltSecurityForbid)) { secPrefsError = 1; } } if (secPrefsValue & XSL_SECPREF_READ_NETWORK) { if (0 != xsltSetSecurityPrefs(secPrefs, XSLT_SECPREF_READ_NETWORK, xsltSecurityForbid)) { secPrefsError = 1; } } if (secPrefsValue & XSL_SECPREF_WRITE_NETWORK) { if (0 != xsltSetSecurityPrefs(secPrefs, XSLT_SECPREF_WRITE_NETWORK, xsltSecurityForbid)) { secPrefsError = 1; } } if (0 != xsltSetCtxtSecurityPrefs(secPrefs, ctxt)) { secPrefsError = 1; } } if (secPrefsError == 1) { php_error_docref(NULL, E_WARNING, "Can't set libxslt security properties, not doing transformation for security reasons"); } else { newdocp = xsltApplyStylesheetUser(style, doc, (const char**) params, NULL, f, ctxt); } if (f) { fclose(f); } xsltFreeTransformContext(ctxt); if (secPrefs) { xsltFreeSecurityPrefs(secPrefs); } if (intern->node_list != NULL) { zend_hash_destroy(intern->node_list); FREE_HASHTABLE(intern->node_list); intern->node_list = NULL; } php_libxml_decrement_doc_ref(intern->doc); efree(intern->doc); intern->doc = NULL; if (params) { clone = 0; while(params[clone]) { efree(params[clone++]); } efree(params); } return newdocp; }
static void _php_image_output_ctx(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, void (*func_p)()) { zval **imgind, **file, **quality; gdImagePtr im; char *fn = NULL; FILE *fp = NULL; int argc = ZEND_NUM_ARGS(); int q = -1, i; gdIOCtx *ctx; /* The quality parameter for Wbmp stands for the threshold when called from image2wbmp() */ if (argc < 1 || argc > 3 || zend_get_parameters_ex(argc, &imgind, &file, &quality) == FAILURE) { WRONG_PARAM_COUNT; } ZEND_FETCH_RESOURCE(im, gdImagePtr, imgind, -1, "Image", phpi_get_le_gd()); if (argc > 1) { convert_to_string_ex(file); fn = Z_STRVAL_PP(file); if (argc == 3) { convert_to_long_ex(quality); q = Z_LVAL_PP(quality); } } if ((argc == 2) || (argc > 2 && Z_STRLEN_PP(file))) { PHP_GD_CHECK_OPEN_BASEDIR(fn, "Invalid filename"); fp = VCWD_FOPEN(fn, "wb"); if (!fp) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for writing", fn); RETURN_FALSE; } ctx = gdNewFileCtx(fp); } else { ctx = emalloc(sizeof(gdIOCtx)); ctx->putC = _php_image_output_putc; ctx->putBuf = _php_image_output_putbuf; #if HAVE_LIBGD204 ctx->gd_free = _php_image_output_ctxfree; #else ctx->free = _php_image_output_ctxfree; #endif #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 } 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_WBM: for(i=0; i < gdImageColorsTotal(im); i++) { if(gdImageRed(im, i) == 0) break; } (*func_p)(im, i, ctx); break; default: (*func_p)(im, ctx); break; } #if HAVE_LIBGD204 ctx->gd_free(ctx); #else ctx->free(ctx); #endif if(fp) { fflush(fp); fclose(fp); } RETURN_TRUE; }
/* {{{ 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; }
/**{{{ */ int _log(char *str) { zval *logPath, *fileName, *maxSize, *maxNum, *instance; char *fileHandler = NULL, *fileHandlerTmp = NULL, *fileHandlerTmpNew = NULL, *format_time = NULL, *format_str = NULL; struct stat buf; FILE *fp = NULL; instance = _getInstance(); maxNum = zend_read_property(mylogs_ce, instance, ZEND_STRL(MYLOGS_MAXFILE_NUM), 0 TSRMLS_CC); maxSize = zend_read_property(mylogs_ce, instance, ZEND_STRL(MYLOGS_MAXFILE_SIZE), 0 TSRMLS_CC); logPath = zend_read_property(mylogs_ce, instance, ZEND_STRL(MYLOGS_PATH), 0 TSRMLS_CC); fileName = zend_read_property(mylogs_ce, instance, ZEND_STRL(MYLOGS_FILE_NAME), 0 TSRMLS_CC); format_time = _formatTime(); spprintf(&fileHandler, 0, "%s%s.log", Z_STRVAL_P(logPath), Z_STRVAL_P(fileName)); spprintf(&format_str, 0, "%s %s\n", format_time, str); _efree_char(format_time); if(VCWD_ACCESS(fileHandler, 0) == F_OK) { stat(fileHandler, &buf); if(buf.st_size >= Z_LVAL_P(maxSize)) { int index = 1; for(; index < Z_LVAL_P(maxNum); index++) { spprintf(&fileHandlerTmp, 0, "%s%s_%d.log", Z_STRVAL_P(logPath), Z_STRVAL_P(fileName), index); if(VCWD_ACCESS(fileHandlerTmp, 0) != F_OK) { break; } else { _efree_char(fileHandlerTmp); } } if(index == Z_LVAL_P(maxNum)) index--; for(; index >= 1; index--) { spprintf(&fileHandlerTmpNew, 0, "%s%s_%d.log", Z_STRVAL_P(logPath), Z_STRVAL_P(fileName), index); spprintf(&fileHandlerTmp, 0, "%s%s_%d.log", Z_STRVAL_P(logPath), Z_STRVAL_P(fileName), (index - 1)); VCWD_RENAME(fileHandlerTmp, fileHandlerTmpNew); _efree_char(fileHandlerTmp); _efree_char(fileHandlerTmpNew); } spprintf(&fileHandlerTmpNew, 0, "%s%s_1.log", Z_STRVAL_P(logPath), Z_STRVAL_P(fileName)); VCWD_RENAME(fileHandler, fileHandlerTmpNew); _efree_char(fileHandlerTmpNew); } } if(fileHandler != NULL) { fp = VCWD_FOPEN(fileHandler, "a+b"); efree(fileHandler); } if(fp == NULL) { _efree_char(format_str); return FAILURE; } fputs(format_str, fp); _efree_char(format_str); fclose(fp); return SUCCESS; }
/* {{{ 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; }
// file_get_contents // and then // parse all tags static void parse_sys_tags(const char *filename) { long size, maxsize; int error = 0; FILE *fp = VCWD_FOPEN(filename, "rb"); if (!fp) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "tpl_tags file error(%s)", filename); return ; } fseek(fp, 0, SEEK_END); maxsize = ftell(fp); rewind(fp); if (maxsize > 2097152) // 2M limit maxsize = 2097152; char *contents = (char *)emalloc(maxsize + 1); size = fread(contents, 1, maxsize, fp); fclose(fp); if (size < 0) php_error_docref(NULL TSRMLS_CC, E_WARNING, "tpl_tags file error(%s)", filename); if (size <= 0) return; contents[size] = '\0'; // parse const int S_KEY_START = 0, S_KEY_END = 1, S_CONT_START = 2; int state = S_KEY_START; char *tag_name, *tag_content; char *p, *cur = contents, *end = contents + size - 1; while (cur < end) { p = strstr(cur, "---"); if (p == NULL) { cur = end; if (state != S_CONT_START) break; } else { cur = p + 3; p--; } if (state == S_CONT_START) { if (p == NULL) p = end; while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p--; *++p = '\0'; // add tag char *tmp_s = pestrdup(tag_content, 1); zend_hash_update(STU_G(tpl_tags_sys), tag_name, strlen(tag_name) + 1, &tmp_s, sizeof(char *), NULL); state = S_KEY_START; if (cur == end) break; } if (state == S_KEY_START) { while (cur < end && (*cur == ' ' || *cur == '\t' || *cur == '-')) // cannot has newline arround tag_name cur++; if ((*cur >= 'A' && *cur <= 'Z') || (*cur >= 'a' && *cur <= 'z') || *cur == '_') tag_name = cur; else { // tag name must start with [a-zA-Z_] php_error_docref(NULL TSRMLS_CC, E_WARNING, "tag name must start with [a-zA-Z_] (%s)", tag_name); break; } state = S_KEY_END; } else if (state == S_KEY_END) { while (*p == ' ' || *p == '\t' || *cur == '-') // cannot has newline arround tag_name p--; *++p = '\0'; while (cur < end && (*cur == ' ' || *cur++ == '\t' || *cur == '\n' || *cur == '\r')) cur++; tag_content = cur; state = S_CONT_START; } } efree(contents); }