repo
stringlengths 1
152
⌀ | file
stringlengths 14
221
| code
stringlengths 501
25k
| file_length
int64 501
25k
| avg_line_length
float64 20
99.5
| max_line_length
int64 21
134
| extension_type
stringclasses 2
values |
---|---|---|---|---|---|---|
php-src
|
php-src-master/main/main_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: aae9f04a1ef2d0d2698c2e3a617594f0bf3d4cd5 */
static void register_main_symbols(int module_number)
{
REGISTER_STRING_CONSTANT("PHP_VERSION", PHP_VERSION, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_MAJOR_VERSION", PHP_MAJOR_VERSION, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_MINOR_VERSION", PHP_MINOR_VERSION, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_RELEASE_VERSION", PHP_RELEASE_VERSION, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PHP_EXTRA_VERSION", PHP_EXTRA_VERSION, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_VERSION_ID", PHP_VERSION_ID, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_ZTS", PHP_ZTS, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_DEBUG", PHP_DEBUG, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PHP_OS", PHP_OS_STR, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PHP_OS_FAMILY", PHP_OS_FAMILY, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("DEFAULT_INCLUDE_PATH", PHP_INCLUDE_PATH, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PEAR_INSTALL_DIR", PEAR_INSTALLDIR, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PEAR_EXTENSION_DIR", PHP_EXTENSION_DIR, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PHP_EXTENSION_DIR", PHP_EXTENSION_DIR, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PHP_PREFIX", PHP_PREFIX, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PHP_BINDIR", PHP_BINDIR, CONST_PERSISTENT);
#if !defined(PHP_WIN32)
REGISTER_STRING_CONSTANT("PHP_MANDIR", PHP_MANDIR, CONST_PERSISTENT);
#endif
REGISTER_STRING_CONSTANT("PHP_LIBDIR", PHP_LIBDIR, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PHP_DATADIR", PHP_DATADIR, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PHP_SYSCONFDIR", PHP_SYSCONFDIR, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PHP_LOCALSTATEDIR", PHP_LOCALSTATEDIR, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PHP_CONFIG_FILE_PATH", PHP_CONFIG_FILE_PATH, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PHP_CONFIG_FILE_SCAN_DIR", PHP_CONFIG_FILE_SCAN_DIR, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PHP_SHLIB_SUFFIX", PHP_SHLIB_SUFFIX, CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PHP_EOL", PHP_EOL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_MAXPATHLEN", MAXPATHLEN, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_INT_MAX", ZEND_LONG_MAX, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_INT_MIN", ZEND_LONG_MIN, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_INT_SIZE", SIZEOF_ZEND_LONG, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_FD_SETSIZE", FD_SETSIZE, CONST_PERSISTENT);
REGISTER_DOUBLE_CONSTANT("PHP_FLOAT_DIG", DBL_DIG, CONST_PERSISTENT);
REGISTER_DOUBLE_CONSTANT("PHP_FLOAT_EPSILON", DBL_EPSILON, CONST_PERSISTENT);
REGISTER_DOUBLE_CONSTANT("PHP_FLOAT_MAX", DBL_MAX, CONST_PERSISTENT);
REGISTER_DOUBLE_CONSTANT("PHP_FLOAT_MIN", DBL_MIN, CONST_PERSISTENT);
#if defined(PHP_WIN32)
REGISTER_LONG_CONSTANT("PHP_WINDOWS_VERSION_MAJOR", EG(windows_version_info).dwMajorVersion, CONST_PERSISTENT);
#endif
#if defined(PHP_WIN32)
REGISTER_LONG_CONSTANT("PHP_WINDOWS_VERSION_MINOR", EG(windows_version_info).dwMinorVersion, CONST_PERSISTENT);
#endif
#if defined(PHP_WIN32)
REGISTER_LONG_CONSTANT("PHP_WINDOWS_VERSION_BUILD", EG(windows_version_info).dwBuildNumber, CONST_PERSISTENT);
#endif
#if defined(PHP_WIN32)
REGISTER_LONG_CONSTANT("PHP_WINDOWS_VERSION_PLATFORM", EG(windows_version_info).dwPlatformId, CONST_PERSISTENT);
#endif
#if defined(PHP_WIN32)
REGISTER_LONG_CONSTANT("PHP_WINDOWS_VERSION_SP_MAJOR", EG(windows_version_info).wServicePackMajor, CONST_PERSISTENT);
#endif
#if defined(PHP_WIN32)
REGISTER_LONG_CONSTANT("PHP_WINDOWS_VERSION_SP_MINOR", EG(windows_version_info).wServicePackMinor, CONST_PERSISTENT);
#endif
#if defined(PHP_WIN32)
REGISTER_LONG_CONSTANT("PHP_WINDOWS_VERSION_SUITEMASK", EG(windows_version_info).wSuiteMask, CONST_PERSISTENT);
#endif
#if defined(PHP_WIN32)
REGISTER_LONG_CONSTANT("PHP_WINDOWS_VERSION_PRODUCTTYPE", EG(windows_version_info).wProductType, CONST_PERSISTENT);
#endif
#if defined(PHP_WIN32)
REGISTER_LONG_CONSTANT("PHP_WINDOWS_NT_DOMAIN_CONTROLLER", VER_NT_DOMAIN_CONTROLLER, CONST_PERSISTENT);
#endif
#if defined(PHP_WIN32)
REGISTER_LONG_CONSTANT("PHP_WINDOWS_NT_SERVER", VER_NT_SERVER, CONST_PERSISTENT);
#endif
#if defined(PHP_WIN32)
REGISTER_LONG_CONSTANT("PHP_WINDOWS_NT_WORKSTATION", VER_NT_WORKSTATION, CONST_PERSISTENT);
#endif
REGISTER_LONG_CONSTANT("PHP_OUTPUT_HANDLER_START", PHP_OUTPUT_HANDLER_START, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_OUTPUT_HANDLER_WRITE", PHP_OUTPUT_HANDLER_WRITE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_OUTPUT_HANDLER_FLUSH", PHP_OUTPUT_HANDLER_FLUSH, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_OUTPUT_HANDLER_CLEAN", PHP_OUTPUT_HANDLER_CLEAN, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_OUTPUT_HANDLER_FINAL", PHP_OUTPUT_HANDLER_FINAL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_OUTPUT_HANDLER_CONT", PHP_OUTPUT_HANDLER_WRITE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_OUTPUT_HANDLER_END", PHP_OUTPUT_HANDLER_FINAL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_OUTPUT_HANDLER_CLEANABLE", PHP_OUTPUT_HANDLER_CLEANABLE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_OUTPUT_HANDLER_FLUSHABLE", PHP_OUTPUT_HANDLER_FLUSHABLE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_OUTPUT_HANDLER_REMOVABLE", PHP_OUTPUT_HANDLER_REMOVABLE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_OUTPUT_HANDLER_STDFLAGS", PHP_OUTPUT_HANDLER_STDFLAGS, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_OUTPUT_HANDLER_STARTED", PHP_OUTPUT_HANDLER_STARTED, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_OUTPUT_HANDLER_DISABLED", PHP_OUTPUT_HANDLER_DISABLED, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("UPLOAD_ERR_OK", PHP_UPLOAD_ERROR_OK, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("UPLOAD_ERR_INI_SIZE", PHP_UPLOAD_ERROR_A, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("UPLOAD_ERR_FORM_SIZE", PHP_UPLOAD_ERROR_B, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("UPLOAD_ERR_PARTIAL", PHP_UPLOAD_ERROR_C, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("UPLOAD_ERR_NO_FILE", PHP_UPLOAD_ERROR_D, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("UPLOAD_ERR_NO_TMP_DIR", PHP_UPLOAD_ERROR_E, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("UPLOAD_ERR_CANT_WRITE", PHP_UPLOAD_ERROR_F, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("UPLOAD_ERR_EXTENSION", PHP_UPLOAD_ERROR_X, CONST_PERSISTENT);
}
| 6,349 | 63.141414 | 118 |
h
|
php-src
|
php-src-master/main/php_compat.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: |
+----------------------------------------------------------------------+
*/
#ifndef PHP_COMPAT_H
#define PHP_COMPAT_H
#ifdef PHP_WIN32
#include "config.w32.h"
#else
#include <php_config.h>
#endif
#if defined(HAVE_BUNDLED_PCRE) || !defined(PHP_VERSION)
#define pcre2_jit_callback_8 php_pcre2_jit_callback
#define pcre2_callout_enumerate_8 php_pcre2_callout_enumerate
#define pcre2_code_copy_8 php_pcre2_code_copy
#define pcre2_code_copy_with_tables_8 php_pcre2_code_copy_with_tables
#define pcre2_code_free_8 php_pcre2_code_free
#define pcre2_compile_8 php_pcre2_compile
#define pcre2_compile_context_copy_8 php_pcre2_compile_context_copy
#define pcre2_compile_context_create_8 php_pcre2_compile_context_create
#define pcre2_compile_context_free_8 php_pcre2_compile_context_free
#define pcre2_config_8 php_pcre2_config
#define pcre2_convert_context_copy_8 php_pcre2_convert_context_copy
#define pcre2_convert_context_create_8 php_pcre2_convert_context_create
#define pcre2_convert_context_free_8 php_pcre2_convert_context_free
#define pcre2_dfa_match_8 php_pcre2_dfa_match
#define pcre2_general_context_copy_8 php_pcre2_general_context_copy
#define pcre2_general_context_create_8 php_pcre2_general_context_create
#define pcre2_general_context_free_8 php_pcre2_general_context_free
#define pcre2_get_error_message_8 php_pcre2_get_error_message
#define pcre2_get_mark_8 php_pcre2_get_mark
#define pcre2_get_ovector_pointer_8 php_pcre2_get_ovector_pointer
#define pcre2_get_ovector_count_8 php_pcre2_get_ovector_count
#define pcre2_get_startchar_8 php_pcre2_get_startchar
#define pcre2_jit_compile_8 php_pcre2_jit_compile
#define pcre2_jit_match_8 php_pcre2_jit_match
#define pcre2_jit_free_unused_memory_8 php_pcre2_jit_free_unused_memory
#define pcre2_jit_stack_assign_8 php_pcre2_jit_stack_assign
#define pcre2_jit_stack_create_8 php_pcre2_jit_stack_create
#define pcre2_jit_stack_free_8 php_pcre2_jit_stack_free
#define pcre2_maketables_8 php_pcre2_maketables
#define pcre2_match_8 php_pcre2_match
#define pcre2_match_context_copy_8 php_pcre2_match_context_copy
#define pcre2_match_context_create_8 php_pcre2_match_context_create
#define pcre2_match_context_free_8 php_pcre2_match_context_free
#define pcre2_match_data_create_8 php_pcre2_match_data_create
#define pcre2_match_data_create_from_pattern_8 php_pcre2_match_data_create_from_pattern
#define pcre2_match_data_free_8 php_pcre2_match_data_free
#define pcre2_pattern_info_8 php_pcre2_pattern_info
#define pcre2_serialize_decode_8 php_pcre2_serialize_decode
#define pcre2_serialize_encode_8 php_pcre2_serialize_encode
#define pcre2_serialize_free_8 php_pcre2_serialize_free
#define pcre2_serialize_get_number_of_codes_8 php_pcre2_serialize_get_number_of_codes
#define pcre2_set_bsr_8 php_pcre2_set_bsr
#define pcre2_set_callout_8 php_pcre2_set_callout
#define pcre2_set_character_tables_8 php_pcre2_set_character_tables
#define pcre2_set_compile_extra_options_8 php_pcre2_set_compile_extra_options
#define pcre2_set_compile_recursion_guard_8 php_pcre2_set_compile_recursion_guard
#define pcre2_set_depth_limit_8 php_pcre2_set_depth_limit
#define pcre2_set_glob_escape_8 php_pcre2_set_glob_escape
#define pcre2_set_glob_separator_8 php_pcre2_set_glob_separator
#define pcre2_set_heap_limit_8 php_pcre2_set_heap_limit
#define pcre2_set_match_limit_8 php_pcre2_set_match_limit
#define pcre2_set_max_pattern_length_8 php_pcre2_set_max_pattern_length
#define pcre2_set_newline_8 php_pcre2_set_newline
#define pcre2_set_parens_nest_limit_8 php_pcre2_set_parens_nest_limit
#define pcre2_set_offset_limit_8 php_pcre2_set_offset_limit
#define pcre2_substitute_8 php_pcre2_substitute
#define pcre2_substring_copy_byname_8 php_pcre2_substring_copy_byname
#define pcre2_substring_copy_bynumber_8 php_pcre2_substring_copy_bynumber
#define pcre2_substring_free_8 php_pcre2_substring_free
#define pcre2_substring_get_byname_8 php_pcre2_substring_get_byname
#define pcre2_substring_get_bynumber_8 php_pcre2_substring_get_bynumber
#define pcre2_substring_length_byname_8 php_pcre2_substring_length_byname
#define pcre2_substring_length_bynumber_8 php_pcre2_substring_length_bynumber
#define pcre2_substring_list_get_8 php_pcre2_substring_list_get
#define pcre2_substring_list_free_8 php_pcre2_substring_list_free
#define pcre2_substring_nametable_scan_8 php_pcre2_substring_nametable_scan
#define pcre2_substring_number_from_name_8 php_pcre2_substring_number_from_name
#define pcre2_set_recursion_limit_8 php_pcre2_set_recursion_limit
#define pcre2_set_recursion_memory_management_8 php_pcre2_set_recursion_memory_management
#endif
#define lookup php_lookup
#define hashTableInit php_hashTableInit
#define hashTableDestroy php_hashTableDestroy
#define hashTableIterInit php_hashTableIterInit
#define hashTableIterNext php_hashTableIterNext
#if defined(HAVE_LIBXML) && (defined(HAVE_XML) || defined(HAVE_XMLRPC)) && !defined(HAVE_LIBEXPAT)
#define XML_DefaultCurrent php_XML_DefaultCurrent
#define XML_ErrorString php_XML_ErrorString
#define XML_ExpatVersion php_XML_ExpatVersion
#define XML_ExpatVersionInfo php_XML_ExpatVersionInfo
#define XML_ExternalEntityParserCreate php_XML_ExternalEntityParserCreate
#define XML_GetBase php_XML_GetBase
#define XML_GetBuffer php_XML_GetBuffer
#define XML_GetCurrentByteCount php_XML_GetCurrentByteCount
#define XML_GetCurrentByteIndex php_XML_GetCurrentByteIndex
#define XML_GetCurrentColumnNumber php_XML_GetCurrentColumnNumber
#define XML_GetCurrentLineNumber php_XML_GetCurrentLineNumber
#define XML_GetErrorCode php_XML_GetErrorCode
#define XML_GetIdAttributeIndex php_XML_GetIdAttributeIndex
#define XML_GetInputContext php_XML_GetInputContext
#define XML_GetSpecifiedAttributeCount php_XML_GetSpecifiedAttributeCount
#define XmlGetUtf16InternalEncodingNS php_XmlGetUtf16InternalEncodingNS
#define XmlGetUtf16InternalEncoding php_XmlGetUtf16InternalEncoding
#define XmlGetUtf8InternalEncodingNS php_XmlGetUtf8InternalEncodingNS
#define XmlGetUtf8InternalEncoding php_XmlGetUtf8InternalEncoding
#define XmlInitEncoding php_XmlInitEncoding
#define XmlInitEncodingNS php_XmlInitEncodingNS
#define XmlInitUnknownEncoding php_XmlInitUnknownEncoding
#define XmlInitUnknownEncodingNS php_XmlInitUnknownEncodingNS
#define XML_ParseBuffer php_XML_ParseBuffer
#define XML_Parse php_XML_Parse
#define XML_ParserCreate_MM php_XML_ParserCreate_MM
#define XML_ParserCreateNS php_XML_ParserCreateNS
#define XML_ParserCreate php_XML_ParserCreate
#define XML_ParserFree php_XML_ParserFree
#define XmlParseXmlDecl php_XmlParseXmlDecl
#define XmlParseXmlDeclNS php_XmlParseXmlDeclNS
#define XmlPrologStateInitExternalEntity php_XmlPrologStateInitExternalEntity
#define XmlPrologStateInit php_XmlPrologStateInit
#define XML_SetAttlistDeclHandler php_XML_SetAttlistDeclHandler
#define XML_SetBase php_XML_SetBase
#define XML_SetCdataSectionHandler php_XML_SetCdataSectionHandler
#define XML_SetCharacterDataHandler php_XML_SetCharacterDataHandler
#define XML_SetCommentHandler php_XML_SetCommentHandler
#define XML_SetDefaultHandlerExpand php_XML_SetDefaultHandlerExpand
#define XML_SetDefaultHandler php_XML_SetDefaultHandler
#define XML_SetDoctypeDeclHandler php_XML_SetDoctypeDeclHandler
#define XML_SetElementDeclHandler php_XML_SetElementDeclHandler
#define XML_SetElementHandler php_XML_SetElementHandler
#define XML_SetEncoding php_XML_SetEncoding
#define XML_SetEndCdataSectionHandler php_XML_SetEndCdataSectionHandler
#define XML_SetEndDoctypeDeclHandler php_XML_SetEndDoctypeDeclHandler
#define XML_SetEndElementHandler php_XML_SetEndElementHandler
#define XML_SetEndNamespaceDeclHandler php_XML_SetEndNamespaceDeclHandler
#define XML_SetEntityDeclHandler php_XML_SetEntityDeclHandler
#define XML_SetExternalEntityRefHandlerArg php_XML_SetExternalEntityRefHandlerArg
#define XML_SetExternalEntityRefHandler php_XML_SetExternalEntityRefHandler
#define XML_SetNamespaceDeclHandler php_XML_SetNamespaceDeclHandler
#define XML_SetNotationDeclHandler php_XML_SetNotationDeclHandler
#define XML_SetNotStandaloneHandler php_XML_SetNotStandaloneHandler
#define XML_SetParamEntityParsing php_XML_SetParamEntityParsing
#define XML_SetProcessingInstructionHandler php_XML_SetProcessingInstructionHandler
#define XML_SetReturnNSTriplet php_XML_SetReturnNSTriplet
#define XML_SetStartCdataSectionHandler php_XML_SetStartCdataSectionHandler
#define XML_SetStartDoctypeDeclHandler php_XML_SetStartDoctypeDeclHandler
#define XML_SetStartElementHandler php_XML_SetStartElementHandler
#define XML_SetStartNamespaceDeclHandler php_XML_SetStartNamespaceDeclHandler
#define XML_SetUnknownEncodingHandler php_XML_SetUnknownEncodingHandler
#define XML_SetUnparsedEntityDeclHandler php_XML_SetUnparsedEntityDeclHandler
#define XML_SetUserData php_XML_SetUserData
#define XML_SetXmlDeclHandler php_XML_SetXmlDeclHandler
#define XmlSizeOfUnknownEncoding php_XmlSizeOfUnknownEncoding
#define XML_UseParserAsHandlerArg php_XML_UseParserAsHandlerArg
#define XmlUtf16Encode php_XmlUtf16Encode
#define XmlUtf8Encode php_XmlUtf8Encode
#define XML_FreeContentModel php_XML_FreeContentModel
#define XML_MemMalloc php_XML_MemMalloc
#define XML_MemRealloc php_XML_MemRealloc
#define XML_MemFree php_XML_MemFree
#define XML_UseForeignDTD php_XML_UseForeignDTD
#define XML_GetFeatureList php_XML_GetFeatureList
#define XML_ParserReset php_XML_ParserReset
#ifdef HAVE_GD_BUNDLED
#define any2eucjp php_gd_any2eucjp
#define createwbmp php_gd_createwbmp
#define empty_output_buffer php_gd_empty_output_buffer
#define fill_input_buffer php_gd_fill_input_buffer
#define freewbmp php_gd_freewbmp
#define gdAlphaBlend php_gd_gdAlphaBlend
#define gdCompareInt php_gd_gdCompareInt
#define gdCosT php_gd_gdCosT
#define gdCtxPrintf php_gd_gdCtxPrintf
#define gdDPExtractData php_gd_gdDPExtractData
#define gdFontGetGiant php_gd_gdFontGetGiant
#define gdFontGetLarge php_gd_gdFontGetLarge
#define gdFontGetMediumBold php_gd_gdFontGetMediumBold
#define gdFontGetSmall php_gd_gdFontGetSmall
#define gdFontGetTiny php_gd_gdFontGetTiny
#define gdFontGiant php_gd_gdFontGiant
#define gdFontGiantData php_gd_gdFontGiantData
#define gdFontGiantRep php_gd_gdFontGiantRep
#define gdFontLarge php_gd_gdFontLarge
#define gdFontLargeData php_gd_gdFontLargeData
#define gdFontLargeRep php_gd_gdFontLargeRep
#define gdFontMediumBold php_gd_gdFontMediumBold
#define gdFontMediumBoldData php_gd_gdFontMediumBoldData
#define gdFontMediumBoldRep php_gd_gdFontMediumBoldRep
#define gdFontSmall php_gd_gdFontSmall
#define gdFontSmallData php_gd_gdFontSmallData
#define gdFontSmallRep php_gd_gdFontSmallRep
#define gdFontTiny php_gd_gdFontTiny
#define gdFontTinyData php_gd_gdFontTinyData
#define gdFontTinyRep php_gd_gdFontTinyRep
#define gdGetBuf php_gd_gdGetBuf
#define gdGetByte php_gd_gdGetByte
#define gdGetC php_gd_gdGetC
#define _gdGetColors php_gd__gdGetColors
#define gd_getin php_gd_gd_getin
#define gdGetInt php_gd_gdGetInt
#define gdGetWord php_gd_gdGetWord
#define gdImageAABlend php_gd_gdImageAABlend
#define gdImageAALine php_gd_gdImageAALine
#define gdImageAlphaBlending php_gd_gdImageAlphaBlending
#define gdImageAntialias php_gd_gdImageAntialias
#define gdImageArc php_gd_gdImageArc
#define gdImageBrightness php_gd_gdImageBrightness
#define gdImageChar php_gd_gdImageChar
#define gdImageCharUp php_gd_gdImageCharUp
#define gdImageColor php_gd_gdImageColor
#define gdImageColorAllocate php_gd_gdImageColorAllocate
#define gdImageColorAllocateAlpha php_gd_gdImageColorAllocateAlpha
#define gdImageColorClosest php_gd_gdImageColorClosest
#define gdImageColorClosestAlpha php_gd_gdImageColorClosestAlpha
#define gdImageColorClosestHWB php_gd_gdImageColorClosestHWB
#define gdImageColorDeallocate php_gd_gdImageColorDeallocate
#define gdImageColorExact php_gd_gdImageColorExact
#define gdImageColorExactAlpha php_gd_gdImageColorExactAlpha
#define gdImageColorMatch php_gd_gdImageColorMatch
#define gdImageColorResolve php_gd_gdImageColorResolve
#define gdImageColorResolveAlpha php_gd_gdImageColorResolveAlpha
#define gdImageColorTransparent php_gd_gdImageColorTransparent
#define gdImageCompare php_gd_gdImageCompare
#define gdImageContrast php_gd_gdImageContrast
#define gdImageConvolution php_gd_gdImageConvolution
#define gdImageCopy php_gd_gdImageCopy
#define gdImageCopyMerge php_gd_gdImageCopyMerge
#define gdImageCopyMergeGray php_gd_gdImageCopyMergeGray
#define gdImageCopyResampled php_gd_gdImageCopyResampled
#define gdImageCopyResized php_gd_gdImageCopyResized
#define gdImageCreate php_gd_gdImageCreate
#define gdImageCreateFromGd php_gd_gdImageCreateFromGd
#define gdImageCreateFromGd2 php_gd_gdImageCreateFromGd2
#define gdImageCreateFromGd2Ctx php_gd_gdImageCreateFromGd2Ctx
#define gdImageCreateFromGd2Part php_gd_gdImageCreateFromGd2Part
#define gdImageCreateFromGd2PartCtx php_gd_gdImageCreateFromGd2PartCtx
#define gdImageCreateFromGd2PartPtr php_gd_gdImageCreateFromGd2PartPtr
#define gdImageCreateFromGd2Ptr php_gd_gdImageCreateFromGd2Ptr
#define gdImageCreateFromGdCtx php_gd_gdImageCreateFromGdCtx
#define gdImageCreateFromGdPtr php_gd_gdImageCreateFromGdPtr
#define gdImageCreateFromGif php_gd_gdImageCreateFromGif
#define gdImageCreateFromGifCtx php_gd_gdImageCreateFromGifCtx
#define gdImageCreateFromGifSource php_gd_gdImageCreateFromGifSource
#define gdImageCreateFromJpeg php_gd_gdImageCreateFromJpeg
#define gdImageCreateFromJpegCtx php_gd_gdImageCreateFromJpegCtx
#define gdImageCreateFromJpegPtr php_gd_gdImageCreateFromJpegPtr
#define gdImageCreateFromPng php_gd_gdImageCreateFromPng
#define gdImageCreateFromPngCtx php_gd_gdImageCreateFromPngCtx
#define gdImageCreateFromPngPtr php_gd_gdImageCreateFromPngPtr
#define gdImageCreateFromPngSource php_gd_gdImageCreateFromPngSource
#define gdImageCreateFromWBMP php_gd_gdImageCreateFromWBMP
#define gdImageCreateFromWBMPCtx php_gd_gdImageCreateFromWBMPCtx
#define gdImageCreateFromWBMPPtr php_gd_gdImageCreateFromWBMPPtr
#define gdImageCreateFromXbm php_gd_gdImageCreateFromXbm
#define gdImageCreatePaletteFromTrueColor php_gd_gdImageCreatePaletteFromTrueColor
#define gdImageCreateTrueColor php_gd_gdImageCreateTrueColor
#define gdImageDashedLine php_gd_gdImageDashedLine
#define gdImageDestroy php_gd_gdImageDestroy
#define gdImageEdgeDetectQuick php_gd_gdImageEdgeDetectQuick
#define gdImageEllipse php_gd_gdImageEllipse
#define gdImageEmboss php_gd_gdImageEmboss
#define gdImageFill php_gd_gdImageFill
#define gdImageFilledArc php_gd_gdImageFilledArc
#define gdImageFilledEllipse php_gd_gdImageFilledEllipse
#define gdImageFilledPolygon php_gd_gdImageFilledPolygon
#define gdImageFilledRectangle php_gd_gdImageFilledRectangle
#define _gdImageFillTiled php_gd__gdImageFillTiled
#define gdImageFillToBorder php_gd_gdImageFillToBorder
#define gdImageGaussianBlur php_gd_gdImageGaussianBlur
#define gdImageGd php_gd_gdImageGd
#define gdImageGd2 php_gd_gdImageGd2
#define gdImageGd2Ptr php_gd_gdImageGd2Ptr
#define gdImageGdPtr php_gd_gdImageGdPtr
#define gdImageGetClip php_gd_gdImageGetClip
#define gdImageGetPixel php_gd_gdImageGetPixel
#define gdImageGetTrueColorPixel php_gd_gdImageGetTrueColorPixel
#define gdImageGif php_gd_gdImageGif
#define gdImageGifCtx php_gd_gdImageGifCtx
#define gdImageGifPtr php_gd_gdImageGifPtr
#define gdImageGrayScale php_gd_gdImageGrayScale
#define gdImageInterlace php_gd_gdImageInterlace
#define gdImageJpeg php_gd_gdImageJpeg
#define gdImageJpegCtx php_gd_gdImageJpegCtx
#define gdImageJpegPtr php_gd_gdImageJpegPtr
#define gdImageLine php_gd_gdImageLine
#define gdImageMeanRemoval php_gd_gdImageMeanRemoval
#define gdImageNegate php_gd_gdImageNegate
#define gdImagePaletteCopy php_gd_gdImagePaletteCopy
#define gdImagePng php_gd_gdImagePng
#define gdImagePngCtx php_gd_gdImagePngCtx
#define gdImagePngCtxEx php_gd_gdImagePngCtxEx
#define gdImagePngEx php_gd_gdImagePngEx
#define gdImagePngPtr php_gd_gdImagePngPtr
#define gdImagePngPtrEx php_gd_gdImagePngPtrEx
#define gdImagePngToSink php_gd_gdImagePngToSink
#define gdImagePolygon php_gd_gdImagePolygon
#define gdImageRectangle php_gd_gdImageRectangle
#define gdImageRotate php_gd_gdImageRotate
#define gdImageRotate180 php_gd_gdImageRotate180
#define gdImageRotate270 php_gd_gdImageRotate270
#define gdImageRotate45 php_gd_gdImageRotate45
#define gdImageRotate90 php_gd_gdImageRotate90
#define gdImageSaveAlpha php_gd_gdImageSaveAlpha
#define gdImageSelectiveBlur php_gd_gdImageSelectiveBlur
#define gdImageSetAntiAliased php_gd_gdImageSetAntiAliased
#define gdImageSetAntiAliasedDontBlend php_gd_gdImageSetAntiAliasedDontBlend
#define gdImageSetBrush php_gd_gdImageSetBrush
#define gdImageSetClip php_gd_gdImageSetClip
#define gdImageSetPixel php_gd_gdImageSetPixel
#define gdImageSetStyle php_gd_gdImageSetStyle
#define gdImageSetThickness php_gd_gdImageSetThickness
#define gdImageSetTile php_gd_gdImageSetTile
#define gdImageSkewX php_gd_gdImageSkewX
#define gdImageSkewY php_gd_gdImageSkewY
#define gdImageSmooth php_gd_gdImageSmooth
#define gdImageString php_gd_gdImageString
#define gdImageString16 php_gd_gdImageString16
#define gdImageStringFT php_gd_gdImageStringFT
#define gdImageStringFTEx php_gd_gdImageStringFTEx
#define gdImageStringTTF php_gd_gdImageStringTTF
#define gdImageStringUp php_gd_gdImageStringUp
#define gdImageStringUp16 php_gd_gdImageStringUp16
#define gdImageTrueColorToPalette php_gd_gdImageTrueColorToPalette
#define gdImageWBMP php_gd_gdImageWBMP
#define gdImageWBMPCtx php_gd_gdImageWBMPCtx
#define gdImageWBMPPtr php_gd_gdImageWBMPPtr
#define gdImageXbmCtx php_gd_gdImageXbmCtx
#define gdNewDynamicCtx php_gd_gdNewDynamicCtx
#define gdNewDynamicCtxEx php_gd_gdNewDynamicCtxEx
#define gdNewFileCtx php_gd_gdNewFileCtx
#define gdNewSSCtx php_gd_gdNewSSCtx
#define gdPutBuf php_gd_gdPutBuf
#define gdPutC php_gd_gdPutC
#define _gdPutColors php_gd__gdPutColors
#define gdPutInt php_gd_gdPutInt
#define gd_putout php_gd_gd_putout
#define gdPutWord php_gd_gdPutWord
#define gdSeek php_gd_gdSeek
#define gdSinT php_gd_gdSinT
#define gd_strtok_r php_gd_gd_strtok_r
#define gdTell php_gd_gdTell
#define getmbi php_gd_getmbi
#define init_destination php_gd_init_destination
#define init_source php_gd_init_source
#define jpeg_gdIOCtx_dest php_gd_jpeg_gdIOCtx_dest
#define jpeg_gdIOCtx_src php_gd_jpeg_gdIOCtx_src
#define lsqrt php_gd_lsqrt
#define printwbmp php_gd_printwbmp
#define Putchar php_gd_Putchar
#define putmbi php_gd_putmbi
#define Putword php_gd_Putword
#define readwbmp php_gd_readwbmp
#define skipheader php_gd_skipheader
#define skip_input_data php_gd_skip_input_data
#define term_destination php_gd_term_destination
#define term_source php_gd_term_source
#define writewbmp php_gd_writewbmp
#define ZeroDataBlock php_gd_ZeroDataBlock
#define gdCacheCreate php_gd_gdCacheCreate
#define gdCacheDelete php_gd_gdCacheDelete
#define gdCacheGet php_gd_gdCacheGet
#define gdFontCacheSetup php_gd_gdFontCacheSetup
#define gdFontCacheShutdown php_gd_gdFontCacheShutdown
#define gdFreeFontCache php_gd_gdFreeFontCache
#endif /* HAVE_GD_BUNDLED */
/* Define to specify how much context to retain around the current parse
point. */
#define XML_CONTEXT_BYTES 1024
/* Define to make parameter entity parsing functionality available. */
#define XML_DTD 1
/* Define to make XML Namespaces functionality available. */
#define XML_NS 1
#endif
#ifdef PHP_EXPORTS
#define PCRE_STATIC
#endif
#endif
| 20,130 | 49.201995 | 98 |
h
|
php-src
|
php-src-master/main/php_content_types.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "SAPI.h"
#include "rfc1867.h"
#include "php_content_types.h"
/* {{{ php_post_entries[] */
static const sapi_post_entry php_post_entries[] = {
{ DEFAULT_POST_CONTENT_TYPE, sizeof(DEFAULT_POST_CONTENT_TYPE)-1, sapi_read_standard_form_data, php_std_post_handler },
{ MULTIPART_CONTENT_TYPE, sizeof(MULTIPART_CONTENT_TYPE)-1, NULL, rfc1867_post_handler },
{ NULL, 0, NULL, NULL }
};
/* }}} */
/* {{{ SAPI_POST_READER_FUNC */
SAPI_API SAPI_POST_READER_FUNC(php_default_post_reader)
{
if (!strcmp(SG(request_info).request_method, "POST")) {
if (NULL == SG(request_info).post_entry) {
/* no post handler registered, so we just swallow the data */
sapi_read_standard_form_data();
}
}
}
/* }}} */
/* {{{ php_startup_sapi_content_types */
int php_startup_sapi_content_types(void)
{
sapi_register_default_post_reader(php_default_post_reader);
sapi_register_treat_data(php_default_treat_data);
sapi_register_input_filter(php_default_input_filter, NULL);
return SUCCESS;
}
/* }}} */
/* {{{ php_setup_sapi_content_types */
int php_setup_sapi_content_types(void)
{
sapi_register_post_entries(php_post_entries);
return SUCCESS;
}
/* }}} */
| 2,202 | 35.114754 | 120 |
c
|
php-src
|
php-src-master/main/php_content_types.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: |
+----------------------------------------------------------------------+
*/
#ifndef PHP_CONTENT_TYPES_H
#define PHP_CONTENT_TYPES_H
#define DEFAULT_POST_CONTENT_TYPE "application/x-www-form-urlencoded"
SAPI_API SAPI_POST_READER_FUNC(php_default_post_reader);
SAPI_API SAPI_POST_HANDLER_FUNC(php_std_post_handler);
int php_startup_sapi_content_types(void);
int php_setup_sapi_content_types(void);
#endif /* PHP_CONTENT_TYPES_H */
| 1,338 | 46.821429 | 74 |
h
|
php-src
|
php-src-master/main/php_getopt.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_GETOPT_H
#define PHP_GETOPT_H
#include "php.h"
/* Define structure for one recognized option (both single char and long name).
* If short_open is '-' this is the last option. */
typedef struct _opt_struct {
char opt_char;
int need_param;
char * opt_name;
} opt_struct;
BEGIN_EXTERN_C()
/* holds the index of the latest fetched element from the opts array */
extern PHPAPI int php_optidx;
PHPAPI int php_getopt(int argc, char* const *argv, const opt_struct opts[], char **optarg, int *optind, int show_err, int arg_start);
END_EXTERN_C()
/* php_getopt will return this value if there is an error in arguments */
#define PHP_GETOPT_INVALID_ARG (-2)
#endif
| 1,671 | 40.8 | 133 |
h
|
php-src
|
php-src-master/main/php_globals.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Zeev Suraski <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_GLOBALS_H
#define PHP_GLOBALS_H
#include "zend_globals.h"
#include <stdint.h>
typedef struct _php_core_globals php_core_globals;
#ifdef ZTS
# define PG(v) ZEND_TSRMG_FAST(core_globals_offset, php_core_globals *, v)
extern PHPAPI int core_globals_id;
extern PHPAPI size_t core_globals_offset;
#else
# define PG(v) (core_globals.v)
extern ZEND_API struct _php_core_globals core_globals;
#endif
/* Error display modes */
#define PHP_DISPLAY_ERRORS_STDOUT 1
#define PHP_DISPLAY_ERRORS_STDERR 2
/* Track vars */
#define TRACK_VARS_POST 0
#define TRACK_VARS_GET 1
#define TRACK_VARS_COOKIE 2
#define TRACK_VARS_SERVER 3
#define TRACK_VARS_ENV 4
#define TRACK_VARS_FILES 5
#define TRACK_VARS_REQUEST 6
struct _php_tick_function_entry;
typedef struct _arg_separators {
char *output;
char *input;
} arg_separators;
struct _php_core_globals {
zend_long output_buffering;
bool implicit_flush;
bool enable_dl;
uint8_t display_errors;
bool display_startup_errors;
bool log_errors;
bool ignore_repeated_errors;
bool ignore_repeated_source;
bool report_memleaks;
char *output_handler;
char *unserialize_callback_func;
zend_long serialize_precision;
zend_long memory_limit;
zend_long max_input_time;
char *error_log;
char *doc_root;
char *user_dir;
char *include_path;
char *open_basedir;
char *extension_dir;
char *php_binary;
char *sys_temp_dir;
char *upload_tmp_dir;
zend_long upload_max_filesize;
char *error_append_string;
char *error_prepend_string;
char *auto_prepend_file;
char *auto_append_file;
char *input_encoding;
char *internal_encoding;
char *output_encoding;
arg_separators arg_separator;
char *variables_order;
HashTable rfc1867_protected_variables;
short connection_status;
bool ignore_user_abort;
unsigned char header_is_being_sent;
zend_llist tick_functions;
zval http_globals[6];
bool expose_php;
bool register_argc_argv;
bool auto_globals_jit;
bool html_errors;
bool xmlrpc_errors;
char *docref_root;
char *docref_ext;
zend_long xmlrpc_error_number;
bool activated_auto_globals[8];
bool modules_activated;
bool file_uploads;
bool during_request_startup;
bool allow_url_fopen;
bool enable_post_data_reading;
bool report_zend_debug;
int last_error_type;
int last_error_lineno;
zend_string *last_error_message;
zend_string *last_error_file;
char *php_sys_temp_dir;
char *disable_classes;
zend_long max_input_nesting_level;
zend_long max_input_vars;
char *user_ini_filename;
zend_long user_ini_cache_ttl;
char *request_order;
char *mail_log;
bool mail_x_header;
bool mail_mixed_lf_and_crlf;
bool in_error_log;
bool allow_url_include;
#ifdef PHP_WIN32
bool com_initialized;
#endif
bool in_user_include;
#ifdef PHP_WIN32
bool windows_show_crt_warning;
#endif
bool have_called_openlog;
zend_long syslog_facility;
char *syslog_ident;
zend_long syslog_filter;
zend_long error_log_mode;
};
#endif /* PHP_GLOBALS_H */
| 3,950 | 21.196629 | 75 |
h
|
php-src
|
php-src-master/main/php_ini.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Zeev Suraski <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_INI_H
#define PHP_INI_H
#include "zend_ini.h"
BEGIN_EXTERN_C()
PHPAPI void config_zval_dtor(zval *zvalue);
int php_init_config(void);
int php_shutdown_config(void);
void php_ini_register_extensions(void);
PHPAPI zval *cfg_get_entry_ex(zend_string *name);
PHPAPI zval *cfg_get_entry(const char *name, size_t name_length);
PHPAPI int cfg_get_long(const char *varname, zend_long *result);
PHPAPI int cfg_get_double(const char *varname, double *result);
PHPAPI int cfg_get_string(const char *varname, char **result);
PHPAPI int php_parse_user_ini_file(const char *dirname, const char *ini_filename, HashTable *target_hash);
PHPAPI void php_ini_activate_config(HashTable *source_hash, int modify_type, int stage);
PHPAPI int php_ini_has_per_dir_config(void);
PHPAPI int php_ini_has_per_host_config(void);
PHPAPI void php_ini_activate_per_dir_config(char *path, size_t path_len);
PHPAPI void php_ini_activate_per_host_config(const char *host, size_t host_len);
PHPAPI HashTable* php_ini_get_configuration_hash(void);
END_EXTERN_C()
#define PHP_INI_USER ZEND_INI_USER
#define PHP_INI_PERDIR ZEND_INI_PERDIR
#define PHP_INI_SYSTEM ZEND_INI_SYSTEM
#define PHP_INI_ALL ZEND_INI_ALL
#define php_ini_entry zend_ini_entry
#define PHP_INI_MH ZEND_INI_MH
#define PHP_INI_DISP ZEND_INI_DISP
#define PHP_INI_BEGIN ZEND_INI_BEGIN
#define PHP_INI_END ZEND_INI_END
#define PHP_INI_ENTRY3_EX ZEND_INI_ENTRY3_EX
#define PHP_INI_ENTRY3 ZEND_INI_ENTRY3
#define PHP_INI_ENTRY2_EX ZEND_INI_ENTRY2_EX
#define PHP_INI_ENTRY2 ZEND_INI_ENTRY2
#define PHP_INI_ENTRY1_EX ZEND_INI_ENTRY1_EX
#define PHP_INI_ENTRY1 ZEND_INI_ENTRY1
#define PHP_INI_ENTRY_EX ZEND_INI_ENTRY_EX
#define PHP_INI_ENTRY ZEND_INI_ENTRY
#define STD_PHP_INI_ENTRY STD_ZEND_INI_ENTRY
#define STD_PHP_INI_ENTRY_EX STD_ZEND_INI_ENTRY_EX
#define STD_PHP_INI_BOOLEAN STD_ZEND_INI_BOOLEAN
#define PHP_INI_DISPLAY_ORIG ZEND_INI_DISPLAY_ORIG
#define PHP_INI_DISPLAY_ACTIVE ZEND_INI_DISPLAY_ACTIVE
#define PHP_INI_STAGE_STARTUP ZEND_INI_STAGE_STARTUP
#define PHP_INI_STAGE_SHUTDOWN ZEND_INI_STAGE_SHUTDOWN
#define PHP_INI_STAGE_ACTIVATE ZEND_INI_STAGE_ACTIVATE
#define PHP_INI_STAGE_DEACTIVATE ZEND_INI_STAGE_DEACTIVATE
#define PHP_INI_STAGE_RUNTIME ZEND_INI_STAGE_RUNTIME
#define PHP_INI_STAGE_HTACCESS ZEND_INI_STAGE_HTACCESS
#define php_ini_boolean_displayer_cb zend_ini_boolean_displayer_cb
#define php_ini_color_displayer_cb zend_ini_color_displayer_cb
#define php_alter_ini_entry zend_alter_ini_entry
#define php_ini_long zend_ini_long
#define php_ini_double zend_ini_double
#define php_ini_string zend_ini_string
#endif /* PHP_INI_H */
| 3,613 | 40.068182 | 106 |
h
|
php-src
|
php-src-master/main/php_main.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Andi Gutmans <[email protected]> |
| Zeev Suraski <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_MAIN_H
#define PHP_MAIN_H
#include "zend_globals.h"
#include "php_globals.h"
#include "SAPI.h"
BEGIN_EXTERN_C()
PHPAPI zend_result php_request_startup(void);
PHPAPI void php_request_shutdown(void *dummy);
PHPAPI zend_result php_module_startup(sapi_module_struct *sf, zend_module_entry *additional_module);
PHPAPI void php_module_shutdown(void);
PHPAPI int php_module_shutdown_wrapper(sapi_module_struct *sapi_globals);
PHPAPI zend_result php_register_extensions(zend_module_entry * const * ptr, int count);
PHPAPI bool php_execute_script(zend_file_handle *primary_file);
PHPAPI int php_execute_simple_script(zend_file_handle *primary_file, zval *ret);
PHPAPI zend_result php_lint_script(zend_file_handle *file);
PHPAPI void php_handle_aborted_connection(void);
PHPAPI int php_handle_auth_data(const char *auth);
PHPAPI void php_html_puts(const char *str, size_t siz);
PHPAPI zend_result php_stream_open_for_zend_ex(zend_file_handle *handle, int mode);
/* environment module */
extern int php_init_environ(void);
extern int php_shutdown_environ(void);
#ifdef ZTS
PHPAPI void php_reserve_tsrm_memory(void);
PHPAPI bool php_tsrm_startup_ex(int expected_threads);
PHPAPI bool php_tsrm_startup(void);
#define PHP_ZTS 1
#else
#define PHP_ZTS 0
#endif
#ifdef PHP_WIN32
#define PHP_OS_STR "WINNT"
#else
#define PHP_OS_STR PHP_OS
#endif
END_EXTERN_C()
#endif
| 2,446 | 35.522388 | 100 |
h
|
php-src
|
php-src-master/main/php_odbc_utils.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Calvin Buckley <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
/*
* This files contains functions shared between ext/pdo_odbc and ext/odbc,
* relating to i.e. connection string quoting rules.
*
* The declarations are PHPAPI due to being available for shared/static
* versions.
*/
/**
* Determines if a string matches the ODBC quoting rules.
*
* A valid quoted string begins with a '{', ends with a '}', and has no '}'
* inside of the string that aren't repeated (as to be escaped).
*
* These rules are what .NET also follows.
*/
PHPAPI bool php_odbc_connstr_is_quoted(const char *str)
{
/* ODBC quotes are curly braces */
if (str[0] != '{') {
return false;
}
/* Check for } that aren't doubled up or at the end of the string */
size_t length = strlen(str);
for (size_t i = 0; i < length; i++) {
if (str[i] == '}' && str[i + 1] == '}') {
/* Skip over so we don't count it again */
i++;
} else if (str[i] == '}' && str[i + 1] != '\0') {
/* If not at the end, not quoted */
return false;
}
}
return true;
}
/**
* Determines if a value for a connection string should be quoted.
*
* The ODBC specification mentions:
* "Because of connection string and initialization file grammar, keywords and
* attribute values that contain the characters []{}(),;?*=!@ not enclosed
* with braces should be avoided."
*
* Note that it assumes that the string is *not* already quoted. You should
* check beforehand.
*/
PHPAPI bool php_odbc_connstr_should_quote(const char *str)
{
return strpbrk(str, "[]{}(),;?*=!@") != NULL;
}
/**
* Estimates the worst-case scenario for a quoted version of a string's size.
*/
PHPAPI size_t php_odbc_connstr_estimate_quote_length(const char *in_str)
{
/* Assume all '}'. Include '{,' '}', and the null terminator too */
return (strlen(in_str) * 2) + 3;
}
/**
* Quotes a string with ODBC rules.
*
* Some characters (curly braces, semicolons) are special and must be quoted.
* In the case of '}' in a quoted string, they must be escaped SQL style; that
* is, repeated.
*/
PHPAPI size_t php_odbc_connstr_quote(char *out_str, const char *in_str, size_t out_str_size)
{
*out_str++ = '{';
out_str_size--;
while (out_str_size > 2) {
if (*in_str == '\0') {
break;
} else if (*in_str == '}' && out_str_size - 1 > 2) {
/* enough room to append */
*out_str++ = '}';
*out_str++ = *in_str++;
out_str_size -= 2;
} else if (*in_str == '}') {
/* not enough, truncate here */
break;
} else {
*out_str++ = *in_str++;
out_str_size--;
}
}
/* append termination */
*out_str++ = '}';
*out_str++ = '\0';
out_str_size -= 2;
/* return how many characters were left */
return strlen(in_str);
}
| 3,693 | 30.305085 | 92 |
c
|
php-src
|
php-src-master/main/php_odbc_utils.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Calvin Buckley <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
PHPAPI bool php_odbc_connstr_is_quoted(const char *str);
PHPAPI bool php_odbc_connstr_should_quote(const char *str);
PHPAPI size_t php_odbc_connstr_estimate_quote_length(const char *in_str);
PHPAPI size_t php_odbc_connstr_quote(char *out_str, const char *in_str, size_t out_str_size);
| 1,298 | 55.478261 | 93 |
h
|
php-src
|
php-src-master/main/php_open_temporary_file.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Zeev Suraski <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "php_open_temporary_file.h"
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef PHP_WIN32
#define O_RDONLY _O_RDONLY
#include "win32/param.h"
#include "win32/winutil.h"
#else
#include <sys/param.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#if HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_FILE_H
#include <sys/file.h>
#endif
#if !defined(P_tmpdir)
#define P_tmpdir ""
#endif
/* {{{ php_do_open_temporary_file */
/* Loosely based on a tempnam() implementation by UCLA */
/*
* Copyright (c) 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
static int php_do_open_temporary_file(const char *path, const char *pfx, zend_string **opened_path_p)
{
#ifdef PHP_WIN32
char *opened_path = NULL;
size_t opened_path_len;
wchar_t *cwdw, *pfxw, pathw[MAXPATHLEN];
#else
char opened_path[MAXPATHLEN];
char *trailing_slash;
#endif
char cwd[MAXPATHLEN];
cwd_state new_state;
int fd = -1;
#ifndef HAVE_MKSTEMP
int open_flags = O_CREAT | O_TRUNC | O_RDWR
#ifdef PHP_WIN32
| _O_BINARY
#endif
;
#endif
if (!path || !path[0]) {
return -1;
}
#ifdef PHP_WIN32
if (!php_win32_check_trailing_space(pfx, strlen(pfx))) {
SetLastError(ERROR_INVALID_NAME);
return -1;
}
#endif
if (!VCWD_GETCWD(cwd, MAXPATHLEN)) {
cwd[0] = '\0';
}
new_state.cwd = estrdup(cwd);
new_state.cwd_length = strlen(cwd);
if (virtual_file_ex(&new_state, path, NULL, CWD_REALPATH)) {
efree(new_state.cwd);
return -1;
}
#ifndef PHP_WIN32
if (IS_SLASH(new_state.cwd[new_state.cwd_length - 1])) {
trailing_slash = "";
} else {
trailing_slash = "/";
}
if (snprintf(opened_path, MAXPATHLEN, "%s%s%sXXXXXX", new_state.cwd, trailing_slash, pfx) >= MAXPATHLEN) {
efree(new_state.cwd);
return -1;
}
#endif
#ifdef PHP_WIN32
cwdw = php_win32_ioutil_any_to_w(new_state.cwd);
pfxw = php_win32_ioutil_any_to_w(pfx);
if (!cwdw || !pfxw) {
free(cwdw);
free(pfxw);
efree(new_state.cwd);
return -1;
}
if (GetTempFileNameW(cwdw, pfxw, 0, pathw)) {
opened_path = php_win32_ioutil_conv_w_to_any(pathw, PHP_WIN32_CP_IGNORE_LEN, &opened_path_len);
if (!opened_path || opened_path_len >= MAXPATHLEN) {
free(cwdw);
free(pfxw);
efree(new_state.cwd);
return -1;
}
assert(strlen(opened_path) == opened_path_len);
/* Some versions of windows set the temp file to be read-only,
* which means that opening it will fail... */
if (VCWD_CHMOD(opened_path, 0600)) {
free(cwdw);
free(pfxw);
efree(new_state.cwd);
free(opened_path);
return -1;
}
fd = VCWD_OPEN_MODE(opened_path, open_flags, 0600);
}
free(cwdw);
free(pfxw);
#elif defined(HAVE_MKSTEMP)
fd = mkstemp(opened_path);
#else
if (mktemp(opened_path)) {
fd = VCWD_OPEN(opened_path, open_flags);
}
#endif
#ifdef PHP_WIN32
if (fd != -1 && opened_path_p) {
*opened_path_p = zend_string_init(opened_path, opened_path_len, 0);
}
free(opened_path);
#else
if (fd != -1 && opened_path_p) {
*opened_path_p = zend_string_init(opened_path, strlen(opened_path), 0);
}
#endif
efree(new_state.cwd);
return fd;
}
/* }}} */
/*
* Determine where to place temporary files.
*/
PHPAPI const char* php_get_temporary_directory(void)
{
/* Did we determine the temporary directory already? */
if (PG(php_sys_temp_dir)) {
return PG(php_sys_temp_dir);
}
/* Is there a temporary directory "sys_temp_dir" in .ini defined? */
{
char *sys_temp_dir = PG(sys_temp_dir);
if (sys_temp_dir) {
size_t len = strlen(sys_temp_dir);
if (len >= 2 && sys_temp_dir[len - 1] == DEFAULT_SLASH) {
PG(php_sys_temp_dir) = estrndup(sys_temp_dir, len - 1);
return PG(php_sys_temp_dir);
} else if (len >= 1 && sys_temp_dir[len - 1] != DEFAULT_SLASH) {
PG(php_sys_temp_dir) = estrndup(sys_temp_dir, len);
return PG(php_sys_temp_dir);
}
}
}
#ifdef PHP_WIN32
/* We can't count on the environment variables TEMP or TMP,
* and so must make the Win32 API call to get the default
* directory for temporary files. Note this call checks
* the environment values TMP and TEMP (in order) first.
*/
{
wchar_t sTemp[MAXPATHLEN];
char *tmp;
size_t len = GetTempPathW(MAXPATHLEN, sTemp);
if (!len) {
return NULL;
}
if (NULL == (tmp = php_win32_ioutil_conv_w_to_any(sTemp, len, &len))) {
return NULL;
}
PG(php_sys_temp_dir) = estrndup(tmp, len - 1);
free(tmp);
return PG(php_sys_temp_dir);
}
#else
/* On Unix use the (usual) TMPDIR environment variable. */
{
char* s = getenv("TMPDIR");
if (s && *s) {
size_t len = strlen(s);
if (s[len - 1] == DEFAULT_SLASH) {
PG(php_sys_temp_dir) = estrndup(s, len - 1);
} else {
PG(php_sys_temp_dir) = estrndup(s, len);
}
return PG(php_sys_temp_dir);
}
}
#ifdef P_tmpdir
/* Use the standard default temporary directory. */
if (P_tmpdir) {
PG(php_sys_temp_dir) = estrdup(P_tmpdir);
return PG(php_sys_temp_dir);
}
#endif
/* Shouldn't ever(!) end up here ... last ditch default. */
PG(php_sys_temp_dir) = estrdup("/tmp");
return PG(php_sys_temp_dir);
#endif
}
/* {{{ php_open_temporary_file
*
* Unlike tempnam(), the supplied dir argument takes precedence
* over the TMPDIR environment variable
* This function should do its best to return a file pointer to a newly created
* unique file, on every platform.
*/
PHPAPI int php_open_temporary_fd_ex(const char *dir, const char *pfx, zend_string **opened_path_p, uint32_t flags)
{
int fd;
const char *temp_dir;
if (!pfx) {
pfx = "tmp.";
}
if (opened_path_p) {
*opened_path_p = NULL;
}
if (!dir || *dir == '\0') {
def_tmp:
temp_dir = php_get_temporary_directory();
if (temp_dir &&
*temp_dir != '\0' &&
(!(flags & PHP_TMP_FILE_OPEN_BASEDIR_CHECK_ON_FALLBACK) || !php_check_open_basedir(temp_dir))) {
return php_do_open_temporary_file(temp_dir, pfx, opened_path_p);
} else {
return -1;
}
}
if ((flags & PHP_TMP_FILE_OPEN_BASEDIR_CHECK_ON_EXPLICIT_DIR) && php_check_open_basedir(dir)) {
return -1;
}
/* Try the directory given as parameter. */
fd = php_do_open_temporary_file(dir, pfx, opened_path_p);
if (fd == -1) {
/* Use default temporary directory. */
if (!(flags & PHP_TMP_FILE_SILENT)) {
php_error_docref(NULL, E_NOTICE, "file created in the system's temporary directory");
}
goto def_tmp;
}
return fd;
}
PHPAPI int php_open_temporary_fd(const char *dir, const char *pfx, zend_string **opened_path_p)
{
return php_open_temporary_fd_ex(dir, pfx, opened_path_p, PHP_TMP_FILE_DEFAULT);
}
PHPAPI FILE *php_open_temporary_file(const char *dir, const char *pfx, zend_string **opened_path_p)
{
FILE *fp;
int fd = php_open_temporary_fd(dir, pfx, opened_path_p);
if (fd == -1) {
return NULL;
}
fp = fdopen(fd, "r+b");
if (fp == NULL) {
close(fd);
}
return fp;
}
/* }}} */
| 9,652 | 26.659026 | 114 |
c
|
php-src
|
php-src-master/main/php_open_temporary_file.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Zeev Suraski <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_OPEN_TEMPORARY_FILE_H
#define PHP_OPEN_TEMPORARY_FILE_H
#define PHP_TMP_FILE_DEFAULT 0
#define PHP_TMP_FILE_OPEN_BASEDIR_CHECK_ON_FALLBACK (1<<0)
#define PHP_TMP_FILE_SILENT (1<<1)
#define PHP_TMP_FILE_OPEN_BASEDIR_CHECK_ON_EXPLICIT_DIR (1<<2)
#define PHP_TMP_FILE_OPEN_BASEDIR_CHECK_ALWAYS \
(PHP_TMP_FILE_OPEN_BASEDIR_CHECK_ON_FALLBACK | PHP_TMP_FILE_OPEN_BASEDIR_CHECK_ON_EXPLICIT_DIR)
/* for compatibility purpose */
#define PHP_TMP_FILE_OPEN_BASEDIR_CHECK PHP_TMP_FILE_OPEN_BASEDIR_CHECK_ON_FALLBACK
BEGIN_EXTERN_C()
PHPAPI FILE *php_open_temporary_file(const char *dir, const char *pfx, zend_string **opened_path_p);
PHPAPI int php_open_temporary_fd_ex(const char *dir, const char *pfx, zend_string **opened_path_p, uint32_t flags);
PHPAPI int php_open_temporary_fd(const char *dir, const char *pfx, zend_string **opened_path_p);
PHPAPI const char *php_get_temporary_directory(void);
END_EXTERN_C()
#endif /* PHP_OPEN_TEMPORARY_FILE_H */
| 1,960 | 49.282051 | 115 |
h
|
php-src
|
php-src-master/main/php_reentrancy.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Sascha Schumann <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_REENTRANCY_H
#define PHP_REENTRANCY_H
#include "php.h"
#include <sys/types.h>
#ifdef HAVE_DIRENT_H
#include <dirent.h>
#endif
#include <time.h>
/* currently, PHP does not check for these functions, but assumes
that they are available on all systems. */
#define HAVE_LOCALTIME 1
#define HAVE_GMTIME 1
#define HAVE_ASCTIME 1
#define HAVE_CTIME 1
#if defined(PHP_IRIX_TIME_R)
#undef HAVE_ASCTIME_R
#undef HAVE_CTIME_R
#endif
#if defined(PHP_HPUX_TIME_R)
#undef HAVE_LOCALTIME_R
#undef HAVE_ASCTIME_R
#undef HAVE_CTIME_R
#undef HAVE_GMTIME_R
#endif
BEGIN_EXTERN_C()
#if !defined(HAVE_LOCALTIME_R) && defined(HAVE_LOCALTIME)
#define PHP_NEED_REENTRANCY 1
PHPAPI struct tm *php_localtime_r(const time_t *const timep, struct tm *p_tm);
#else
#define php_localtime_r localtime_r
#ifdef MISSING_LOCALTIME_R_DECL
struct tm *localtime_r(const time_t *const timep, struct tm *p_tm);
#endif
#endif
#if !defined(HAVE_CTIME_R) && defined(HAVE_CTIME)
#define PHP_NEED_REENTRANCY 1
PHPAPI char *php_ctime_r(const time_t *clock, char *buf);
#else
#define php_ctime_r ctime_r
#ifdef MISSING_CTIME_R_DECL
char *ctime_r(const time_t *clock, char *buf);
#endif
#endif
#if !defined(HAVE_ASCTIME_R) && defined(HAVE_ASCTIME)
#define PHP_NEED_REENTRANCY 1
PHPAPI char *php_asctime_r(const struct tm *tm, char *buf);
#else
#define php_asctime_r asctime_r
#ifdef MISSING_ASCTIME_R_DECL
char *asctime_r(const struct tm *tm, char *buf);
#endif
#endif
#if !defined(HAVE_GMTIME_R) && defined(HAVE_GMTIME)
#define PHP_NEED_REENTRANCY 1
PHPAPI struct tm *php_gmtime_r(const time_t *const timep, struct tm *p_tm);
#else
#define php_gmtime_r gmtime_r
#ifdef MISSING_GMTIME_R_DECL
struct tm *php_gmtime_r(const time_t *const timep, struct tm *p_tm);
#endif
#endif
#if !defined(HAVE_STRTOK_R)
PHPAPI char *php_strtok_r(char *s, const char *delim, char **last);
#else
#define php_strtok_r strtok_r
#ifdef MISSING_STRTOK_R_DECL
char *strtok_r(char *s, const char *delim, char **last);
#endif
#endif
END_EXTERN_C()
#if !defined(ZTS)
#undef PHP_NEED_REENTRANCY
#endif
#if defined(PHP_NEED_REENTRANCY)
void reentrancy_startup(void);
void reentrancy_shutdown(void);
#else
#define reentrancy_startup()
#define reentrancy_shutdown()
#endif
#endif
| 3,231 | 26.623932 | 78 |
h
|
php-src
|
php-src-master/main/php_syslog.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Philip Prindeville <[email protected]> |
+----------------------------------------------------------------------+
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "php.h"
#include "php_syslog.h"
#include "zend.h"
#include "zend_smart_string.h"
/*
* The SCO OpenServer 5 Development System (not the UDK)
* defines syslog to std_syslog.
*/
#ifdef HAVE_STD_SYSLOG
#define syslog std_syslog
#endif
PHPAPI void php_syslog_str(int priority, const zend_string* message)
{
smart_string sbuf = {0};
if (PG(syslog_filter) == PHP_SYSLOG_FILTER_RAW) {
/* Just send it directly to the syslog */
syslog(priority, "%s", ZSTR_VAL(message));
return;
}
/* We use < because we don't want the final NUL byte to be converted to '\x00' */
for (size_t i = 0; i < ZSTR_LEN(message); ++i) {
unsigned char c = ZSTR_VAL(message)[i];
/* check for NVT ASCII only unless test disabled */
if (((0x20 <= c) && (c <= 0x7e))) {
smart_string_appendc(&sbuf, c);
} else if ((c >= 0x80) && (PG(syslog_filter) != PHP_SYSLOG_FILTER_ASCII)) {
smart_string_appendc(&sbuf, c);
} else if (c == '\n') {
/* Smart string is not NUL terminated */
syslog(priority, "%.*s", (int)sbuf.len, sbuf.c);
smart_string_reset(&sbuf);
} else if ((c < 0x20) && (PG(syslog_filter) == PHP_SYSLOG_FILTER_ALL)) {
smart_string_appendc(&sbuf, c);
} else {
static const char xdigits[] = "0123456789abcdef";
smart_string_appendl(&sbuf, "\\x", 2);
smart_string_appendc(&sbuf, xdigits[c >> 4]);
smart_string_appendc(&sbuf, xdigits[c & 0xf]);
}
}
/* Smart string is not NUL terminated */
syslog(priority, "%.*s", (int)sbuf.len, sbuf.c);
smart_string_free(&sbuf);
}
void php_openlog(const char *ident, int option, int facility)
{
openlog(ident, option, facility);
PG(have_called_openlog) = 1;
}
void php_closelog(void)
{
closelog();
PG(have_called_openlog) = 0;
}
#ifdef PHP_WIN32
PHPAPI void php_syslog(int priority, const char *format, ...) /* {{{ */
{
va_list args;
/*
* don't rely on openlog() being called by syslog() if it's
* not already been done; call it ourselves and pass the
* correct parameters!
*/
if (!PG(have_called_openlog)) {
php_openlog(PG(syslog_ident), 0, PG(syslog_facility));
}
va_start(args, format);
vsyslog(priority, format, args);
va_end(args);
}
/* }}} */
#else
PHPAPI void php_syslog(int priority, const char *format, ...) /* {{{ */
{
zend_string *fbuf = NULL;
va_list args;
/*
* don't rely on openlog() being called by syslog() if it's
* not already been done; call it ourselves and pass the
* correct parameters!
*/
if (!PG(have_called_openlog)) {
php_openlog(PG(syslog_ident), 0, PG(syslog_facility));
}
va_start(args, format);
fbuf = zend_vstrpprintf(0, format, args);
va_end(args);
php_syslog_str(priority, fbuf);
zend_string_release(fbuf);
}
/* }}} */
#endif
| 3,744 | 27.807692 | 82 |
c
|
php-src
|
php-src-master/main/php_syslog.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: |
+----------------------------------------------------------------------+
*/
#ifndef PHP_SYSLOG_H
#define PHP_SYSLOG_H
#include "php.h"
#ifdef PHP_WIN32
#include "win32/syslog.h"
#else
#include <php_config.h>
#ifdef HAVE_SYSLOG_H
#include <syslog.h>
#endif
#endif
/* Syslog filters */
#define PHP_SYSLOG_FILTER_ALL 0
#define PHP_SYSLOG_FILTER_NO_CTRL 1
#define PHP_SYSLOG_FILTER_ASCII 2
#define PHP_SYSLOG_FILTER_RAW 3
BEGIN_EXTERN_C()
PHPAPI void php_syslog_str(int priority, const zend_string* message);
PHPAPI void php_syslog(int, const char *format, ...);
PHPAPI void php_openlog(const char *, int, int);
PHPAPI void php_closelog(void);
END_EXTERN_C()
#endif
| 1,576 | 34.044444 | 74 |
h
|
php-src
|
php-src-master/main/php_ticks.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Stig Bakken <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "php_ticks.h"
struct st_tick_function
{
void (*func)(int, void *);
void *arg;
};
int php_startup_ticks(void)
{
zend_llist_init(&PG(tick_functions), sizeof(struct st_tick_function), NULL, 1);
return SUCCESS;
}
void php_deactivate_ticks(void)
{
zend_llist_clean(&PG(tick_functions));
}
void php_shutdown_ticks(php_core_globals *core_globals)
{
zend_llist_destroy(&core_globals->tick_functions);
}
static int php_compare_tick_functions(void *elem1, void *elem2)
{
struct st_tick_function *e1 = (struct st_tick_function *)elem1;
struct st_tick_function *e2 = (struct st_tick_function *)elem2;
return e1->func == e2->func && e1->arg == e2->arg;
}
PHPAPI void php_add_tick_function(void (*func)(int, void*), void * arg)
{
struct st_tick_function tmp = {func, arg};
zend_llist_add_element(&PG(tick_functions), (void *)&tmp);
}
PHPAPI void php_remove_tick_function(void (*func)(int, void *), void * arg)
{
struct st_tick_function tmp = {func, arg};
zend_llist_del_element(&PG(tick_functions), (void *)&tmp, (int(*)(void*, void*))php_compare_tick_functions);
}
static void php_tick_iterator(void *d, void *arg)
{
struct st_tick_function *data = (struct st_tick_function *)d;
data->func(*((int *)arg), data->arg);
}
void php_run_ticks(int count)
{
zend_llist_apply_with_argument(&PG(tick_functions), (llist_apply_with_arg_func_t) php_tick_iterator, &count);
}
| 2,396 | 32.760563 | 110 |
c
|
php-src
|
php-src-master/main/php_ticks.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Stig Bakken <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_TICKS_H
#define PHP_TICKS_H
int php_startup_ticks(void);
void php_deactivate_ticks(void);
void php_shutdown_ticks(php_core_globals *core_globals);
void php_run_ticks(int count);
BEGIN_EXTERN_C()
PHPAPI void php_add_tick_function(void (*func)(int, void *), void *arg);
PHPAPI void php_remove_tick_function(void (*func)(int, void *), void * arg);
END_EXTERN_C()
#endif
| 1,377 | 43.451613 | 76 |
h
|
php-src
|
php-src-master/main/php_variables.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <[email protected]> |
| Zeev Suraski <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_VARIABLES_H
#define PHP_VARIABLES_H
#include "php.h"
#include "SAPI.h"
#define PARSE_POST 0
#define PARSE_GET 1
#define PARSE_COOKIE 2
#define PARSE_STRING 3
#define PARSE_ENV 4
#define PARSE_SERVER 5
#define PARSE_SESSION 6
BEGIN_EXTERN_C()
void php_startup_auto_globals(void);
extern PHPAPI void (*php_import_environment_variables)(zval *array_ptr);
PHPAPI void php_register_variable(const char *var, const char *val, zval *track_vars_array);
/* binary-safe version */
PHPAPI void php_register_variable_safe(const char *var, const char *val, size_t val_len, zval *track_vars_array);
PHPAPI void php_register_variable_ex(const char *var, zval *val, zval *track_vars_array);
PHPAPI void php_register_known_variable(const char *var, size_t var_len, zval *value, zval *track_vars_array);
PHPAPI void php_build_argv(const char *s, zval *track_vars_array);
PHPAPI int php_hash_environment(void);
END_EXTERN_C()
#define NUM_TRACK_VARS 6
#endif /* PHP_VARIABLES_H */
| 2,050 | 41.729167 | 113 |
h
|
php-src
|
php-src-master/main/reentrancy.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Sascha Schumann <[email protected]> |
+----------------------------------------------------------------------+
*/
#include <sys/types.h>
#include <string.h>
#include <errno.h>
#ifdef HAVE_DIRENT_H
#include <dirent.h>
#endif
#include "php_reentrancy.h"
#include "ext/random/php_random.h" /* for PHP_RAND_MAX */
enum {
LOCALTIME_R,
CTIME_R,
ASCTIME_R,
GMTIME_R,
NUMBER_OF_LOCKS
};
#if defined(PHP_NEED_REENTRANCY)
#include <TSRM.h>
static MUTEX_T reentrant_locks[NUMBER_OF_LOCKS];
#define local_lock(x) tsrm_mutex_lock(reentrant_locks[x])
#define local_unlock(x) tsrm_mutex_unlock(reentrant_locks[x])
#else
#define local_lock(x)
#define local_unlock(x)
#endif
#if defined(PHP_IRIX_TIME_R)
#define HAVE_CTIME_R 1
#define HAVE_ASCTIME_R 1
PHPAPI char *php_ctime_r(const time_t *clock, char *buf)
{
if (ctime_r(clock, buf) == buf)
return (buf);
return (NULL);
}
PHPAPI char *php_asctime_r(const struct tm *tm, char *buf)
{
if (asctime_r(tm, buf) == buf)
return (buf);
return (NULL);
}
#endif
#if defined(PHP_HPUX_TIME_R)
#define HAVE_LOCALTIME_R 1
#define HAVE_CTIME_R 1
#define HAVE_ASCTIME_R 1
#define HAVE_GMTIME_R 1
PHPAPI struct tm *php_localtime_r(const time_t *const timep, struct tm *p_tm)
{
if (localtime_r(timep, p_tm) == 0)
return (p_tm);
return (NULL);
}
PHPAPI char *php_ctime_r(const time_t *clock, char *buf)
{
if (ctime_r(clock, buf, 26) != -1)
return (buf);
return (NULL);
}
PHPAPI char *php_asctime_r(const struct tm *tm, char *buf)
{
if (asctime_r(tm, buf, 26) != -1)
return (buf);
return (NULL);
}
PHPAPI struct tm *php_gmtime_r(const time_t *const timep, struct tm *p_tm)
{
if (gmtime_r(timep, p_tm) == 0)
return (p_tm);
return (NULL);
}
#endif
#if !defined(HAVE_LOCALTIME_R) && defined(HAVE_LOCALTIME)
PHPAPI struct tm *php_localtime_r(const time_t *const timep, struct tm *p_tm)
{
struct tm *tmp;
local_lock(LOCALTIME_R);
tmp = localtime(timep);
if (tmp) {
memcpy(p_tm, tmp, sizeof(struct tm));
tmp = p_tm;
}
local_unlock(LOCALTIME_R);
return tmp;
}
#endif
#if !defined(HAVE_CTIME_R) && defined(HAVE_CTIME)
PHPAPI char *php_ctime_r(const time_t *clock, char *buf)
{
char *tmp;
local_lock(CTIME_R);
tmp = ctime(clock);
if (tmp) {
strcpy(buf, tmp);
tmp = buf;
}
local_unlock(CTIME_R);
return tmp;
}
#endif
#if !defined(HAVE_ASCTIME_R) && defined(HAVE_ASCTIME)
PHPAPI char *php_asctime_r(const struct tm *tm, char *buf)
{
char *tmp;
local_lock(ASCTIME_R);
tmp = asctime(tm);
if (tmp) {
strcpy(buf, tmp);
tmp = buf;
}
local_unlock(ASCTIME_R);
return tmp;
}
#endif
#if !defined(HAVE_GMTIME_R) && defined(HAVE_GMTIME)
PHPAPI struct tm *php_gmtime_r(const time_t *const timep, struct tm *p_tm)
{
struct tm *tmp;
local_lock(GMTIME_R);
tmp = gmtime(timep);
if (tmp) {
memcpy(p_tm, tmp, sizeof(struct tm));
tmp = p_tm;
}
local_unlock(GMTIME_R);
return tmp;
}
#endif
#if defined(PHP_NEED_REENTRANCY)
void reentrancy_startup(void)
{
int i;
for (i = 0; i < NUMBER_OF_LOCKS; i++) {
reentrant_locks[i] = tsrm_mutex_alloc();
}
}
void reentrancy_shutdown(void)
{
int i;
for (i = 0; i < NUMBER_OF_LOCKS; i++) {
tsrm_mutex_free(reentrant_locks[i]);
}
}
#endif
#ifndef HAVE_STRTOK_R
/*
* Copyright (c) 1998 Softweyr LLC. All rights reserved.
*
* strtok_r, from Berkeley strtok
* Oct 13, 1998 by Wes Peters <[email protected]>
*
* Copyright (c) 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notices, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notices, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
*
* This product includes software developed by Softweyr LLC, the
* University of California, Berkeley, and its contributors.
*
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY SOFTWEYR LLC, THE REGENTS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SOFTWEYR LLC, THE
* REGENTS, OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stddef.h>
PHPAPI char *
php_strtok_r(char *s, const char *delim, char **last)
{
char *spanp;
int c, sc;
char *tok;
if (s == NULL && (s = *last) == NULL)
{
return NULL;
}
/*
* Skip (span) leading delimiters (s += strspn(s, delim), sort of).
*/
cont:
c = *s++;
for (spanp = (char *)delim; (sc = *spanp++) != 0; )
{
if (c == sc)
{
goto cont;
}
}
if (c == 0) /* no non-delimiter characters */
{
*last = NULL;
return NULL;
}
tok = s - 1;
/*
* Scan token (scan for delimiters: s += strcspn(s, delim), sort of).
* Note that delim must have one NUL; we stop if we see that, too.
*/
for (;;)
{
c = *s++;
spanp = (char *)delim;
do
{
if ((sc = *spanp++) == c)
{
if (c == 0)
{
s = NULL;
}
else
{
char *w = s - 1;
*w = '\0';
}
*last = s;
return tok;
}
}
while (sc != 0);
}
/* NOTREACHED */
}
#endif
| 7,141 | 20.907975 | 77 |
c
|
php-src
|
php-src-master/main/rfc1867.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: |
+----------------------------------------------------------------------+
*/
#ifndef RFC1867_H
#define RFC1867_H
#include "SAPI.h"
#define MULTIPART_CONTENT_TYPE "multipart/form-data"
#define MULTIPART_EVENT_START 0
#define MULTIPART_EVENT_FORMDATA 1
#define MULTIPART_EVENT_FILE_START 2
#define MULTIPART_EVENT_FILE_DATA 3
#define MULTIPART_EVENT_FILE_END 4
#define MULTIPART_EVENT_END 5
/* Errors */
#define PHP_UPLOAD_ERROR_OK 0 /* File upload successful */
#define PHP_UPLOAD_ERROR_A 1 /* Uploaded file exceeded upload_max_filesize */
#define PHP_UPLOAD_ERROR_B 2 /* Uploaded file exceeded MAX_FILE_SIZE */
#define PHP_UPLOAD_ERROR_C 3 /* Partially uploaded */
#define PHP_UPLOAD_ERROR_D 4 /* No file uploaded */
#define PHP_UPLOAD_ERROR_E 6 /* Missing /tmp or similar directory */
#define PHP_UPLOAD_ERROR_F 7 /* Failed to write file to disk */
#define PHP_UPLOAD_ERROR_X 8 /* File upload stopped by extension */
typedef struct _multipart_event_start {
size_t content_length;
} multipart_event_start;
typedef struct _multipart_event_formdata {
size_t post_bytes_processed;
char *name;
char **value;
size_t length;
size_t *newlength;
} multipart_event_formdata;
typedef struct _multipart_event_file_start {
size_t post_bytes_processed;
char *name;
char **filename;
} multipart_event_file_start;
typedef struct _multipart_event_file_data {
size_t post_bytes_processed;
zend_off_t offset;
char *data;
size_t length;
size_t *newlength;
} multipart_event_file_data;
typedef struct _multipart_event_file_end {
size_t post_bytes_processed;
char *temp_filename;
int cancel_upload;
} multipart_event_file_end;
typedef struct _multipart_event_end {
size_t post_bytes_processed;
} multipart_event_end;
typedef int (*php_rfc1867_encoding_translation_t)(void);
typedef void (*php_rfc1867_get_detect_order_t)(const zend_encoding ***list, size_t *list_size);
typedef void (*php_rfc1867_set_input_encoding_t)(const zend_encoding *encoding);
typedef char* (*php_rfc1867_getword_t)(const zend_encoding *encoding, char **line, char stop);
typedef char* (*php_rfc1867_getword_conf_t)(const zend_encoding *encoding, char *str);
typedef char* (*php_rfc1867_basename_t)(const zend_encoding *encoding, char *str);
SAPI_API SAPI_POST_HANDLER_FUNC(rfc1867_post_handler);
PHPAPI void destroy_uploaded_files_hash(void);
extern PHPAPI zend_result (*php_rfc1867_callback)(unsigned int event, void *event_data, void **extra);
SAPI_API void php_rfc1867_set_multibyte_callbacks(
php_rfc1867_encoding_translation_t encoding_translation,
php_rfc1867_get_detect_order_t get_detect_order,
php_rfc1867_set_input_encoding_t set_input_encoding,
php_rfc1867_getword_t getword,
php_rfc1867_getword_conf_t getword_conf,
php_rfc1867_basename_t basename);
#endif /* RFC1867_H */
| 3,739 | 37.556701 | 102 |
h
|
php-src
|
php-src-master/main/safe_bcmp.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: David Carlier <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include <string.h>
/*
* Returns 0 if both inputs match, non-zero if they don't.
* Returns -1 early if inputs do not have the same lengths.
*
*/
PHPAPI int php_safe_bcmp(const zend_string *a, const zend_string *b)
{
const volatile unsigned char *ua = (const volatile unsigned char *)ZSTR_VAL(a);
const volatile unsigned char *ub = (const volatile unsigned char *)ZSTR_VAL(b);
size_t i = 0;
int r = 0;
if (ZSTR_LEN(a) != ZSTR_LEN(b)) {
return -1;
}
/* This is security sensitive code. Do not optimize this for speed. */
while (i < ZSTR_LEN(a)) {
r |= ua[i] ^ ub[i];
++i;
}
return r;
}
| 1,608 | 34.755556 | 80 |
c
|
php-src
|
php-src-master/main/snprintf.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Stig Sæther Bakken <[email protected]> |
| Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
/*
Comparing: sprintf, snprintf, slprintf, spprintf
sprintf offers the ability to make a lot of failures since it does not know
the size of the buffer it uses. Therefore usage of sprintf often
results in possible entries for buffer overrun attacks. So please
use this version only if you are sure the call is safe. sprintf
always terminates the buffer it writes to.
snprintf knows the buffers size and will not write behind it. But you will
have to use either a static buffer or allocate a dynamic buffer
before being able to call the function. In other words you must
be sure that you really know the maximum size of the buffer required.
A bad thing is having a big maximum while in most cases you would
only need a small buffer. If the size of the resulting string is
longer or equal to the buffer size than the buffer is not terminated.
The function also returns the number of chars not including the
terminating \0 that were needed to fully comply to the print request.
slprintf same as snprintf with the difference that it actually returns the
length printed not including the terminating \0.
spprintf is the dynamical version of snprintf. It allocates the buffer in size
as needed and allows a maximum setting as snprintf (turn this feature
off by setting max_len to 0). spprintf is a little bit slower than
snprintf and offers possible memory leaks if you miss freeing the
buffer allocated by the function. Therefore this function should be
used where either no maximum is known or the maximum is much bigger
than normal size required. spprintf always terminates the buffer.
Example:
#define MAX 1024 | #define MAX 1024 | #define MAX 1024
char buffer[MAX] | char buffer[MAX] | char *buffer;
| |
| | // No need to initialize buffer:
| | // spprintf ignores value of buffer
sprintf(buffer, "test"); | snprintf(buffer, MAX, "test"); | spprintf(&buffer, MAX, "text");
| | if (!buffer)
| | return OUT_OF_MEMORY
// sprintf always terminates | // manual termination of | // spprintf allays terminates buffer
// buffer | // buffer *IS* required |
| buffer[MAX-1] = 0; |
action_with_buffer(buffer); | action_with_buffer(buffer); | action_with_buffer(buffer);
| | efree(buffer);
*/
#ifndef SNPRINTF_H
#define SNPRINTF_H
#include <stdbool.h>
BEGIN_EXTERN_C()
PHPAPI int ap_php_slprintf(char *buf, size_t len, const char *format,...) ZEND_ATTRIBUTE_FORMAT(printf, 3, 4);
PHPAPI int ap_php_vslprintf(char *buf, size_t len, const char *format, va_list ap);
PHPAPI int ap_php_snprintf(char *, size_t, const char *, ...) ZEND_ATTRIBUTE_FORMAT(printf, 3, 4);
PHPAPI int ap_php_vsnprintf(char *, size_t, const char *, va_list ap);
PHPAPI int ap_php_vasprintf(char **buf, const char *format, va_list ap);
PHPAPI int ap_php_asprintf(char **buf, const char *format, ...) ZEND_ATTRIBUTE_FORMAT(printf, 2, 3);
PHPAPI char * php_0cvt(double value, int ndigit, char dec_point, char exponent, char *buf);
PHPAPI char * php_conv_fp(char format, double num,
bool add_dp, int precision, char dec_point, bool * is_negative, char *buf, size_t *len);
END_EXTERN_C()
#define php_gcvt zend_gcvt
#ifdef slprintf
#undef slprintf
#endif
#define slprintf ap_php_slprintf
#ifdef vslprintf
#undef vslprintf
#endif
#define vslprintf ap_php_vslprintf
#ifdef snprintf
#undef snprintf
#endif
#define snprintf ap_php_snprintf
#ifdef vsnprintf
#undef vsnprintf
#endif
#define vsnprintf ap_php_vsnprintf
#ifndef HAVE_VASPRINTF
#define vasprintf ap_php_vasprintf
#endif
#ifndef HAVE_ASPRINTF
#define asprintf ap_php_asprintf
#endif
typedef enum {
LM_STD = 0,
#if SIZEOF_INTMAX_T
LM_INTMAX_T,
#endif
#if SIZEOF_PTRDIFF_T
LM_PTRDIFF_T,
#endif
#if SIZEOF_LONG_LONG
LM_LONG_LONG,
#endif
LM_SIZE_T,
LM_LONG,
LM_LONG_DOUBLE,
} length_modifier_e;
PHPAPI char * ap_php_conv_10(int64_t num, bool is_unsigned,
bool * is_negative, char *buf_end, size_t *len);
PHPAPI char * ap_php_conv_p2(uint64_t num, int nbits,
char format, char *buf_end, size_t *len);
#endif /* SNPRINTF_H */
| 5,730 | 40.832117 | 110 |
h
|
php-src
|
php-src-master/main/spprintf.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef SPPRINTF_H
#define SPPRINTF_H
#include "snprintf.h"
#include "zend_smart_str_public.h"
#include "zend_smart_string_public.h"
BEGIN_EXTERN_C()
PHPAPI void php_printf_to_smart_string(smart_string *buf, const char *format, va_list ap);
PHPAPI void php_printf_to_smart_str(smart_str *buf, const char *format, va_list ap);
END_EXTERN_C()
#define spprintf zend_spprintf
#define strpprintf zend_strpprintf
#define vspprintf zend_vspprintf
#define vstrpprintf zend_vstrpprintf
#endif /* SPPRINTF_H */
| 1,501 | 41.914286 | 90 |
h
|
php-src
|
php-src-master/main/strlcat.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: |
+----------------------------------------------------------------------+
*/
#include "php.h"
#ifdef USE_STRLCAT_PHP_IMPL
/* $OpenBSD: strlcat.c,v 1.18 2016/10/16 17:37:39 dtucker Exp $ */
/*
* Copyright (c) 1998 Todd C. Miller <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static const char *rcsid = "$OpenBSD: strlcat.c,v 1.17 2016/10/14 18:19:04 dtucker Exp $";
#endif /* LIBC_SCCS and not lint */
#include <sys/types.h>
#include <string.h>
/*
* Appends src to string dst of size siz (unlike strncat, siz is the
* full size of dst, not space left). At most siz-1 characters
* will be copied. Always NUL terminates (unless siz <= strlen(dst)).
* Returns strlen(src) + MIN(siz, strlen(initial dst).
* If retval >= siz, truncation occurred.
*/
PHPAPI size_t php_strlcat(char *dst, const char *src, size_t siz)
{
const char *d = dst;
const char *s = src;
size_t n = siz;
size_t dlen;
/* Find the end of dst and adjust bytes left but don't go past end */
while (n-- != 0 && *dst != '\0')
dst++;
dlen = dst - d;
n = siz - dlen;
if (n-- == 0)
return(dlen + strlen(src));
while (*src != '\0') {
if (n != 0) {
*dst++ = *src;
n--;
}
src++;
}
*dst = '\0';
return(dlen + (src - s));
}
#endif /* !HAVE_STRLCAT */
| 3,603 | 38.173913 | 90 |
c
|
php-src
|
php-src-master/main/strlcpy.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: |
+----------------------------------------------------------------------+
*/
#include "php.h"
#ifdef USE_STRLCPY_PHP_IMPL
/* $OpenBSD: strlcpy.c,v 1.15 2016/10/16 17:37:39 dtucker Exp $ */
/*
* Copyright (c) 1998 Todd C. Miller <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static const char *rcsid = "$OpenBSD: strlcpy.c,v 1.15 2016/10/16 17:37:39 dtucker Exp $";
#endif /* LIBC_SCCS and not lint */
#include <sys/types.h>
#include <string.h>
/*
* Copy src to string dst of size siz. At most siz-1 characters
* will be copied. Always NUL terminates (unless siz == 0).
* Returns strlen(src); if retval >= siz, truncation occurred.
*/
PHPAPI size_t php_strlcpy(char *dst, const char *src, size_t siz)
{
const char *s = src;
size_t n = siz;
/* Copy as many bytes as will fit */
if (n != 0) {
while (--n != 0) {
if ((*dst++ = *src++) == 0)
break;
}
}
/* Not enough room in dst, add NUL and traverse rest of src */
if (n == 0) {
if (siz != 0)
*dst = '\0'; /* NUL-terminate dst */
while (*src++)
;
}
return(src - s - 1);
}
#endif /* !HAVE_STRLCPY */
| 3,445 | 38.609195 | 90 |
c
|
php-src
|
php-src-master/main/streams/filter.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Wez Furlong <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "php_globals.h"
#include "php_network.h"
#include "php_open_temporary_file.h"
#include "ext/standard/file.h"
#include <stddef.h>
#include <fcntl.h>
#include "php_streams_int.h"
/* Global filter hash, copied to FG(stream_filters) on registration of volatile filter */
static HashTable stream_filters_hash;
/* Should only be used during core initialization */
PHPAPI HashTable *php_get_stream_filters_hash_global(void)
{
return &stream_filters_hash;
}
/* Normal hash selection/retrieval call */
PHPAPI HashTable *_php_get_stream_filters_hash(void)
{
return (FG(stream_filters) ? FG(stream_filters) : &stream_filters_hash);
}
/* API for registering GLOBAL filters */
PHPAPI int php_stream_filter_register_factory(const char *filterpattern, const php_stream_filter_factory *factory)
{
int ret;
zend_string *str = zend_string_init_interned(filterpattern, strlen(filterpattern), 1);
ret = zend_hash_add_ptr(&stream_filters_hash, str, (void*)factory) ? SUCCESS : FAILURE;
zend_string_release_ex(str, 1);
return ret;
}
PHPAPI int php_stream_filter_unregister_factory(const char *filterpattern)
{
return zend_hash_str_del(&stream_filters_hash, filterpattern, strlen(filterpattern));
}
/* API for registering VOLATILE wrappers */
PHPAPI int php_stream_filter_register_factory_volatile(zend_string *filterpattern, const php_stream_filter_factory *factory)
{
if (!FG(stream_filters)) {
ALLOC_HASHTABLE(FG(stream_filters));
zend_hash_init(FG(stream_filters), zend_hash_num_elements(&stream_filters_hash) + 1, NULL, NULL, 0);
zend_hash_copy(FG(stream_filters), &stream_filters_hash, NULL);
}
return zend_hash_add_ptr(FG(stream_filters), filterpattern, (void*)factory) ? SUCCESS : FAILURE;
}
/* Buckets */
PHPAPI php_stream_bucket *php_stream_bucket_new(php_stream *stream, char *buf, size_t buflen, uint8_t own_buf, uint8_t buf_persistent)
{
int is_persistent = php_stream_is_persistent(stream);
php_stream_bucket *bucket;
bucket = (php_stream_bucket*)pemalloc(sizeof(php_stream_bucket), is_persistent);
bucket->next = bucket->prev = NULL;
if (is_persistent && !buf_persistent) {
/* all data in a persistent bucket must also be persistent */
bucket->buf = pemalloc(buflen, 1);
memcpy(bucket->buf, buf, buflen);
bucket->buflen = buflen;
bucket->own_buf = 1;
} else {
bucket->buf = buf;
bucket->buflen = buflen;
bucket->own_buf = own_buf;
}
bucket->is_persistent = is_persistent;
bucket->refcount = 1;
bucket->brigade = NULL;
return bucket;
}
/* Given a bucket, returns a version of that bucket with a writeable buffer.
* If the original bucket has a refcount of 1 and owns its buffer, then it
* is returned unchanged.
* Otherwise, a copy of the buffer is made.
* In both cases, the original bucket is unlinked from its brigade.
* If a copy is made, the original bucket is delref'd.
* */
PHPAPI php_stream_bucket *php_stream_bucket_make_writeable(php_stream_bucket *bucket)
{
php_stream_bucket *retval;
php_stream_bucket_unlink(bucket);
if (bucket->refcount == 1 && bucket->own_buf) {
return bucket;
}
retval = (php_stream_bucket*)pemalloc(sizeof(php_stream_bucket), bucket->is_persistent);
memcpy(retval, bucket, sizeof(*retval));
retval->buf = pemalloc(retval->buflen, retval->is_persistent);
memcpy(retval->buf, bucket->buf, retval->buflen);
retval->refcount = 1;
retval->own_buf = 1;
php_stream_bucket_delref(bucket);
return retval;
}
PHPAPI int php_stream_bucket_split(php_stream_bucket *in, php_stream_bucket **left, php_stream_bucket **right, size_t length)
{
*left = (php_stream_bucket*)pecalloc(1, sizeof(php_stream_bucket), in->is_persistent);
*right = (php_stream_bucket*)pecalloc(1, sizeof(php_stream_bucket), in->is_persistent);
(*left)->buf = pemalloc(length, in->is_persistent);
(*left)->buflen = length;
memcpy((*left)->buf, in->buf, length);
(*left)->refcount = 1;
(*left)->own_buf = 1;
(*left)->is_persistent = in->is_persistent;
(*right)->buflen = in->buflen - length;
(*right)->buf = pemalloc((*right)->buflen, in->is_persistent);
memcpy((*right)->buf, in->buf + length, (*right)->buflen);
(*right)->refcount = 1;
(*right)->own_buf = 1;
(*right)->is_persistent = in->is_persistent;
return SUCCESS;
}
PHPAPI void php_stream_bucket_delref(php_stream_bucket *bucket)
{
if (--bucket->refcount == 0) {
if (bucket->own_buf) {
pefree(bucket->buf, bucket->is_persistent);
}
pefree(bucket, bucket->is_persistent);
}
}
PHPAPI void php_stream_bucket_prepend(php_stream_bucket_brigade *brigade, php_stream_bucket *bucket)
{
bucket->next = brigade->head;
bucket->prev = NULL;
if (brigade->head) {
brigade->head->prev = bucket;
} else {
brigade->tail = bucket;
}
brigade->head = bucket;
bucket->brigade = brigade;
}
PHPAPI void php_stream_bucket_append(php_stream_bucket_brigade *brigade, php_stream_bucket *bucket)
{
if (brigade->tail == bucket) {
return;
}
bucket->prev = brigade->tail;
bucket->next = NULL;
if (brigade->tail) {
brigade->tail->next = bucket;
} else {
brigade->head = bucket;
}
brigade->tail = bucket;
bucket->brigade = brigade;
}
PHPAPI void php_stream_bucket_unlink(php_stream_bucket *bucket)
{
if (bucket->prev) {
bucket->prev->next = bucket->next;
} else if (bucket->brigade) {
bucket->brigade->head = bucket->next;
}
if (bucket->next) {
bucket->next->prev = bucket->prev;
} else if (bucket->brigade) {
bucket->brigade->tail = bucket->prev;
}
bucket->brigade = NULL;
bucket->next = bucket->prev = NULL;
}
/* We allow very simple pattern matching for filter factories:
* if "convert.charset.utf-8/sjis" is requested, we search first for an exact
* match. If that fails, we try "convert.charset.*", then "convert.*"
* This means that we don't need to clog up the hashtable with a zillion
* charsets (for example) but still be able to provide them all as filters */
PHPAPI php_stream_filter *php_stream_filter_create(const char *filtername, zval *filterparams, uint8_t persistent)
{
HashTable *filter_hash = (FG(stream_filters) ? FG(stream_filters) : &stream_filters_hash);
const php_stream_filter_factory *factory = NULL;
php_stream_filter *filter = NULL;
size_t n;
char *period;
n = strlen(filtername);
if (NULL != (factory = zend_hash_str_find_ptr(filter_hash, filtername, n))) {
filter = factory->create_filter(filtername, filterparams, persistent);
} else if ((period = strrchr(filtername, '.'))) {
/* try a wildcard */
char *wildname;
wildname = safe_emalloc(1, n, 3);
memcpy(wildname, filtername, n+1);
period = wildname + (period - filtername);
while (period && !filter) {
ZEND_ASSERT(period[0] == '.');
period[1] = '*';
period[2] = '\0';
if (NULL != (factory = zend_hash_str_find_ptr(filter_hash, wildname, strlen(wildname)))) {
filter = factory->create_filter(filtername, filterparams, persistent);
}
*period = '\0';
period = strrchr(wildname, '.');
}
efree(wildname);
}
if (filter == NULL) {
/* TODO: these need correct docrefs */
if (factory == NULL)
php_error_docref(NULL, E_WARNING, "Unable to locate filter \"%s\"", filtername);
else
php_error_docref(NULL, E_WARNING, "Unable to create or locate filter \"%s\"", filtername);
}
return filter;
}
PHPAPI php_stream_filter *_php_stream_filter_alloc(const php_stream_filter_ops *fops, void *abstract, uint8_t persistent STREAMS_DC)
{
php_stream_filter *filter;
filter = (php_stream_filter*) pemalloc_rel_orig(sizeof(php_stream_filter), persistent);
memset(filter, 0, sizeof(php_stream_filter));
filter->fops = fops;
Z_PTR(filter->abstract) = abstract;
filter->is_persistent = persistent;
return filter;
}
PHPAPI void php_stream_filter_free(php_stream_filter *filter)
{
if (filter->fops->dtor)
filter->fops->dtor(filter);
pefree(filter, filter->is_persistent);
}
PHPAPI int php_stream_filter_prepend_ex(php_stream_filter_chain *chain, php_stream_filter *filter)
{
filter->next = chain->head;
filter->prev = NULL;
if (chain->head) {
chain->head->prev = filter;
} else {
chain->tail = filter;
}
chain->head = filter;
filter->chain = chain;
return SUCCESS;
}
PHPAPI void _php_stream_filter_prepend(php_stream_filter_chain *chain, php_stream_filter *filter)
{
php_stream_filter_prepend_ex(chain, filter);
}
PHPAPI int php_stream_filter_append_ex(php_stream_filter_chain *chain, php_stream_filter *filter)
{
php_stream *stream = chain->stream;
filter->prev = chain->tail;
filter->next = NULL;
if (chain->tail) {
chain->tail->next = filter;
} else {
chain->head = filter;
}
chain->tail = filter;
filter->chain = chain;
if (&(stream->readfilters) == chain && (stream->writepos - stream->readpos) > 0) {
/* Let's going ahead and wind anything in the buffer through this filter */
php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL };
php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out;
php_stream_filter_status_t status;
php_stream_bucket *bucket;
size_t consumed = 0;
bucket = php_stream_bucket_new(stream, (char*) stream->readbuf + stream->readpos, stream->writepos - stream->readpos, 0, 0);
php_stream_bucket_append(brig_inp, bucket);
status = filter->fops->filter(stream, filter, brig_inp, brig_outp, &consumed, PSFS_FLAG_NORMAL);
if (stream->readpos + consumed > (uint32_t)stream->writepos) {
/* No behaving filter should cause this. */
status = PSFS_ERR_FATAL;
}
switch (status) {
case PSFS_ERR_FATAL:
while (brig_in.head) {
bucket = brig_in.head;
php_stream_bucket_unlink(bucket);
php_stream_bucket_delref(bucket);
}
while (brig_out.head) {
bucket = brig_out.head;
php_stream_bucket_unlink(bucket);
php_stream_bucket_delref(bucket);
}
php_error_docref(NULL, E_WARNING, "Filter failed to process pre-buffered data");
return FAILURE;
case PSFS_FEED_ME:
/* We don't actually need data yet,
leave this filter in a feed me state until data is needed.
Reset stream's internal read buffer since the filter is "holding" it. */
stream->readpos = 0;
stream->writepos = 0;
break;
case PSFS_PASS_ON:
/* If any data is consumed, we cannot rely upon the existing read buffer,
as the filtered data must replace the existing data, so invalidate the cache */
stream->writepos = 0;
stream->readpos = 0;
while (brig_outp->head) {
bucket = brig_outp->head;
/* Grow buffer to hold this bucket if need be.
TODO: See warning in main/stream/streams.c::php_stream_fill_read_buffer */
if (stream->readbuflen - stream->writepos < bucket->buflen) {
stream->readbuflen += bucket->buflen;
stream->readbuf = perealloc(stream->readbuf, stream->readbuflen, stream->is_persistent);
}
memcpy(stream->readbuf + stream->writepos, bucket->buf, bucket->buflen);
stream->writepos += bucket->buflen;
php_stream_bucket_unlink(bucket);
php_stream_bucket_delref(bucket);
}
break;
}
}
return SUCCESS;
}
PHPAPI void _php_stream_filter_append(php_stream_filter_chain *chain, php_stream_filter *filter)
{
if (php_stream_filter_append_ex(chain, filter) != SUCCESS) {
if (chain->head == filter) {
chain->head = NULL;
chain->tail = NULL;
} else {
filter->prev->next = NULL;
chain->tail = filter->prev;
}
}
}
PHPAPI int _php_stream_filter_flush(php_stream_filter *filter, int finish)
{
php_stream_bucket_brigade brig_a = { NULL, NULL }, brig_b = { NULL, NULL }, *inp = &brig_a, *outp = &brig_b, *brig_temp;
php_stream_bucket *bucket;
php_stream_filter_chain *chain;
php_stream_filter *current;
php_stream *stream;
size_t flushed_size = 0;
long flags = (finish ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC);
if (!filter->chain || !filter->chain->stream) {
/* Filter is not attached to a chain, or chain is somehow not part of a stream */
return FAILURE;
}
chain = filter->chain;
stream = chain->stream;
for(current = filter; current; current = current->next) {
php_stream_filter_status_t status;
status = current->fops->filter(stream, current, inp, outp, NULL, flags);
if (status == PSFS_FEED_ME) {
/* We've flushed the data far enough */
return SUCCESS;
}
if (status == PSFS_ERR_FATAL) {
return FAILURE;
}
/* Otherwise we have data available to PASS_ON
Swap the brigades and continue */
brig_temp = inp;
inp = outp;
outp = brig_temp;
outp->head = NULL;
outp->tail = NULL;
flags = PSFS_FLAG_NORMAL;
}
/* Last filter returned data via PSFS_PASS_ON
Do something with it */
for(bucket = inp->head; bucket; bucket = bucket->next) {
flushed_size += bucket->buflen;
}
if (flushed_size == 0) {
/* Unlikely, but possible */
return SUCCESS;
}
if (chain == &(stream->readfilters)) {
/* Dump any newly flushed data to the read buffer */
if (stream->readpos > 0) {
/* Back the buffer up */
memcpy(stream->readbuf, stream->readbuf + stream->readpos, stream->writepos - stream->readpos);
stream->readpos = 0;
stream->writepos -= stream->readpos;
}
if (flushed_size > (stream->readbuflen - stream->writepos)) {
/* Grow the buffer */
stream->readbuf = perealloc(stream->readbuf, stream->writepos + flushed_size + stream->chunk_size, stream->is_persistent);
}
while ((bucket = inp->head)) {
memcpy(stream->readbuf + stream->writepos, bucket->buf, bucket->buflen);
stream->writepos += bucket->buflen;
php_stream_bucket_unlink(bucket);
php_stream_bucket_delref(bucket);
}
} else if (chain == &(stream->writefilters)) {
/* Send flushed data to the stream */
while ((bucket = inp->head)) {
ssize_t count = stream->ops->write(stream, bucket->buf, bucket->buflen);
if (count > 0) {
stream->position += count;
}
php_stream_bucket_unlink(bucket);
php_stream_bucket_delref(bucket);
}
}
return SUCCESS;
}
PHPAPI php_stream_filter *php_stream_filter_remove(php_stream_filter *filter, int call_dtor)
{
if (filter->prev) {
filter->prev->next = filter->next;
} else {
filter->chain->head = filter->next;
}
if (filter->next) {
filter->next->prev = filter->prev;
} else {
filter->chain->tail = filter->prev;
}
if (filter->res) {
zend_list_delete(filter->res);
}
if (call_dtor) {
php_stream_filter_free(filter);
return NULL;
}
return filter;
}
| 15,315 | 29.268775 | 134 |
c
|
php-src
|
php-src-master/main/streams/glob_wrapper.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "php_streams_int.h"
#ifdef HAVE_GLOB
# ifndef PHP_WIN32
# include <glob.h>
# else
# include "win32/glob.h"
# endif
#endif
#ifdef HAVE_GLOB
#ifndef GLOB_ONLYDIR
#define GLOB_ONLYDIR (1<<30)
#define GLOB_FLAGMASK (~GLOB_ONLYDIR)
#else
#define GLOB_FLAGMASK (~0)
#endif
typedef struct {
glob_t glob;
size_t index;
int flags;
char *path;
size_t path_len;
char *pattern;
size_t pattern_len;
size_t *open_basedir_indexmap;
size_t open_basedir_indexmap_size;
bool open_basedir_used;
} glob_s_t;
PHPAPI char* _php_glob_stream_get_path(php_stream *stream, size_t *plen STREAMS_DC) /* {{{ */
{
glob_s_t *pglob = (glob_s_t *)stream->abstract;
if (pglob && pglob->path) {
if (plen) {
*plen = pglob->path_len;
}
return pglob->path;
} else {
if (plen) {
*plen = 0;
}
return NULL;
}
}
/* }}} */
PHPAPI char* _php_glob_stream_get_pattern(php_stream *stream, size_t *plen STREAMS_DC) /* {{{ */
{
glob_s_t *pglob = (glob_s_t *)stream->abstract;
if (pglob && pglob->pattern) {
if (plen) {
*plen = pglob->pattern_len;
}
return pglob->pattern;
} else {
if (plen) {
*plen = 0;
}
return NULL;
}
}
/* }}} */
static inline int php_glob_stream_get_result_count(glob_s_t *pglob)
{
return pglob->open_basedir_used ? (int) pglob->open_basedir_indexmap_size : pglob->glob.gl_pathc;
}
PHPAPI int _php_glob_stream_get_count(php_stream *stream, int *pflags STREAMS_DC) /* {{{ */
{
glob_s_t *pglob = (glob_s_t *)stream->abstract;
if (pglob) {
if (pflags) {
*pflags = pglob->flags;
}
return php_glob_stream_get_result_count(pglob);
} else {
if (pflags) {
*pflags = 0;
}
return 0;
}
}
/* }}} */
static void php_glob_stream_path_split(glob_s_t *pglob, const char *path, int get_path, const char **p_file) /* {{{ */
{
const char *pos, *gpath = path;
if ((pos = strrchr(path, '/')) != NULL) {
path = pos+1;
}
#ifdef PHP_WIN32
if ((pos = strrchr(path, '\\')) != NULL) {
path = pos+1;
}
#endif
*p_file = path;
if (get_path) {
if (pglob->path) {
efree(pglob->path);
}
if ((path - gpath) > 1) {
path--;
}
pglob->path_len = path - gpath;
pglob->path = estrndup(gpath, pglob->path_len);
}
}
/* }}} */
static ssize_t php_glob_stream_read(php_stream *stream, char *buf, size_t count) /* {{{ */
{
glob_s_t *pglob = (glob_s_t *)stream->abstract;
php_stream_dirent *ent = (php_stream_dirent*)buf;
const char *path;
int glob_result_count;
size_t index;
/* avoid problems if someone mis-uses the stream */
if (count == sizeof(php_stream_dirent) && pglob) {
glob_result_count = php_glob_stream_get_result_count(pglob);
if (pglob->index < (size_t) glob_result_count) {
index = pglob->open_basedir_used && pglob->open_basedir_indexmap ?
pglob->open_basedir_indexmap[pglob->index] : pglob->index;
php_glob_stream_path_split(pglob, pglob->glob.gl_pathv[index], pglob->flags & GLOB_APPEND, &path);
++pglob->index;
PHP_STRLCPY(ent->d_name, path, sizeof(ent->d_name), strlen(path));
ent->d_type = DT_UNKNOWN;
return sizeof(php_stream_dirent);
}
pglob->index = glob_result_count;
if (pglob->path) {
efree(pglob->path);
pglob->path = NULL;
}
}
return -1;
}
/* }}} */
static int php_glob_stream_close(php_stream *stream, int close_handle) /* {{{ */
{
glob_s_t *pglob = (glob_s_t *)stream->abstract;
if (pglob) {
pglob->index = 0;
globfree(&pglob->glob);
if (pglob->path) {
efree(pglob->path);
}
if (pglob->pattern) {
efree(pglob->pattern);
}
if (pglob->open_basedir_indexmap) {
efree(pglob->open_basedir_indexmap);
}
}
efree(stream->abstract);
return 0;
}
/* {{{ */
static int php_glob_stream_rewind(php_stream *stream, zend_off_t offset, int whence, zend_off_t *newoffs) /* {{{ */
{
glob_s_t *pglob = (glob_s_t *)stream->abstract;
if (pglob) {
pglob->index = 0;
if (pglob->path) {
efree(pglob->path);
pglob->path = NULL;
}
}
return 0;
}
/* }}} */
const php_stream_ops php_glob_stream_ops = {
NULL, php_glob_stream_read,
php_glob_stream_close, NULL,
"glob",
php_glob_stream_rewind,
NULL, /* cast */
NULL, /* stat */
NULL /* set_option */
};
/* {{{ php_glob_stream_opener */
static php_stream *php_glob_stream_opener(php_stream_wrapper *wrapper, const char *path, const char *mode,
int options, zend_string **opened_path, php_stream_context *context STREAMS_DC)
{
glob_s_t *pglob;
int ret, i;
const char *tmp, *pos;
if (!strncmp(path, "glob://", sizeof("glob://")-1)) {
path += sizeof("glob://")-1;
if (opened_path) {
*opened_path = zend_string_init(path, strlen(path), 0);
}
}
pglob = ecalloc(sizeof(*pglob), 1);
if (0 != (ret = glob(path, pglob->flags & GLOB_FLAGMASK, NULL, &pglob->glob))) {
#ifdef GLOB_NOMATCH
if (GLOB_NOMATCH != ret)
#endif
{
efree(pglob);
return NULL;
}
}
/* if open_basedir in use, check and filter restricted paths */
if ((options & STREAM_DISABLE_OPEN_BASEDIR) == 0) {
pglob->open_basedir_used = true;
for (i = 0; i < pglob->glob.gl_pathc; i++) {
if (!php_check_open_basedir_ex(pglob->glob.gl_pathv[i], 0)) {
if (!pglob->open_basedir_indexmap) {
pglob->open_basedir_indexmap = (size_t *) safe_emalloc(
pglob->glob.gl_pathc, sizeof(size_t), 0);
}
pglob->open_basedir_indexmap[pglob->open_basedir_indexmap_size++] = i;
}
}
}
pos = path;
if ((tmp = strrchr(pos, '/')) != NULL) {
pos = tmp+1;
}
#ifdef PHP_WIN32
if ((tmp = strrchr(pos, '\\')) != NULL) {
pos = tmp+1;
}
#endif
pglob->pattern_len = strlen(pos);
pglob->pattern = estrndup(pos, pglob->pattern_len);
pglob->flags |= GLOB_APPEND;
if (pglob->glob.gl_pathc) {
php_glob_stream_path_split(pglob, pglob->glob.gl_pathv[0], 1, &tmp);
} else {
php_glob_stream_path_split(pglob, path, 1, &tmp);
}
return php_stream_alloc(&php_glob_stream_ops, pglob, 0, mode);
}
/* }}} */
static const php_stream_wrapper_ops php_glob_stream_wrapper_ops = {
NULL,
NULL,
NULL,
NULL,
php_glob_stream_opener,
"glob",
NULL,
NULL,
NULL,
NULL,
NULL
};
const php_stream_wrapper php_glob_stream_wrapper = {
&php_glob_stream_wrapper_ops,
NULL,
0
};
#endif /* HAVE_GLOB */
| 7,163 | 22.88 | 118 |
c
|
php-src
|
php-src-master/main/streams/php_stream_glob_wrapper.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
PHPAPI extern const php_stream_wrapper php_glob_stream_wrapper;
PHPAPI extern const php_stream_ops php_glob_stream_ops;
BEGIN_EXTERN_C()
PHPAPI char* _php_glob_stream_get_path(php_stream *stream, size_t *plen STREAMS_DC);
#define php_glob_stream_get_path(stream, plen) _php_glob_stream_get_path((stream), (plen) STREAMS_CC)
PHPAPI char* _php_glob_stream_get_pattern(php_stream *stream, size_t *plen STREAMS_DC);
#define php_glob_stream_get_pattern(stream, plen) _php_glob_stream_get_pattern((stream), (plen) STREAMS_CC)
PHPAPI int _php_glob_stream_get_count(php_stream *stream, int *pflags STREAMS_DC);
#define php_glob_stream_get_count(stream, pflags) _php_glob_stream_get_count((stream), (pflags) STREAMS_CC)
END_EXTERN_C()
| 1,733 | 53.1875 | 107 |
h
|
php-src
|
php-src-master/main/streams/php_stream_userspace.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Wez Furlong <[email protected]> |
+----------------------------------------------------------------------+
*/
/* for user-space streams */
PHPAPI extern const php_stream_ops php_stream_userspace_ops;
PHPAPI extern const php_stream_ops php_stream_userspace_dir_ops;
#define PHP_STREAM_IS_USERSPACE &php_stream_userspace_ops
#define PHP_STREAM_IS_USERSPACE_DIR &php_stream_userspace_dir_ops
| 1,275 | 57 | 75 |
h
|
php-src
|
php-src-master/main/streams/php_streams_int.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Wez Furlong <[email protected]> |
+----------------------------------------------------------------------+
*/
#if ZEND_DEBUG
#define emalloc_rel_orig(size) \
( __php_stream_call_depth == 0 \
? _emalloc((size) ZEND_FILE_LINE_CC ZEND_FILE_LINE_RELAY_CC) \
: _emalloc((size) ZEND_FILE_LINE_CC ZEND_FILE_LINE_ORIG_RELAY_CC) )
#define erealloc_rel_orig(ptr, size) \
( __php_stream_call_depth == 0 \
? _erealloc((ptr), (size), 0 ZEND_FILE_LINE_CC ZEND_FILE_LINE_RELAY_CC) \
: _erealloc((ptr), (size), 0 ZEND_FILE_LINE_CC ZEND_FILE_LINE_ORIG_RELAY_CC) )
#define pemalloc_rel_orig(size, persistent) ((persistent) ? malloc((size)) : emalloc_rel_orig((size)))
#define perealloc_rel_orig(ptr, size, persistent) ((persistent) ? realloc((ptr), (size)) : erealloc_rel_orig((ptr), (size)))
#else
# define pemalloc_rel_orig(size, persistent) pemalloc((size), (persistent))
# define perealloc_rel_orig(ptr, size, persistent) perealloc((ptr), (size), (persistent))
# define emalloc_rel_orig(size) emalloc((size))
#endif
#define STREAM_DEBUG 0
#define STREAM_WRAPPER_PLAIN_FILES ((php_stream_wrapper*)-1)
#ifndef MAP_FAILED
#define MAP_FAILED ((void *) -1)
#endif
#define CHUNK_SIZE 8192
#ifdef PHP_WIN32
# ifdef EWOULDBLOCK
# undef EWOULDBLOCK
# endif
# define EWOULDBLOCK WSAEWOULDBLOCK
# ifdef EMSGSIZE
# undef EMSGSIZE
# endif
# define EMSGSIZE WSAEMSGSIZE
#endif
/* This functions transforms the first char to 'w' if it's not 'r', 'a' or 'w'
* and strips any subsequent chars except '+' and 'b'.
* Use this to sanitize stream->mode if you call e.g. fdopen, fopencookie or
* any other function that expects standard modes and you allow non-standard
* ones. result should be a char[5]. */
void php_stream_mode_sanitize_fdopen_fopencookie(php_stream *stream, char *result);
| 2,667 | 41.349206 | 124 |
h
|
php-src
|
php-src-master/main/streams/userspace_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: 9198095c858c95fcb31252ddfa24fe04787d0460 */
static void register_userspace_symbols(int module_number)
{
REGISTER_LONG_CONSTANT("STREAM_USE_PATH", USE_PATH, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_IGNORE_URL", IGNORE_URL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_REPORT_ERRORS", REPORT_ERRORS, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_MUST_SEEK", STREAM_MUST_SEEK, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_URL_STAT_LINK", PHP_STREAM_URL_STAT_LINK, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_URL_STAT_QUIET", PHP_STREAM_URL_STAT_QUIET, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_MKDIR_RECURSIVE", PHP_STREAM_MKDIR_RECURSIVE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_IS_URL", PHP_STREAM_IS_URL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_OPTION_BLOCKING", PHP_STREAM_OPTION_BLOCKING, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_OPTION_READ_TIMEOUT", PHP_STREAM_OPTION_READ_TIMEOUT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_OPTION_READ_BUFFER", PHP_STREAM_OPTION_READ_BUFFER, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_OPTION_WRITE_BUFFER", PHP_STREAM_OPTION_WRITE_BUFFER, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_BUFFER_NONE", PHP_STREAM_BUFFER_NONE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_BUFFER_LINE", PHP_STREAM_BUFFER_LINE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_BUFFER_FULL", PHP_STREAM_BUFFER_FULL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_CAST_AS_STREAM", PHP_STREAM_AS_STDIO, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_CAST_FOR_SELECT", PHP_STREAM_AS_FD_FOR_SELECT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_META_TOUCH", PHP_STREAM_META_TOUCH, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_META_OWNER", PHP_STREAM_META_OWNER, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_META_OWNER_NAME", PHP_STREAM_META_OWNER_NAME, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_META_GROUP", PHP_STREAM_META_GROUP, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_META_GROUP_NAME", PHP_STREAM_META_GROUP_NAME, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("STREAM_META_ACCESS", PHP_STREAM_META_ACCESS, CONST_PERSISTENT);
}
| 2,268 | 69.90625 | 104 |
h
|
php-src
|
php-src-master/sapi/apache2handler/mod_php.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Sascha Schumann <[email protected]> |
| Parts based on Apache 1.3 SAPI module by |
| Rasmus Lerdorf and Zeev Suraski |
+----------------------------------------------------------------------+
*/
#define ZEND_INCLUDE_FULL_WINDOWS_HEADERS
#include "php.h"
#ifdef strcasecmp
# undef strcasecmp
#endif
#ifdef strncasecmp
# undef strncasecmp
#endif
#include "php_apache.h"
AP_MODULE_DECLARE_DATA module php_module = {
STANDARD20_MODULE_STUFF,
create_php_config, /* create per-directory config structure */
merge_php_config, /* merge per-directory config structures */
NULL, /* create per-server config structure */
NULL, /* merge per-server config structures */
php_dir_cmds, /* command apr_table_t */
php_ap2_register_hook, /* register hooks */
0 /* flags */
};
| 1,738 | 42.475 | 75 |
c
|
php-src
|
php-src-master/sapi/apache2handler/php_apache.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Sascha Schumann <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_APACHE_H
#define PHP_APACHE_H
#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_log.h"
#include "php.h"
#include "main/php_streams.h"
/* Enable per-module logging in Apache 2.4+ */
#ifdef APLOG_USE_MODULE
APLOG_USE_MODULE(php);
#endif
/* Declare this so we can get to it from outside the sapi_apache2.c file */
extern module AP_MODULE_DECLARE_DATA php_module;
/* A way to specify the location of the php.ini dir in an apache directive */
extern char *apache2_php_ini_path_override;
/* The server_context used by PHP */
typedef struct php_struct {
int state;
request_rec *r;
apr_bucket_brigade *brigade;
/* stat structure of the current file */
zend_stat_t finfo;
/* Whether or not we've processed PHP in the output filters yet. */
int request_processed;
/* final content type */
char *content_type;
} php_struct;
void *merge_php_config(apr_pool_t *p, void *base_conf, void *new_conf);
void *create_php_config(apr_pool_t *p, char *dummy);
char *get_php_config(void *conf, char *name, size_t name_len);
void apply_config(void *);
extern const command_rec php_dir_cmds[];
void php_ap2_register_hook(apr_pool_t *p);
#define APR_ARRAY_FOREACH_OPEN(arr, key, val) \
{ \
apr_table_entry_t *elts; \
int i; \
elts = (apr_table_entry_t *) arr->elts; \
for (i = 0; i < arr->nelts; i++) { \
key = elts[i].key; \
val = elts[i].val;
#define APR_ARRAY_FOREACH_CLOSE() }}
typedef struct {
bool engine;
bool xbithack;
bool last_modified;
} php_apache2_info_struct;
extern zend_module_entry apache2_module_entry;
#ifdef ZTS
extern int php_apache2_info_id;
#define AP2(v) ZEND_TSRMG(php_apache2_info_id, php_apache2_info_struct *, v)
ZEND_TSRMLS_CACHE_EXTERN()
#else
extern php_apache2_info_struct php_apache2_info;
#define AP2(v) (php_apache2_info.v)
#endif
/* fix for gcc4 visibility patch */
#ifndef PHP_WIN32
# undef AP_MODULE_DECLARE_DATA
# define AP_MODULE_DECLARE_DATA PHPAPI
#endif
#endif /* PHP_APACHE_H */
| 3,011 | 31.042553 | 77 |
h
|
php-src
|
php-src-master/sapi/apache2handler/php_functions_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: 130666f6f971fe7b43a450d922e4b3d092e78667 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_apache_lookup_uri, 0, 1, MAY_BE_OBJECT|MAY_BE_FALSE)
ZEND_ARG_TYPE_INFO(0, filename, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_virtual, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, uri, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_apache_request_headers, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
#define arginfo_getallheaders arginfo_apache_request_headers
#define arginfo_apache_response_headers arginfo_apache_request_headers
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_apache_note, 0, 1, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_TYPE_INFO(0, note_name, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, note_value, IS_STRING, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_apache_setenv, 0, 2, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, variable, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, value, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, walk_to_top, _IS_BOOL, 0, "false")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_apache_getenv, 0, 1, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_TYPE_INFO(0, variable, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, walk_to_top, _IS_BOOL, 0, "false")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_apache_get_version, 0, 0, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_END_ARG_INFO()
#define arginfo_apache_get_modules arginfo_apache_request_headers
ZEND_FUNCTION(apache_lookup_uri);
ZEND_FUNCTION(virtual);
ZEND_FUNCTION(apache_request_headers);
ZEND_FUNCTION(apache_response_headers);
ZEND_FUNCTION(apache_note);
ZEND_FUNCTION(apache_setenv);
ZEND_FUNCTION(apache_getenv);
ZEND_FUNCTION(apache_get_version);
ZEND_FUNCTION(apache_get_modules);
static const zend_function_entry ext_functions[] = {
ZEND_FE(apache_lookup_uri, arginfo_apache_lookup_uri)
ZEND_FE(virtual, arginfo_virtual)
ZEND_FE(apache_request_headers, arginfo_apache_request_headers)
ZEND_FALIAS(getallheaders, apache_request_headers, arginfo_getallheaders)
ZEND_FE(apache_response_headers, arginfo_apache_response_headers)
ZEND_FE(apache_note, arginfo_apache_note)
ZEND_FE(apache_setenv, arginfo_apache_setenv)
ZEND_FE(apache_getenv, arginfo_apache_getenv)
ZEND_FE(apache_get_version, arginfo_apache_get_version)
ZEND_FE(apache_get_modules, arginfo_apache_get_modules)
ZEND_FE_END
};
| 2,533 | 37.984615 | 101 |
h
|
php-src
|
php-src-master/sapi/cgi/cgi_main_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: df963adc6bc610cdd31861036889141fa9464ded */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_apache_child_terminate, 0, 0, IS_VOID, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_apache_request_headers, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
#define arginfo_getallheaders arginfo_apache_request_headers
#define arginfo_apache_response_headers arginfo_apache_request_headers
ZEND_FUNCTION(apache_child_terminate);
ZEND_FUNCTION(apache_request_headers);
ZEND_FUNCTION(apache_response_headers);
static const zend_function_entry ext_functions[] = {
ZEND_FE(apache_child_terminate, arginfo_apache_child_terminate)
ZEND_FE(apache_request_headers, arginfo_apache_request_headers)
ZEND_FALIAS(getallheaders, apache_request_headers, arginfo_getallheaders)
ZEND_FE(apache_response_headers, arginfo_apache_response_headers)
ZEND_FE_END
};
| 940 | 33.851852 | 90 |
h
|
php-src
|
php-src-master/sapi/cli/cli.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Johannes Schlueter <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef CLI_H
#define CLI_H
#ifdef PHP_WIN32
# define PHP_CLI_API __declspec(dllexport)
#elif defined(__GNUC__) && __GNUC__ >= 4
# define PHP_CLI_API __attribute__ ((visibility("default")))
#else
# define PHP_CLI_API
#endif
extern PHP_CLI_API ssize_t sapi_cli_single_write(const char *str, size_t str_length);
typedef struct {
size_t (*cli_shell_write)(const char *str, size_t str_length);
size_t (*cli_shell_ub_write)(const char *str, size_t str_length);
int (*cli_shell_run)(void);
} cli_shell_callbacks_t;
extern PHP_CLI_API cli_shell_callbacks_t *php_cli_get_shell_callbacks(void);
#endif /* CLI_H */
| 1,603 | 39.1 | 85 |
h
|
php-src
|
php-src-master/sapi/cli/php_cli_process_title.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Keyur Govande ([email protected]) |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_cli_process_title.h"
#include "ps_title.h"
/* {{{ Return a boolean to confirm if the process title was successfully changed or not */
PHP_FUNCTION(cli_set_process_title)
{
char *title = NULL;
size_t title_len;
int rc;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &title, &title_len) == FAILURE) {
RETURN_THROWS();
}
rc = set_ps_title(title);
if (rc == PS_TITLE_SUCCESS) {
RETURN_TRUE;
}
php_error_docref(NULL, E_WARNING, "cli_set_process_title had an error: %s", ps_title_errno(rc));
RETURN_FALSE;
}
/* }}} */
/* {{{ Return a string with the current process title. NULL if error. */
PHP_FUNCTION(cli_get_process_title)
{
size_t length = 0;
const char* title = NULL;
int rc;
if (zend_parse_parameters_none() == FAILURE) {
RETURN_THROWS();
}
rc = get_ps_title(&length, &title);
if (rc != PS_TITLE_SUCCESS) {
php_error_docref(NULL, E_WARNING, "cli_get_process_title had an error: %s", ps_title_errno(rc));
RETURN_NULL();
}
RETURN_STRINGL(title, length);
}
/* }}} */
| 2,067 | 30.333333 | 99 |
c
|
php-src
|
php-src-master/sapi/cli/php_cli_process_title.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Keyur Govande ([email protected]) |
+----------------------------------------------------------------------+
*/
#ifndef PHP_PS_TITLE_HEADER
#define PHP_PS_TITLE_HEADER
PHP_FUNCTION(cli_set_process_title);
PHP_FUNCTION(cli_get_process_title);
#endif
| 1,121 | 45.75 | 74 |
h
|
php-src
|
php-src-master/sapi/cli/php_cli_server.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Moriyoshi Koizumi <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_CLI_SERVER_H
#define PHP_CLI_SERVER_H
#include "SAPI.h"
extern const zend_function_entry server_additional_functions[];
extern sapi_module_struct cli_server_sapi_module;
extern int do_cli_server(int argc, char **argv);
ZEND_BEGIN_MODULE_GLOBALS(cli_server)
short color;
ZEND_END_MODULE_GLOBALS(cli_server)
#ifdef ZTS
#define CLI_SERVER_G(v) ZEND_TSRMG(cli_server_globals_id, zend_cli_server_globals *, v)
ZEND_TSRMLS_CACHE_EXTERN()
#else
#define CLI_SERVER_G(v) (cli_server_globals.v)
#endif
#endif /* PHP_CLI_SERVER_H */
| 1,535 | 39.421053 | 87 |
h
|
php-src
|
php-src-master/sapi/cli/php_http_parser.h
|
/* Copyright 2009,2010 Ryan Dahl <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/* modified by Moriyoshi Koizumi <[email protected]> to make it fit to PHP source tree. */
#ifndef php_http_parser_h
#define php_http_parser_h
#ifdef __cplusplus
extern "C" {
#endif
#include <sys/types.h>
#if defined(_WIN32) && !defined(__MINGW32__)
# include <windows.h>
# include "config.w32.h"
#else
# include "php_config.h"
#endif
#include <stdint.h>
/* Compile with -DPHP_HTTP_PARSER_STRICT=0 to make less checks, but run
* faster
*/
#ifndef PHP_HTTP_PARSER_STRICT
# define PHP_HTTP_PARSER_STRICT 1
#else
# define PHP_HTTP_PARSER_STRICT 0
#endif
/* Maximum header size allowed */
#define PHP_HTTP_MAX_HEADER_SIZE (80*1024)
typedef struct php_http_parser php_http_parser;
typedef struct php_http_parser_settings php_http_parser_settings;
/* Callbacks should return non-zero to indicate an error. The parser will
* then halt execution.
*
* The one exception is on_headers_complete. In a PHP_HTTP_RESPONSE parser
* returning '1' from on_headers_complete will tell the parser that it
* should not expect a body. This is used when receiving a response to a
* HEAD request which may contain 'Content-Length' or 'Transfer-Encoding:
* chunked' headers that indicate the presence of a body.
*
* http_data_cb does not return data chunks. It will be call arbitrarily
* many times for each string. E.G. you might get 10 callbacks for "on_path"
* each providing just a few characters more data.
*/
typedef int (*php_http_data_cb) (php_http_parser*, const char *at, size_t length);
typedef int (*php_http_cb) (php_http_parser*);
/* Request Methods */
enum php_http_method
{ PHP_HTTP_DELETE = 0
, PHP_HTTP_GET
, PHP_HTTP_HEAD
, PHP_HTTP_POST
, PHP_HTTP_PUT
, PHP_HTTP_PATCH
/* pathological */
, PHP_HTTP_CONNECT
, PHP_HTTP_OPTIONS
, PHP_HTTP_TRACE
/* webdav */
, PHP_HTTP_COPY
, PHP_HTTP_LOCK
, PHP_HTTP_MKCOL
, PHP_HTTP_MOVE
, PHP_HTTP_MKCALENDAR
, PHP_HTTP_PROPFIND
, PHP_HTTP_PROPPATCH
, PHP_HTTP_SEARCH
, PHP_HTTP_UNLOCK
/* subversion */
, PHP_HTTP_REPORT
, PHP_HTTP_MKACTIVITY
, PHP_HTTP_CHECKOUT
, PHP_HTTP_MERGE
/* upnp */
, PHP_HTTP_MSEARCH
, PHP_HTTP_NOTIFY
, PHP_HTTP_SUBSCRIBE
, PHP_HTTP_UNSUBSCRIBE
/* unknown, not implemented */
, PHP_HTTP_NOT_IMPLEMENTED
};
enum php_http_parser_type { PHP_HTTP_REQUEST, PHP_HTTP_RESPONSE, PHP_HTTP_BOTH };
enum state
{ s_dead = 1 /* important that this is > 0 */
, s_start_req_or_res
, s_res_or_resp_H
, s_start_res
, s_res_H
, s_res_HT
, s_res_HTT
, s_res_HTTP
, s_res_first_http_major
, s_res_http_major
, s_res_first_http_minor
, s_res_http_minor
, s_res_first_status_code
, s_res_status_code
, s_res_status
, s_res_line_almost_done
, s_start_req
, s_req_method
, s_req_spaces_before_url
, s_req_schema
, s_req_schema_slash
, s_req_schema_slash_slash
, s_req_host
, s_req_port
, s_req_path
, s_req_query_string_start
, s_req_query_string
, s_req_fragment_start
, s_req_fragment
, s_req_http_start
, s_req_http_H
, s_req_http_HT
, s_req_http_HTT
, s_req_http_HTTP
, s_req_first_http_major
, s_req_http_major
, s_req_first_http_minor
, s_req_http_minor
, s_req_line_almost_done
, s_header_field_start
, s_header_field
, s_header_value_start
, s_header_value
, s_header_almost_done
, s_headers_almost_done
/* Important: 's_headers_almost_done' must be the last 'header' state. All
* states beyond this must be 'body' states. It is used for overflow
* checking. See the PARSING_HEADER() macro.
*/
, s_chunk_size_start
, s_chunk_size
, s_chunk_size_almost_done
, s_chunk_parameters
, s_chunk_data
, s_chunk_data_almost_done
, s_chunk_data_done
, s_body_identity
, s_body_identity_eof
};
struct php_http_parser {
/** PRIVATE **/
unsigned char type : 2;
unsigned char flags : 6;
unsigned char state;
unsigned char header_state;
unsigned char index;
uint32_t nread;
ssize_t content_length;
/** READ-ONLY **/
unsigned short http_major;
unsigned short http_minor;
unsigned short status_code; /* responses only */
unsigned char method; /* requests only */
/* 1 = Upgrade header was present and the parser has exited because of that.
* 0 = No upgrade header present.
* Should be checked when http_parser_execute() returns in addition to
* error checking.
*/
char upgrade;
/** PUBLIC **/
void *data; /* A pointer to get hook to the "connection" or "socket" object */
};
struct php_http_parser_settings {
php_http_cb on_message_begin;
php_http_data_cb on_path;
php_http_data_cb on_query_string;
php_http_data_cb on_url;
php_http_data_cb on_fragment;
php_http_data_cb on_header_field;
php_http_data_cb on_header_value;
php_http_cb on_headers_complete;
php_http_data_cb on_body;
php_http_cb on_message_complete;
};
void php_http_parser_init(php_http_parser *parser, enum php_http_parser_type type);
size_t php_http_parser_execute(php_http_parser *parser,
const php_http_parser_settings *settings,
const char *data,
size_t len);
/* If php_http_should_keep_alive() in the on_headers_complete or
* on_message_complete callback returns true, then this will be should be
* the last message on the connection.
* If you are the server, respond with the "Connection: close" header.
* If you are the client, close the connection.
*/
int php_http_should_keep_alive(php_http_parser *parser);
/* Returns a string version of the HTTP method. */
const char *php_http_method_str(enum php_http_method);
#ifdef __cplusplus
}
#endif
#endif
| 6,791 | 26.387097 | 90 |
h
|
php-src
|
php-src-master/sapi/cli/ps_title.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Keyur Govande <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PS_TITLE_HEADER
#define PS_TITLE_HEADER
#define PS_TITLE_SUCCESS 0
#define PS_TITLE_NOT_AVAILABLE 1
#define PS_TITLE_NOT_INITIALIZED 2
#define PS_TITLE_BUFFER_NOT_AVAILABLE 3
#define PS_TITLE_WINDOWS_ERROR 4
extern char** save_ps_args(int argc, char** argv);
extern int set_ps_title(const char* new_str);
extern int get_ps_title(size_t* displen, const char** string);
extern const char* ps_title_errno(int rc);
extern int is_ps_title_available(void);
extern void cleanup_ps_args(char **argv);
#endif // PS_TITLE_HEADER
| 1,531 | 38.282051 | 75 |
h
|
php-src
|
php-src-master/sapi/embed/php_embed.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Edin Kadribasic <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php_embed.h"
#include "ext/standard/php_standard.h"
#include "ext/standard/dl_arginfo.h"
#ifdef PHP_WIN32
#include <io.h>
#include <fcntl.h>
#endif
const char HARDCODED_INI[] =
"html_errors=0\n"
"register_argc_argv=1\n"
"implicit_flush=1\n"
"output_buffering=0\n"
"max_execution_time=0\n"
"max_input_time=-1\n\0";
#if defined(PHP_WIN32) && defined(ZTS)
ZEND_TSRMLS_CACHE_DEFINE()
#endif
static char* php_embed_read_cookies(void)
{
return NULL;
}
static int php_embed_deactivate(void)
{
fflush(stdout);
return SUCCESS;
}
/* Here we prefer to use write(), which is unbuffered, over fwrite(), which is
* buffered. Using an unbuffered write operation to stdout will ensure PHP's
* output buffering feature does not compete with a SAPI output buffer and
* therefore we avoid situations wherein flushing the output buffer results in
* nondeterministic behavior.
*/
static inline size_t php_embed_single_write(const char *str, size_t str_length)
{
#ifdef PHP_WRITE_STDOUT
zend_long ret;
ret = write(STDOUT_FILENO, str, str_length);
if (ret <= 0) return 0;
return ret;
#else
size_t ret;
ret = fwrite(str, 1, MIN(str_length, 16384), stdout);
return ret;
#endif
}
/* SAPIs only have unbuffered write operations. This is because PHP's output
* buffering feature will handle any buffering of the output and invoke the
* SAPI unbuffered write operation when it flushes the buffer.
*/
static size_t php_embed_ub_write(const char *str, size_t str_length)
{
const char *ptr = str;
size_t remaining = str_length;
size_t ret;
while (remaining > 0) {
ret = php_embed_single_write(ptr, remaining);
if (!ret) {
php_handle_aborted_connection();
}
ptr += ret;
remaining -= ret;
}
return str_length;
}
static void php_embed_flush(void *server_context)
{
if (fflush(stdout)==EOF) {
php_handle_aborted_connection();
}
}
static void php_embed_send_header(sapi_header_struct *sapi_header, void *server_context)
{
}
/* The SAPI error logger that is called when the 'error_log' INI setting is not
* set.
*
* https://www.php.net/manual/en/errorfunc.configuration.php#ini.error-log
*/
static void php_embed_log_message(const char *message, int syslog_type_int)
{
fprintf(stderr, "%s\n", message);
}
static void php_embed_register_variables(zval *track_vars_array)
{
php_import_environment_variables(track_vars_array);
}
/* Module initialization (MINIT) */
static int php_embed_startup(sapi_module_struct *sapi_module)
{
return php_module_startup(sapi_module, NULL);
}
EMBED_SAPI_API sapi_module_struct php_embed_module = {
"embed", /* name */
"PHP Embedded Library", /* pretty name */
php_embed_startup, /* startup */
php_module_shutdown_wrapper, /* shutdown */
NULL, /* activate */
php_embed_deactivate, /* deactivate */
php_embed_ub_write, /* unbuffered write */
php_embed_flush, /* flush */
NULL, /* get uid */
NULL, /* getenv */
php_error, /* error handler */
NULL, /* header handler */
NULL, /* send headers handler */
php_embed_send_header, /* send header handler */
NULL, /* read POST data */
php_embed_read_cookies, /* read Cookies */
php_embed_register_variables, /* register server variables */
php_embed_log_message, /* Log message */
NULL, /* Get request time */
NULL, /* Child terminate */
STANDARD_SAPI_MODULE_PROPERTIES
};
/* }}} */
static const zend_function_entry additional_functions[] = {
ZEND_FE(dl, arginfo_dl)
ZEND_FE_END
};
EMBED_SAPI_API int php_embed_init(int argc, char **argv)
{
#if defined(SIGPIPE) && defined(SIG_IGN)
signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
that sockets created via fsockopen()
don't kill PHP if the remote site
closes it. in apache|apxs mode apache
does that for us! [email protected]
20000419 */
#endif
#ifdef ZTS
php_tsrm_startup();
# ifdef PHP_WIN32
ZEND_TSRMLS_CACHE_UPDATE();
# endif
#endif
zend_signal_startup();
/* SAPI initialization (SINIT)
*
* Initialize the SAPI globals (memset to 0). After this point we can set
* SAPI globals via the SG() macro.
*
* Reentrancy startup.
*
* This also sets 'php_embed_module.ini_entries = NULL' so we cannot
* allocate the INI entries until after this call.
*/
sapi_startup(&php_embed_module);
#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
/* This hard-coded string of INI settings is parsed and read into PHP's
* configuration hash table at the very end of php_init_config(). This
* means these settings will overwrite any INI settings that were set from
* an INI file.
*
* To provide overwritable INI defaults, hook the ini_defaults function
* pointer that is part of the sapi_module_struct
* (php_embed_module.ini_defaults).
*
* void (*ini_defaults)(HashTable *configuration_hash);
*
* This callback is invoked as soon as the configuration hash table is
* allocated so any INI settings added via this callback will have the
* lowest precedence and will allow INI files to overwrite them.
*/
php_embed_module.ini_entries = HARDCODED_INI;
/* SAPI-provided functions. */
php_embed_module.additional_functions = additional_functions;
if (argv) {
php_embed_module.executable_location = argv[0];
}
/* Module initialization (MINIT) */
if (php_embed_module.startup(&php_embed_module) == FAILURE) {
return FAILURE;
}
/* Do not chdir to the script's directory. This is akin to calling the CGI
* SAPI with '-C'.
*/
SG(options) |= SAPI_OPTION_NO_CHDIR;
SG(request_info).argc=argc;
SG(request_info).argv=argv;
/* Request initialization (RINIT) */
if (php_request_startup() == FAILURE) {
php_module_shutdown();
return FAILURE;
}
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
php_register_variable("PHP_SELF", "-", NULL);
return SUCCESS;
}
EMBED_SAPI_API void php_embed_shutdown(void)
{
/* Request shutdown (RSHUTDOWN) */
php_request_shutdown((void *) 0);
/* Module shutdown (MSHUTDOWN) */
php_module_shutdown();
/* SAPI shutdown (SSHUTDOWN) */
sapi_shutdown();
#ifdef ZTS
tsrm_shutdown();
#endif
}
| 7,638 | 27.610487 | 88 |
c
|
php-src
|
php-src-master/sapi/embed/php_embed.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Edin Kadribasic <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef _PHP_EMBED_H_
#define _PHP_EMBED_H_
#include <main/php.h>
#include <main/SAPI.h>
#include <main/php_main.h>
#include <main/php_variables.h>
#include <main/php_ini.h>
#include <zend_ini.h>
#define PHP_EMBED_START_BLOCK(x,y) { \
php_embed_init(x, y); \
zend_first_try {
#define PHP_EMBED_END_BLOCK() \
} zend_catch { \
/* int exit_status = EG(exit_status); */ \
} zend_end_try(); \
php_embed_shutdown(); \
}
#ifndef PHP_WIN32
#define EMBED_SAPI_API SAPI_API
#else
#define EMBED_SAPI_API
#endif
#ifdef ZTS
ZEND_TSRMLS_CACHE_EXTERN()
#endif
BEGIN_EXTERN_C()
EMBED_SAPI_API int php_embed_init(int argc, char **argv);
EMBED_SAPI_API void php_embed_shutdown(void);
extern EMBED_SAPI_API sapi_module_struct php_embed_module;
END_EXTERN_C()
#endif /* _PHP_EMBED_H_ */
| 1,796 | 31.089286 | 75 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_atomic.h
|
/* (c) 2007,2008 Andrei Nigmatulin */
#ifndef FPM_ATOMIC_H
#define FPM_ATOMIC_H 1
#include <inttypes.h>
#include <sched.h>
#ifdef HAVE_BUILTIN_ATOMIC
/**
* all the cases below (as provided by upstream) define:
* word as atomic_int_t, and
* unsigned word as atomic_uint_t
* and only use volatile atomic_uint_t as atomic_t
*/
typedef volatile unsigned long atomic_t;
#define atomic_cmp_set(a,b,c) __sync_bool_compare_and_swap(a,b,c)
#elif ( __i386__ || __i386 )
typedef int32_t atomic_int_t;
typedef uint32_t atomic_uint_t;
typedef volatile atomic_uint_t atomic_t;
static inline atomic_int_t atomic_fetch_add(atomic_t *value, atomic_int_t add) /* {{{ */
{
__asm__ volatile ( "lock;" "xaddl %0, %1;" :
"+r" (add) : "m" (*value) : "memory");
return add;
}
/* }}} */
static inline atomic_uint_t atomic_cmp_set(atomic_t *lock, atomic_uint_t old, atomic_uint_t set) /* {{{ */
{
unsigned char res;
__asm__ volatile ( "lock;" "cmpxchgl %3, %1;" "sete %0;" :
"=a" (res) : "m" (*lock), "a" (old), "r" (set) : "memory");
return res;
}
/* }}} */
#elif ( __amd64__ || __amd64 || __x86_64__ )
typedef int64_t atomic_int_t;
typedef uint64_t atomic_uint_t;
typedef volatile atomic_uint_t atomic_t;
static inline atomic_int_t atomic_fetch_add(atomic_t *value, atomic_int_t add) /* {{{ */
{
__asm__ volatile ( "lock;" "xaddq %0, %1;" :
"+r" (add) : "m" (*value) : "memory");
return add;
}
/* }}} */
static inline atomic_uint_t atomic_cmp_set(atomic_t *lock, atomic_uint_t old, atomic_uint_t set) /* {{{ */
{
unsigned char res;
__asm__ volatile ( "lock;" "cmpxchgq %3, %1;" "sete %0;" :
"=a" (res) : "m" (*lock), "a" (old), "r" (set) : "memory");
return res;
}
/* }}} */
#if (__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2))
#elif ( __arm__ || __arm ) /* W-Mark Kubacki */
#if (__arch64__ || __arch64)
typedef int64_t atomic_int_t;
typedef uint64_t atomic_uint_t;
#else
typedef int32_t atomic_int_t;
typedef uint32_t atomic_uint_t;
#endif
#define atomic_cmp_set(a,b,c) __sync_bool_compare_and_swap(a,b,c)
#endif /* defined (__GNUC__) &&... */
#elif ( __sparc__ || __sparc ) /* Marcin Ochab */
#if (__sparcv9 || __sparcv9__)
#if (__arch64__ || __arch64)
typedef uint64_t atomic_uint_t;
typedef volatile atomic_uint_t atomic_t;
static inline atomic_uint_t atomic_cas_64(atomic_t *lock, atomic_uint_t old, atomic_uint_t new) /* {{{ */
{
__asm__ __volatile__("casx [%2], %3, %0 " : "=&r"(new) : "0"(new), "r"(lock), "r"(old): "memory");
return new;
}
/* }}} */
static inline atomic_uint_t atomic_cmp_set(atomic_t *lock, atomic_uint_t old, atomic_uint_t set) /* {{{ */
{
return (atomic_cas_64(lock, old, set)==old);
}
/* }}} */
#else
typedef uint32_t atomic_uint_t;
typedef volatile atomic_uint_t atomic_t;
static inline atomic_uint_t atomic_cas_32(atomic_t *lock, atomic_uint_t old, atomic_uint_t new) /* {{{ */
{
__asm__ __volatile__("cas [%2], %3, %0 " : "=&r"(new) : "0"(new), "r"(lock), "r"(old): "memory");
return new;
}
/* }}} */
static inline atomic_uint_t atomic_cmp_set(atomic_t *lock, atomic_uint_t old, atomic_uint_t set) /* {{{ */
{
return (atomic_cas_32(lock, old, set)==old);
}
/* }}} */
#endif
#else /* #if (__sparcv9 || __sparcv9__) */
#error Sparc v8 and predecessors are not and will not be supported (see bug report 53310)
#endif /* #if (__sparcv9 || __sparcv9__) */
#else
#error Unsupported processor. Please open a bug report (https://github.com/php/php-src/issues).
#endif
static inline int fpm_spinlock(atomic_t *lock, int try_once) /* {{{ */
{
if (try_once) {
return atomic_cmp_set(lock, 0, 1) ? 1 : 0;
}
for (;;) {
if (atomic_cmp_set(lock, 0, 1)) {
break;
}
sched_yield();
}
return 1;
}
/* }}} */
#define fpm_unlock(lock) lock = 0
#endif
| 3,966 | 23.487654 | 106 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_children.h
|
/* (c) 2007,2008 Andrei Nigmatulin */
#ifndef FPM_CHILDREN_H
#define FPM_CHILDREN_H 1
#include <sys/time.h>
#include <sys/types.h>
#include "fpm_worker_pool.h"
#include "fpm_events.h"
#include "zlog.h"
struct fpm_child_s;
int fpm_children_create_initial(struct fpm_worker_pool_s *wp);
int fpm_children_free(struct fpm_child_s *child);
void fpm_children_bury(void);
int fpm_children_init_main(void);
int fpm_children_make(struct fpm_worker_pool_s *wp, int in_event_loop, int nb_to_spawn, int is_debug);
struct fpm_child_s *fpm_child_find(pid_t pid);
struct fpm_child_s {
struct fpm_child_s *prev, *next;
struct timeval started;
struct fpm_worker_pool_s *wp;
struct fpm_event_s ev_stdout, ev_stderr, ev_free;
int shm_slot_i;
int fd_stdout, fd_stderr;
void (*tracer)(struct fpm_child_s *);
struct timeval slow_logged;
bool idle_kill;
bool postponed_free;
pid_t pid;
int scoreboard_i;
struct zlog_stream *log_stream;
};
#endif
| 944 | 23.230769 | 102 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_config.h
|
/* (c) 2007,2008 Andrei Nigmatulin */
#include <php_config.h>
/* Solaris does not have it */
#ifndef INADDR_NONE
# define INADDR_NONE (-1)
#endif
/* If we're not using GNU C, elide __attribute__ */
#ifndef __GNUC__
# define __attribute__(x) /*NOTHING*/
#endif
/* Missing timer* macros (for solaris) */
#ifndef timerisset
# define timerisset(tvp) ((tvp)->tv_sec || (tvp)->tv_usec)
#endif
#ifndef timerclear
# define timerclear(tvp) ((tvp)->tv_sec = (tvp)->tv_usec = 0)
#endif
#ifndef timersub
# define timersub(tvp, uvp, vvp) \
do { \
(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \
(vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \
if ((vvp)->tv_usec < 0) { \
(vvp)->tv_sec--; \
(vvp)->tv_usec += 1000000; \
} \
} while (0)
#endif
#ifndef timeradd
# define timeradd(a, b, result) \
do { \
(result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \
(result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \
if ((result)->tv_usec >= 1000000) \
{ \
++(result)->tv_sec; \
(result)->tv_usec -= 1000000; \
} \
} while (0)
#endif
#ifndef timercmp
/* does not work for >= and <= */
# define timercmp(a, b, CMP) \
(((a)->tv_sec == (b)->tv_sec) ? \
((a)->tv_usec CMP (b)->tv_usec) : \
((a)->tv_sec CMP (b)->tv_sec))
#endif
/* endof timer* macros */
#ifndef MIN
# define MIN(a,b) (((a)<(b))?(a):(b))
#endif
#ifndef MAX
# define MAX(a,b) (((a)>(b))?(a):(b))
#endif
#if defined(HAVE_PTRACE) || defined(PROC_MEM_FILE) || defined(HAVE_MACH_VM_READ)
# define HAVE_FPM_TRACE 1
#else
# define HAVE_FPM_TRACE 0
#endif
#if defined(HAVE_LQ_TCP_INFO) || defined(HAVE_LQ_TCP_CONNECTION_INFO) || defined(HAVE_LQ_SO_LISTENQ)
# define HAVE_FPM_LQ 1
#else
# define HAVE_FPM_LQ 0
#endif
| 2,134 | 26.371795 | 100 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_events.h
|
/* (c) 2007,2008 Andrei Nigmatulin */
#ifndef FPM_EVENTS_H
#define FPM_EVENTS_H 1
#define FPM_EV_TIMEOUT (1 << 0)
#define FPM_EV_READ (1 << 1)
#define FPM_EV_PERSIST (1 << 2)
#define FPM_EV_EDGE (1 << 3)
#define fpm_event_set_timer(ev, flags, cb, arg) fpm_event_set((ev), -1, (flags), (cb), (arg))
struct fpm_event_s {
int fd; /* not set with FPM_EV_TIMEOUT */
struct timeval timeout; /* next time to trigger */
struct timeval frequency;
void (*callback)(struct fpm_event_s *, short, void *);
void *arg;
int flags;
int index; /* index of the fd in the ufds array */
short which; /* type of event */
};
typedef struct fpm_event_queue_s {
struct fpm_event_queue_s *prev;
struct fpm_event_queue_s *next;
struct fpm_event_s *ev;
} fpm_event_queue;
struct fpm_event_module_s {
const char *name;
int support_edge_trigger;
int (*init)(int max_fd);
int (*clean)(void);
int (*wait)(struct fpm_event_queue_s *queue, unsigned long int timeout);
int (*add)(struct fpm_event_s *ev);
int (*remove)(struct fpm_event_s *ev);
};
void fpm_event_loop(int err);
void fpm_event_fire(struct fpm_event_s *ev);
int fpm_event_init_main(void);
int fpm_event_set(struct fpm_event_s *ev, int fd, int flags, void (*callback)(struct fpm_event_s *, short, void *), void *arg);
int fpm_event_add(struct fpm_event_s *ev, unsigned long int timeout);
int fpm_event_del(struct fpm_event_s *ev);
int fpm_event_pre_init(char *machanism);
const char *fpm_event_mechanism_name(void);
int fpm_event_support_edge_trigger(void);
#endif
| 1,578 | 29.960784 | 127 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_main_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: b4ac4c0f1d91c354293e21185a2e6d9f99cc9fcc */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_fastcgi_finish_request, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_apache_request_headers, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
#define arginfo_getallheaders arginfo_apache_request_headers
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_fpm_get_status, 0, 0, MAY_BE_ARRAY|MAY_BE_FALSE)
ZEND_END_ARG_INFO()
ZEND_FUNCTION(fastcgi_finish_request);
ZEND_FUNCTION(apache_request_headers);
ZEND_FUNCTION(fpm_get_status);
static const zend_function_entry ext_functions[] = {
ZEND_FE(fastcgi_finish_request, arginfo_fastcgi_finish_request)
ZEND_FE(apache_request_headers, arginfo_apache_request_headers)
ZEND_FALIAS(getallheaders, apache_request_headers, arginfo_getallheaders)
ZEND_FE(fpm_get_status, arginfo_fpm_get_status)
ZEND_FE_END
};
| 960 | 33.321429 | 96 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_php.h
|
/* (c) 2007,2008 Andrei Nigmatulin */
#ifndef FPM_PHP_H
#define FPM_PHP_H 1
#include <TSRM.h>
#include "php.h"
#include "build-defs.h" /* for PHP_ defines */
#include "fpm/fpm_conf.h"
#define FPM_PHP_INI_TO_EXPAND \
{ \
"error_log", \
"extension_dir", \
"sendmail_path", \
"session.cookie_path", \
"session_pgsql.sem_file_name", \
"soap.wsdl_cache_dir", \
"uploadprogress.file.filename_template", \
"xdebug.output_dir", \
"xdebug.profiler_output_dir", \
"xdebug.trace_output_dir", \
"xmms.path", \
"axis2.client_home", \
"blenc.key_file", \
"coin_acceptor.device", \
NULL \
}
struct fpm_worker_pool_s;
int fpm_php_init_child(struct fpm_worker_pool_s *wp);
char *fpm_php_script_filename(void);
char *fpm_php_request_uri(void);
char *fpm_php_request_method(void);
char *fpm_php_query_string(void);
char *fpm_php_auth_user(void);
size_t fpm_php_content_length(void);
void fpm_php_soft_quit(void);
int fpm_php_init_main(void);
int fpm_php_apply_defines_ex(struct key_value_s *kv, int mode);
int fpm_php_limit_extensions(char *path);
bool fpm_php_is_key_in_table(zend_string *table, const char *key, size_t key_len);
#endif
| 1,159 | 23.680851 | 82 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_process_ctl.h
|
/* (c) 2007,2008 Andrei Nigmatulin */
#ifndef FPM_PROCESS_CTL_H
#define FPM_PROCESS_CTL_H 1
#include "fpm_events.h"
/* 1s (in ms) heartbeat for idle server maintenance */
#define FPM_IDLE_SERVER_MAINTENANCE_HEARTBEAT (1000)
/* a minimum of 130ms heartbeat for pctl */
#define FPM_PCTL_MIN_HEARTBEAT (130)
struct fpm_child_s;
void fpm_pctl(int new_state, int action);
int fpm_pctl_can_spawn_children(void);
int fpm_pctl_kill(pid_t pid, int how);
void fpm_pctl_kill_all(int signo);
void fpm_pctl_heartbeat(struct fpm_event_s *ev, short which, void *arg);
void fpm_pctl_perform_idle_server_maintenance_heartbeat(struct fpm_event_s *ev, short which, void *arg);
void fpm_pctl_on_socket_accept(struct fpm_event_s *ev, short which, void *arg);
int fpm_pctl_child_exited(void);
int fpm_pctl_init_main(void);
enum {
FPM_PCTL_STATE_UNSPECIFIED,
FPM_PCTL_STATE_NORMAL,
FPM_PCTL_STATE_RELOADING,
FPM_PCTL_STATE_TERMINATING,
FPM_PCTL_STATE_FINISHING
};
enum {
FPM_PCTL_ACTION_SET,
FPM_PCTL_ACTION_TIMEOUT,
FPM_PCTL_ACTION_LAST_CHILD_EXITED
};
enum {
FPM_PCTL_TERM,
FPM_PCTL_STOP,
FPM_PCTL_CONT,
FPM_PCTL_QUIT,
FPM_PCTL_KILL
};
#endif
| 1,147 | 21.96 | 104 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_scoreboard.c
|
/* (c) 2009 Jerome Loyet */
#include "php.h"
#include "SAPI.h"
#include <stdio.h>
#include <time.h>
#include "fpm_config.h"
#include "fpm_children.h"
#include "fpm_scoreboard.h"
#include "fpm_shm.h"
#include "fpm_sockets.h"
#include "fpm_worker_pool.h"
#include "fpm_clock.h"
#include "zlog.h"
static struct fpm_scoreboard_s *fpm_scoreboard = NULL;
static int fpm_scoreboard_i = -1;
#ifdef HAVE_TIMES
static float fpm_scoreboard_tick;
#endif
int fpm_scoreboard_init_main(void)
{
struct fpm_worker_pool_s *wp;
#ifdef HAVE_TIMES
#if (defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK))
fpm_scoreboard_tick = sysconf(_SC_CLK_TCK);
#else /* _SC_CLK_TCK */
#ifdef HZ
fpm_scoreboard_tick = HZ;
#else /* HZ */
fpm_scoreboard_tick = 100;
#endif /* HZ */
#endif /* _SC_CLK_TCK */
zlog(ZLOG_DEBUG, "got clock tick '%.0f'", fpm_scoreboard_tick);
#endif /* HAVE_TIMES */
for (wp = fpm_worker_all_pools; wp; wp = wp->next) {
size_t scoreboard_procs_size;
void *shm_mem;
if (wp->config->pm_max_children < 1) {
zlog(ZLOG_ERROR, "[pool %s] Unable to create scoreboard SHM because max_client is not set", wp->config->name);
return -1;
}
if (wp->scoreboard) {
zlog(ZLOG_ERROR, "[pool %s] Unable to create scoreboard SHM because it already exists", wp->config->name);
return -1;
}
scoreboard_procs_size = sizeof(struct fpm_scoreboard_proc_s) * wp->config->pm_max_children;
shm_mem = fpm_shm_alloc(sizeof(struct fpm_scoreboard_s) + scoreboard_procs_size);
if (!shm_mem) {
return -1;
}
wp->scoreboard = shm_mem;
wp->scoreboard->pm = wp->config->pm;
wp->scoreboard->nprocs = wp->config->pm_max_children;
wp->scoreboard->start_epoch = time(NULL);
strlcpy(wp->scoreboard->pool, wp->config->name, sizeof(wp->scoreboard->pool));
if (wp->shared) {
/* shared pool is added after non shared ones so the shared scoreboard is allocated */
wp->scoreboard->shared = wp->shared->scoreboard;
}
}
return 0;
}
static struct fpm_scoreboard_s *fpm_scoreboard_get_for_update(struct fpm_scoreboard_s *scoreboard) /* {{{ */
{
if (!scoreboard) {
scoreboard = fpm_scoreboard;
}
if (!scoreboard) {
zlog(ZLOG_WARNING, "Unable to update scoreboard: the SHM has not been found");
}
return scoreboard;
}
/* }}} */
void fpm_scoreboard_update_begin(struct fpm_scoreboard_s *scoreboard) /* {{{ */
{
scoreboard = fpm_scoreboard_get_for_update(scoreboard);
if (!scoreboard) {
return;
}
fpm_spinlock(&scoreboard->lock, 0);
}
/* }}} */
void fpm_scoreboard_update_commit(
int idle, int active, int lq, int lq_len, int requests, int max_children_reached,
int slow_rq, int action, struct fpm_scoreboard_s *scoreboard) /* {{{ */
{
scoreboard = fpm_scoreboard_get_for_update(scoreboard);
if (!scoreboard) {
return;
}
if (action == FPM_SCOREBOARD_ACTION_SET) {
if (idle >= 0) {
scoreboard->idle = idle;
}
if (active >= 0) {
scoreboard->active = active;
}
if (lq >= 0) {
scoreboard->lq = lq;
}
if (lq_len >= 0) {
scoreboard->lq_len = lq_len;
}
#if HAVE_FPM_LQ /* prevent unnecessary test */
if (scoreboard->lq > scoreboard->lq_max) {
scoreboard->lq_max = scoreboard->lq;
}
#endif
if (requests >= 0) {
scoreboard->requests = requests;
}
if (max_children_reached >= 0) {
scoreboard->max_children_reached = max_children_reached;
}
if (slow_rq > 0) {
scoreboard->slow_rq = slow_rq;
}
} else {
if (scoreboard->idle + idle > 0) {
scoreboard->idle += idle;
} else {
scoreboard->idle = 0;
}
if (scoreboard->active + active > 0) {
scoreboard->active += active;
} else {
scoreboard->active = 0;
}
if (scoreboard->requests + requests > 0) {
scoreboard->requests += requests;
} else {
scoreboard->requests = 0;
}
if (scoreboard->max_children_reached + max_children_reached > 0) {
scoreboard->max_children_reached += max_children_reached;
} else {
scoreboard->max_children_reached = 0;
}
if (scoreboard->slow_rq + slow_rq > 0) {
scoreboard->slow_rq += slow_rq;
} else {
scoreboard->slow_rq = 0;
}
}
if (scoreboard->active > scoreboard->active_max) {
scoreboard->active_max = scoreboard->active;
}
fpm_unlock(scoreboard->lock);
}
/* }}} */
void fpm_scoreboard_update(
int idle, int active, int lq, int lq_len, int requests, int max_children_reached,
int slow_rq, int action, struct fpm_scoreboard_s *scoreboard) /* {{{ */
{
fpm_scoreboard_update_begin(scoreboard);
fpm_scoreboard_update_commit(
idle, active, lq, lq_len, requests, max_children_reached, slow_rq, action, scoreboard);
}
/* }}} */
struct fpm_scoreboard_s *fpm_scoreboard_get(void)
{
return fpm_scoreboard;
}
static inline struct fpm_scoreboard_proc_s *fpm_scoreboard_proc_get_ex(
struct fpm_scoreboard_s *scoreboard, int child_index, unsigned int nprocs) /* {{{*/
{
if (!scoreboard) {
return NULL;
}
if (child_index < 0 || (unsigned int)child_index >= nprocs) {
return NULL;
}
return &scoreboard->procs[child_index];
}
/* }}} */
struct fpm_scoreboard_proc_s *fpm_scoreboard_proc_get(
struct fpm_scoreboard_s *scoreboard, int child_index) /* {{{*/
{
if (!scoreboard) {
scoreboard = fpm_scoreboard;
}
if (child_index < 0) {
child_index = fpm_scoreboard_i;
}
return fpm_scoreboard_proc_get_ex(scoreboard, child_index, scoreboard->nprocs);
}
/* }}} */
struct fpm_scoreboard_proc_s *fpm_scoreboard_proc_get_from_child(struct fpm_child_s *child) /* {{{*/
{
struct fpm_worker_pool_s *wp = child->wp;
unsigned int nprocs = wp->config->pm_max_children;
struct fpm_scoreboard_s *scoreboard = wp->scoreboard;
int child_index = child->scoreboard_i;
return fpm_scoreboard_proc_get_ex(scoreboard, child_index, nprocs);
}
/* }}} */
struct fpm_scoreboard_s *fpm_scoreboard_acquire(struct fpm_scoreboard_s *scoreboard, int nohang) /* {{{ */
{
struct fpm_scoreboard_s *s;
s = scoreboard ? scoreboard : fpm_scoreboard;
if (!s) {
return NULL;
}
if (!fpm_spinlock(&s->lock, nohang)) {
return NULL;
}
return s;
}
/* }}} */
void fpm_scoreboard_release(struct fpm_scoreboard_s *scoreboard) {
if (!scoreboard) {
return;
}
scoreboard->lock = 0;
}
struct fpm_scoreboard_s *fpm_scoreboard_copy(struct fpm_scoreboard_s *scoreboard, int copy_procs)
{
struct fpm_scoreboard_s *scoreboard_copy;
struct fpm_scoreboard_proc_s *scoreboard_proc_p;
size_t scoreboard_size, scoreboard_nprocs_size;
int i;
void *mem;
if (!scoreboard) {
scoreboard = fpm_scoreboard_get();
}
if (copy_procs) {
scoreboard_size = sizeof(struct fpm_scoreboard_s);
scoreboard_nprocs_size = sizeof(struct fpm_scoreboard_proc_s) * scoreboard->nprocs;
mem = malloc(scoreboard_size + scoreboard_nprocs_size);
} else {
mem = malloc(sizeof(struct fpm_scoreboard_s));
}
if (!mem) {
zlog(ZLOG_ERROR, "scoreboard: failed to allocate memory for copy");
return NULL;
}
scoreboard_copy = mem;
scoreboard = fpm_scoreboard_acquire(scoreboard, FPM_SCOREBOARD_LOCK_NOHANG);
if (!scoreboard) {
free(mem);
zlog(ZLOG_ERROR, "scoreboard: failed to lock (already locked)");
return NULL;
}
*scoreboard_copy = *scoreboard;
if (copy_procs) {
mem += scoreboard_size;
for (i = 0; i < scoreboard->nprocs; i++, mem += sizeof(struct fpm_scoreboard_proc_s)) {
scoreboard_proc_p = fpm_scoreboard_proc_acquire(scoreboard, i, FPM_SCOREBOARD_LOCK_HANG);
scoreboard_copy->procs[i] = *scoreboard_proc_p;
fpm_scoreboard_proc_release(scoreboard_proc_p);
}
}
fpm_scoreboard_release(scoreboard);
return scoreboard_copy;
}
void fpm_scoreboard_free_copy(struct fpm_scoreboard_s *scoreboard)
{
free(scoreboard);
}
struct fpm_scoreboard_proc_s *fpm_scoreboard_proc_acquire(struct fpm_scoreboard_s *scoreboard, int child_index, int nohang) /* {{{ */
{
struct fpm_scoreboard_proc_s *proc;
proc = fpm_scoreboard_proc_get(scoreboard, child_index);
if (!proc) {
return NULL;
}
if (!fpm_spinlock(&proc->lock, nohang)) {
return NULL;
}
return proc;
}
/* }}} */
void fpm_scoreboard_proc_release(struct fpm_scoreboard_proc_s *proc) /* {{{ */
{
if (!proc) {
return;
}
proc->lock = 0;
}
void fpm_scoreboard_free(struct fpm_worker_pool_s *wp) /* {{{ */
{
size_t scoreboard_procs_size;
struct fpm_scoreboard_s *scoreboard = wp->scoreboard;
if (!scoreboard) {
zlog(ZLOG_ERROR, "**scoreboard is NULL");
return;
}
scoreboard_procs_size = sizeof(struct fpm_scoreboard_proc_s) * wp->config->pm_max_children;
fpm_shm_free(scoreboard, sizeof(struct fpm_scoreboard_s) + scoreboard_procs_size);
}
/* }}} */
void fpm_scoreboard_child_use(struct fpm_child_s *child, pid_t pid) /* {{{ */
{
struct fpm_scoreboard_proc_s *proc;
fpm_scoreboard = child->wp->scoreboard;
fpm_scoreboard_i = child->scoreboard_i;
proc = fpm_scoreboard_proc_get_from_child(child);
if (!proc) {
return;
}
proc->pid = pid;
proc->start_epoch = time(NULL);
}
/* }}} */
void fpm_scoreboard_proc_free(struct fpm_child_s *child) /* {{{ */
{
struct fpm_worker_pool_s *wp = child->wp;
struct fpm_scoreboard_s *scoreboard = wp->scoreboard;
int child_index = child->scoreboard_i;
if (!scoreboard) {
return;
}
if (child_index < 0 || child_index >= wp->config->pm_max_children) {
return;
}
if (scoreboard->procs[child_index].used > 0) {
memset(&scoreboard->procs[child_index], 0, sizeof(struct fpm_scoreboard_proc_s));
}
/* set this slot as free to avoid search on next alloc */
scoreboard->free_proc = child_index;
}
/* }}} */
int fpm_scoreboard_proc_alloc(struct fpm_child_s *child) /* {{{ */
{
int i = -1;
struct fpm_worker_pool_s *wp = child->wp;
struct fpm_scoreboard_s *scoreboard = wp->scoreboard;
int nprocs = wp->config->pm_max_children;
if (!scoreboard) {
return -1;
}
/* first try the slot which is supposed to be free */
if (scoreboard->free_proc >= 0 && scoreboard->free_proc < nprocs) {
if (!scoreboard->procs[scoreboard->free_proc].used) {
i = scoreboard->free_proc;
}
}
if (i < 0) { /* the supposed free slot is not, let's search for a free slot */
zlog(ZLOG_DEBUG, "[pool %s] the proc->free_slot was not free. Let's search", scoreboard->pool);
for (i = 0; i < nprocs; i++) {
if (!scoreboard->procs[i].used) { /* found */
break;
}
}
}
/* no free slot */
if (i < 0 || i >= nprocs) {
zlog(ZLOG_ERROR, "[pool %s] no free scoreboard slot", scoreboard->pool);
return -1;
}
scoreboard->procs[i].used = 1;
child->scoreboard_i = i;
/* supposed next slot is free */
if (i + 1 >= nprocs) {
scoreboard->free_proc = 0;
} else {
scoreboard->free_proc = i + 1;
}
return 0;
}
/* }}} */
#ifdef HAVE_TIMES
float fpm_scoreboard_get_tick(void)
{
return fpm_scoreboard_tick;
}
#endif
| 10,604 | 22.671875 | 133 |
c
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_signals.c
|
/* (c) 2007,2008 Andrei Nigmatulin */
#include "fpm_config.h"
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include "fpm.h"
#include "fpm_signals.h"
#include "fpm_sockets.h"
#include "fpm_php.h"
#include "zlog.h"
static int sp[2];
static sigset_t block_sigset;
static sigset_t child_block_sigset;
const char *fpm_signal_names[NSIG + 1] = {
#ifdef SIGHUP
[SIGHUP] = "SIGHUP",
#endif
#ifdef SIGINT
[SIGINT] = "SIGINT",
#endif
#ifdef SIGQUIT
[SIGQUIT] = "SIGQUIT",
#endif
#ifdef SIGILL
[SIGILL] = "SIGILL",
#endif
#ifdef SIGTRAP
[SIGTRAP] = "SIGTRAP",
#endif
#ifdef SIGABRT
[SIGABRT] = "SIGABRT",
#endif
#ifdef SIGEMT
[SIGEMT] = "SIGEMT",
#endif
#ifdef SIGBUS
[SIGBUS] = "SIGBUS",
#endif
#ifdef SIGFPE
[SIGFPE] = "SIGFPE",
#endif
#ifdef SIGKILL
[SIGKILL] = "SIGKILL",
#endif
#ifdef SIGUSR1
[SIGUSR1] = "SIGUSR1",
#endif
#ifdef SIGSEGV
[SIGSEGV] = "SIGSEGV",
#endif
#ifdef SIGUSR2
[SIGUSR2] = "SIGUSR2",
#endif
#ifdef SIGPIPE
[SIGPIPE] = "SIGPIPE",
#endif
#ifdef SIGALRM
[SIGALRM] = "SIGALRM",
#endif
#ifdef SIGTERM
[SIGTERM] = "SIGTERM",
#endif
#ifdef SIGCHLD
[SIGCHLD] = "SIGCHLD",
#endif
#ifdef SIGCONT
[SIGCONT] = "SIGCONT",
#endif
#ifdef SIGSTOP
[SIGSTOP] = "SIGSTOP",
#endif
#ifdef SIGTSTP
[SIGTSTP] = "SIGTSTP",
#endif
#ifdef SIGTTIN
[SIGTTIN] = "SIGTTIN",
#endif
#ifdef SIGTTOU
[SIGTTOU] = "SIGTTOU",
#endif
#ifdef SIGURG
[SIGURG] = "SIGURG",
#endif
#ifdef SIGXCPU
[SIGXCPU] = "SIGXCPU",
#endif
#ifdef SIGXFSZ
[SIGXFSZ] = "SIGXFSZ",
#endif
#ifdef SIGVTALRM
[SIGVTALRM] = "SIGVTALRM",
#endif
#ifdef SIGPROF
[SIGPROF] = "SIGPROF",
#endif
#ifdef SIGWINCH
[SIGWINCH] = "SIGWINCH",
#endif
#ifdef SIGINFO
[SIGINFO] = "SIGINFO",
#endif
#ifdef SIGIO
[SIGIO] = "SIGIO",
#endif
#ifdef SIGPWR
[SIGPWR] = "SIGPWR",
#endif
#ifdef SIGSYS
[SIGSYS] = "SIGSYS",
#endif
#ifdef SIGWAITING
[SIGWAITING] = "SIGWAITING",
#endif
#ifdef SIGLWP
[SIGLWP] = "SIGLWP",
#endif
#ifdef SIGFREEZE
[SIGFREEZE] = "SIGFREEZE",
#endif
#ifdef SIGTHAW
[SIGTHAW] = "SIGTHAW",
#endif
#ifdef SIGCANCEL
[SIGCANCEL] = "SIGCANCEL",
#endif
#ifdef SIGLOST
[SIGLOST] = "SIGLOST",
#endif
};
static void sig_soft_quit(int signo) /* {{{ */
{
int saved_errno = errno;
/* closing fastcgi listening socket will force fcgi_accept() exit immediately */
close(fpm_globals.listening_socket);
if (0 > socket(AF_UNIX, SOCK_STREAM, 0)) {
zlog(ZLOG_WARNING, "failed to create a new socket");
}
fpm_php_soft_quit();
errno = saved_errno;
}
/* }}} */
static void sig_handler(int signo) /* {{{ */
{
static const char sig_chars[NSIG + 1] = {
[SIGTERM] = 'T',
[SIGINT] = 'I',
[SIGUSR1] = '1',
[SIGUSR2] = '2',
[SIGQUIT] = 'Q',
[SIGCHLD] = 'C'
};
char s;
int saved_errno;
if (fpm_globals.parent_pid != getpid()) {
/* Avoid using of signal handlers from the master process in a worker
before the child sets up its own signal handlers.
Normally it is prevented by the sigprocmask() calls
around fork(). This execution branch is a last resort trap
that has no protection against #76601. */
return;
}
saved_errno = errno;
s = sig_chars[signo];
zend_quiet_write(sp[1], &s, sizeof(s));
errno = saved_errno;
}
/* }}} */
int fpm_signals_init_main(void)
{
struct sigaction act;
if (0 > socketpair(AF_UNIX, SOCK_STREAM, 0, sp)) {
zlog(ZLOG_SYSERROR, "failed to init signals: socketpair()");
return -1;
}
if (0 > fd_set_blocked(sp[0], 0) || 0 > fd_set_blocked(sp[1], 0)) {
zlog(ZLOG_SYSERROR, "failed to init signals: fd_set_blocked()");
return -1;
}
if (0 > fcntl(sp[0], F_SETFD, FD_CLOEXEC) || 0 > fcntl(sp[1], F_SETFD, FD_CLOEXEC)) {
zlog(ZLOG_SYSERROR, "failed to init signals: fcntl(F_SETFD, FD_CLOEXEC)");
return -1;
}
memset(&act, 0, sizeof(act));
act.sa_handler = sig_handler;
sigfillset(&act.sa_mask);
if (0 > sigaction(SIGTERM, &act, 0) ||
0 > sigaction(SIGINT, &act, 0) ||
0 > sigaction(SIGUSR1, &act, 0) ||
0 > sigaction(SIGUSR2, &act, 0) ||
0 > sigaction(SIGCHLD, &act, 0) ||
0 > sigaction(SIGQUIT, &act, 0)) {
zlog(ZLOG_SYSERROR, "failed to init signals: sigaction()");
return -1;
}
zlog(ZLOG_DEBUG, "Unblocking all signals");
if (0 > fpm_signals_unblock()) {
return -1;
}
return 0;
}
int fpm_signals_init_child(void)
{
struct sigaction act, act_dfl;
memset(&act, 0, sizeof(act));
memset(&act_dfl, 0, sizeof(act_dfl));
act.sa_handler = &sig_soft_quit;
act.sa_flags |= SA_RESTART;
act_dfl.sa_handler = SIG_DFL;
close(sp[0]);
close(sp[1]);
if (0 > sigaction(SIGTERM, &act_dfl, 0) ||
0 > sigaction(SIGINT, &act_dfl, 0) ||
0 > sigaction(SIGUSR1, &act_dfl, 0) ||
0 > sigaction(SIGUSR2, &act_dfl, 0) ||
0 > sigaction(SIGCHLD, &act_dfl, 0) ||
0 > sigaction(SIGQUIT, &act, 0)) {
zlog(ZLOG_SYSERROR, "failed to init child signals: sigaction()");
return -1;
}
zend_signal_init();
if (0 > fpm_signals_unblock()) {
return -1;
}
return 0;
}
int fpm_signals_get_fd(void)
{
return sp[0];
}
int fpm_signals_init_mask(void)
{
/* Subset of signals from fpm_signals_init_main() and fpm_got_signal()
blocked to avoid unexpected death during early init
or during reload just after execvp() or fork */
static const int init_signal_array[] = { SIGUSR1, SIGUSR2, SIGCHLD };
size_t size = sizeof(init_signal_array)/sizeof(init_signal_array[0]);
size_t i = 0;
if (0 > sigemptyset(&block_sigset) ||
0 > sigemptyset(&child_block_sigset)) {
zlog(ZLOG_SYSERROR, "failed to prepare signal block mask: sigemptyset()");
return -1;
}
for (i = 0; i < size; ++i) {
int sig_i = init_signal_array[i];
if (0 > sigaddset(&block_sigset, sig_i) ||
0 > sigaddset(&child_block_sigset, sig_i)) {
if (sig_i <= NSIG && fpm_signal_names[sig_i] != NULL) {
zlog(ZLOG_SYSERROR, "failed to prepare signal block mask: sigaddset(%s)",
fpm_signal_names[sig_i]);
} else {
zlog(ZLOG_SYSERROR, "failed to prepare signal block mask: sigaddset(%d)", sig_i);
}
return -1;
}
}
if (0 > sigaddset(&child_block_sigset, SIGTERM) ||
0 > sigaddset(&child_block_sigset, SIGQUIT)) {
zlog(ZLOG_SYSERROR, "failed to prepare child signal block mask: sigaddset()");
return -1;
}
return 0;
}
int fpm_signals_block(void)
{
if (0 > sigprocmask(SIG_BLOCK, &block_sigset, NULL)) {
zlog(ZLOG_SYSERROR, "failed to block signals");
return -1;
}
return 0;
}
int fpm_signals_child_block(void)
{
if (0 > sigprocmask(SIG_BLOCK, &child_block_sigset, NULL)) {
zlog(ZLOG_SYSERROR, "failed to block child signals");
return -1;
}
return 0;
}
int fpm_signals_unblock(void)
{
/* Ensure that during reload after upgrade all signals are unblocked.
block_sigset could have different value before execve() */
sigset_t all_signals;
sigfillset(&all_signals);
if (0 > sigprocmask(SIG_UNBLOCK, &all_signals, NULL)) {
zlog(ZLOG_SYSERROR, "failed to unblock signals");
return -1;
}
return 0;
}
| 7,086 | 20.541033 | 86 |
c
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_sockets.c
|
/* (c) 2007,2008 Andrei Nigmatulin */
#include "fpm_config.h"
#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#endif
#include <sys/types.h>
#include <sys/stat.h> /* for chmod(2) */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include "zlog.h"
#include "fpm_arrays.h"
#include "fpm_sockets.h"
#include "fpm_worker_pool.h"
#include "fpm_unix.h"
#include "fpm_str.h"
#include "fpm_env.h"
#include "fpm_cleanup.h"
#include "fpm_scoreboard.h"
struct listening_socket_s {
int refcount;
int sock;
int type;
char *key;
};
static struct fpm_array_s sockets_list;
enum { FPM_GET_USE_SOCKET = 1, FPM_STORE_SOCKET = 2, FPM_STORE_USE_SOCKET = 3 };
#ifdef SO_SETFIB
static int routemax = -1;
#endif
static inline void fpm_sockets_get_env_name(char *envname, unsigned idx) /* {{{ */
{
if (!idx) {
strcpy(envname, "FPM_SOCKETS");
} else {
sprintf(envname, "FPM_SOCKETS_%d", idx);
}
}
/* }}} */
static void fpm_sockets_cleanup(int which, void *arg) /* {{{ */
{
unsigned i;
unsigned socket_set_count = 0;
unsigned socket_set[FPM_ENV_SOCKET_SET_MAX];
unsigned socket_set_buf = 0;
char envname[32];
char *env_value = 0;
int p = 0;
struct listening_socket_s *ls = sockets_list.data;
for (i = 0; i < sockets_list.used; i++, ls++) {
if (which != FPM_CLEANUP_PARENT_EXEC) {
close(ls->sock);
} else { /* on PARENT EXEC we want socket fds to be inherited through environment variable */
char fd[32];
char *tmpenv_value;
sprintf(fd, "%d", ls->sock);
socket_set_buf = (i % FPM_ENV_SOCKET_SET_SIZE == 0 && i) ? 1 : 0;
tmpenv_value = realloc(env_value, p + (p ? 1 : 0) + strlen(ls->key) + 1 + strlen(fd) + socket_set_buf + 1);
if (!tmpenv_value) {
zlog(ZLOG_SYSERROR, "failure to inherit data on parent exec for socket `%s` due to memory allocation failure", ls->key);
free(ls->key);
break;
}
env_value = tmpenv_value;
if (i % FPM_ENV_SOCKET_SET_SIZE == 0) {
socket_set[socket_set_count] = p + socket_set_buf;
socket_set_count++;
if (i) {
*(env_value + p + 1) = 0;
}
}
p += sprintf(env_value + p + socket_set_buf, "%s%s=%s", (p && !socket_set_buf) ? "," : "", ls->key, fd);
p += socket_set_buf;
}
if (which == FPM_CLEANUP_PARENT_EXIT_MAIN) {
if (ls->type == FPM_AF_UNIX) {
unlink(ls->key);
}
}
free(ls->key);
}
if (env_value) {
for (i = 0; i < socket_set_count; i++) {
fpm_sockets_get_env_name(envname, i);
setenv(envname, env_value + socket_set[i], 1);
}
fpm_sockets_get_env_name(envname, socket_set_count);
unsetenv(envname);
free(env_value);
}
fpm_array_free(&sockets_list);
}
/* }}} */
static void *fpm_get_in_addr(struct sockaddr *sa) /* {{{ */
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
/* }}} */
static int fpm_get_in_port(struct sockaddr *sa) /* {{{ */
{
if (sa->sa_family == AF_INET) {
return ntohs(((struct sockaddr_in*)sa)->sin_port);
}
return ntohs(((struct sockaddr_in6*)sa)->sin6_port);
}
/* }}} */
static int fpm_sockets_hash_op(int sock, struct sockaddr *sa, char *key, int type, int op) /* {{{ */
{
if (key == NULL) {
switch (type) {
case FPM_AF_INET : {
key = alloca(INET6_ADDRSTRLEN+10);
inet_ntop(sa->sa_family, fpm_get_in_addr(sa), key, INET6_ADDRSTRLEN);
sprintf(key+strlen(key), ":%d", fpm_get_in_port(sa));
break;
}
case FPM_AF_UNIX : {
struct sockaddr_un *sa_un = (struct sockaddr_un *) sa;
key = alloca(strlen(sa_un->sun_path) + 1);
strcpy(key, sa_un->sun_path);
break;
}
default :
return -1;
}
}
switch (op) {
case FPM_GET_USE_SOCKET :
{
unsigned i;
struct listening_socket_s *ls = sockets_list.data;
for (i = 0; i < sockets_list.used; i++, ls++) {
if (!strcmp(ls->key, key)) {
++ls->refcount;
return ls->sock;
}
}
break;
}
case FPM_STORE_SOCKET : /* inherited socket */
case FPM_STORE_USE_SOCKET : /* just created */
{
struct listening_socket_s *ls;
ls = fpm_array_push(&sockets_list);
if (!ls) {
break;
}
if (op == FPM_STORE_SOCKET) {
ls->refcount = 0;
} else {
ls->refcount = 1;
}
ls->type = type;
ls->sock = sock;
ls->key = strdup(key);
return 0;
}
}
return -1;
}
/* }}} */
static int fpm_sockets_new_listening_socket(struct fpm_worker_pool_s *wp, struct sockaddr *sa, int socklen) /* {{{ */
{
int flags = 1;
int sock;
mode_t saved_umask = 0;
sock = socket(sa->sa_family, SOCK_STREAM, 0);
if (0 > sock) {
zlog(ZLOG_SYSERROR, "failed to create new listening socket: socket()");
return -1;
}
if (0 > setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &flags, sizeof(flags))) {
zlog(ZLOG_WARNING, "failed to change socket attribute");
}
if (wp->listen_address_domain == FPM_AF_UNIX) {
if (fpm_socket_unix_test_connect((struct sockaddr_un *)sa, socklen) == 0) {
zlog(ZLOG_ERROR, "Another FPM instance seems to already listen on %s", ((struct sockaddr_un *) sa)->sun_path);
close(sock);
return -1;
}
unlink( ((struct sockaddr_un *) sa)->sun_path);
saved_umask = umask(0777 ^ wp->socket_mode);
}
if (0 > bind(sock, sa, socklen)) {
zlog(ZLOG_SYSERROR, "unable to bind listening socket for address '%s'", wp->config->listen_address);
if (wp->listen_address_domain == FPM_AF_UNIX) {
umask(saved_umask);
}
close(sock);
return -1;
}
if (wp->listen_address_domain == FPM_AF_UNIX) {
char *path = ((struct sockaddr_un *) sa)->sun_path;
umask(saved_umask);
if (0 > fpm_unix_set_socket_permissions(wp, path)) {
close(sock);
return -1;
}
}
if (0 > listen(sock, wp->config->listen_backlog)) {
zlog(ZLOG_SYSERROR, "failed to listen to address '%s'", wp->config->listen_address);
close(sock);
return -1;
}
#ifdef SO_SETFIB
if (-1 < wp->config->listen_setfib) {
if (routemax < wp->config->listen_setfib) {
zlog(ZLOG_ERROR, "Invalid routing table id %d, max is %d", wp->config->listen_setfib, routemax);
close(sock);
return -1;
}
if (0 > setsockopt(sock, SOL_SOCKET, SO_SETFIB, &wp->config->listen_setfib, sizeof(wp->config->listen_setfib))) {
zlog(ZLOG_WARNING, "failed to change socket SO_SETFIB attribute");
}
}
#endif
return sock;
}
/* }}} */
static int fpm_sockets_get_listening_socket(struct fpm_worker_pool_s *wp, struct sockaddr *sa, int socklen) /* {{{ */
{
int sock;
sock = fpm_sockets_hash_op(0, sa, 0, wp->listen_address_domain, FPM_GET_USE_SOCKET);
if (sock >= 0) {
return sock;
}
sock = fpm_sockets_new_listening_socket(wp, sa, socklen);
fpm_sockets_hash_op(sock, sa, 0, wp->listen_address_domain, FPM_STORE_USE_SOCKET);
return sock;
}
/* }}} */
enum fpm_address_domain fpm_sockets_domain_from_address(char *address) /* {{{ */
{
if (strchr(address, ':')) {
return FPM_AF_INET;
}
if (strlen(address) == strspn(address, "0123456789")) {
return FPM_AF_INET;
}
return FPM_AF_UNIX;
}
/* }}} */
static int fpm_socket_af_inet_socket_by_addr(struct fpm_worker_pool_s *wp, const char *addr, const char *port) /* {{{ */
{
struct addrinfo hints, *servinfo, *p;
char tmpbuf[INET6_ADDRSTRLEN];
int status;
int sock = -1;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((status = getaddrinfo(addr, port, &hints, &servinfo)) != 0) {
zlog(ZLOG_ERROR, "getaddrinfo: %s", gai_strerror(status));
return -1;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
inet_ntop(p->ai_family, fpm_get_in_addr(p->ai_addr), tmpbuf, INET6_ADDRSTRLEN);
if (sock < 0) {
if ((sock = fpm_sockets_get_listening_socket(wp, p->ai_addr, p->ai_addrlen)) != -1) {
zlog(ZLOG_DEBUG, "Found address for %s, socket opened on %s", addr, tmpbuf);
}
} else {
zlog(ZLOG_WARNING, "Found multiple addresses for %s, %s ignored", addr, tmpbuf);
}
}
freeaddrinfo(servinfo);
return sock;
}
/* }}} */
static int fpm_socket_af_inet_listening_socket(struct fpm_worker_pool_s *wp) /* {{{ */
{
char *dup_address = strdup(wp->config->listen_address);
char *port_str = strrchr(dup_address, ':');
char *addr = NULL;
int addr_len;
int port = 0;
int sock = -1;
if (port_str) { /* this is host:port pair */
*port_str++ = '\0';
port = atoi(port_str);
addr = dup_address;
/* strip brackets from address for getaddrinfo */
addr_len = strlen(addr);
if (addr[0] == '[' && addr[addr_len - 1] == ']') {
addr[addr_len - 1] = '\0';
addr++;
}
} else if (strlen(dup_address) == strspn(dup_address, "0123456789")) { /* this is port */
port = atoi(dup_address);
port_str = dup_address;
}
if (port < 1 || port > 65535) {
zlog(ZLOG_ERROR, "invalid port value '%s'", port_str);
free(dup_address);
return -1;
}
if (addr) {
/* Bind a specific address */
sock = fpm_socket_af_inet_socket_by_addr(wp, addr, port_str);
} else {
/* Bind ANYADDR
*
* Try "::" first as that covers IPv6 ANYADDR and mapped IPv4 ANYADDR
* silencing warnings since failure is an option
*
* If that fails (because AF_INET6 is unsupported) retry with 0.0.0.0
*/
int old_level = zlog_set_level(ZLOG_ALERT);
sock = fpm_socket_af_inet_socket_by_addr(wp, "::", port_str);
zlog_set_level(old_level);
if (sock < 0) {
zlog(ZLOG_NOTICE, "Failed implicitly binding to ::, retrying with 0.0.0.0");
sock = fpm_socket_af_inet_socket_by_addr(wp, "0.0.0.0", port_str);
}
}
free(dup_address);
return sock;
}
/* }}} */
static int fpm_socket_af_unix_listening_socket(struct fpm_worker_pool_s *wp) /* {{{ */
{
struct sockaddr_un sa_un;
size_t socket_length = sizeof(sa_un.sun_path);
size_t address_length = strlen(wp->config->listen_address);
memset(&sa_un, 0, sizeof(sa_un));
strlcpy(sa_un.sun_path, wp->config->listen_address, socket_length);
if (address_length >= socket_length) {
zlog(
ZLOG_WARNING,
"[pool %s] cannot bind to UNIX socket '%s' as path is too long (found length: %zu, "
"maximal length: %zu), trying cut socket path instead '%s'",
wp->config->name,
wp->config->listen_address,
address_length,
socket_length,
sa_un.sun_path
);
}
sa_un.sun_family = AF_UNIX;
return fpm_sockets_get_listening_socket(wp, (struct sockaddr *) &sa_un, sizeof(struct sockaddr_un));
}
/* }}} */
#ifdef SO_SETFIB
static zend_result fpm_socket_setfib_init(void)
{
/* potentially up to 65536 but needs to check the actual cap beforehand */
size_t len = sizeof(routemax);
if (sysctlbyname("net.fibs", &routemax, &len, NULL, 0) < 0) {
zlog(ZLOG_ERROR, "failed to get max routing table");
return FAILURE;
}
return SUCCESS;
}
#endif
int fpm_sockets_init_main(void)
{
unsigned i, lq_len;
struct fpm_worker_pool_s *wp;
char envname[32];
char sockpath[256];
char *inherited;
struct listening_socket_s *ls;
if (0 == fpm_array_init(&sockets_list, sizeof(struct listening_socket_s), 10)) {
return -1;
}
#ifdef SO_SETFIB
if (fpm_socket_setfib_init() == FAILURE) {
return -1;
}
#endif
/* import inherited sockets */
for (i = 0; i < FPM_ENV_SOCKET_SET_MAX; i++) {
fpm_sockets_get_env_name(envname, i);
inherited = getenv(envname);
if (!inherited) {
break;
}
while (inherited && *inherited) {
char *comma = strchr(inherited, ',');
int type, fd_no;
char *eq;
if (comma) {
*comma = '\0';
}
eq = strchr(inherited, '=');
if (eq) {
int sockpath_len = eq - inherited;
if (sockpath_len > 255) {
/* this should never happen as UDS limit is lower */
sockpath_len = 255;
}
memcpy(sockpath, inherited, sockpath_len);
sockpath[sockpath_len] = '\0';
fd_no = atoi(eq + 1);
type = fpm_sockets_domain_from_address(sockpath);
zlog(ZLOG_NOTICE, "using inherited socket fd=%d, \"%s\"", fd_no, sockpath);
fpm_sockets_hash_op(fd_no, 0, sockpath, type, FPM_STORE_SOCKET);
}
if (comma) {
inherited = comma + 1;
} else {
inherited = 0;
}
}
}
/* create all required sockets */
for (wp = fpm_worker_all_pools; wp; wp = wp->next) {
switch (wp->listen_address_domain) {
case FPM_AF_INET :
wp->listening_socket = fpm_socket_af_inet_listening_socket(wp);
break;
case FPM_AF_UNIX :
if (0 > fpm_unix_resolve_socket_permissions(wp)) {
return -1;
}
wp->listening_socket = fpm_socket_af_unix_listening_socket(wp);
break;
}
if (wp->listening_socket == -1) {
return -1;
}
if (wp->listen_address_domain == FPM_AF_INET && fpm_socket_get_listening_queue(wp->listening_socket, NULL, &lq_len) >= 0) {
fpm_scoreboard_update(-1, -1, -1, (int)lq_len, -1, -1, 0, FPM_SCOREBOARD_ACTION_SET, wp->scoreboard);
}
}
/* close unused sockets that was inherited */
ls = sockets_list.data;
for (i = 0; i < sockets_list.used; ) {
if (ls->refcount == 0) {
close(ls->sock);
if (ls->type == FPM_AF_UNIX) {
unlink(ls->key);
}
free(ls->key);
fpm_array_item_remove(&sockets_list, i);
} else {
++i;
++ls;
}
}
if (0 > fpm_cleanup_add(FPM_CLEANUP_ALL, fpm_sockets_cleanup, 0)) {
return -1;
}
return 0;
}
#if HAVE_FPM_LQ
#ifdef HAVE_LQ_TCP_INFO
#include <netinet/tcp.h>
int fpm_socket_get_listening_queue(int sock, unsigned *cur_lq, unsigned *max_lq)
{
struct tcp_info info;
socklen_t len = sizeof(info);
if (0 > getsockopt(sock, IPPROTO_TCP, TCP_INFO, &info, &len)) {
zlog(ZLOG_SYSERROR, "failed to retrieve TCP_INFO for socket");
return -1;
}
#if defined(__FreeBSD__) || defined(__NetBSD__)
if (info.__tcpi_sacked == 0) {
return -1;
}
if (cur_lq) {
*cur_lq = info.__tcpi_unacked;
}
if (max_lq) {
*max_lq = info.__tcpi_sacked;
}
#else
/* kernel >= 2.6.24 return non-zero here, that means operation is supported */
if (info.tcpi_sacked == 0) {
return -1;
}
if (cur_lq) {
*cur_lq = info.tcpi_unacked;
}
if (max_lq) {
*max_lq = info.tcpi_sacked;
}
#endif
return 0;
}
#elif defined(HAVE_LQ_TCP_CONNECTION_INFO)
#include <netinet/tcp.h>
int fpm_socket_get_listening_queue(int sock, unsigned *cur_lq, unsigned *max_lq)
{
struct tcp_connection_info info;
socklen_t len = sizeof(info);
if (0 > getsockopt(sock, IPPROTO_TCP, TCP_CONNECTION_INFO, &info, &len)) {
zlog(ZLOG_SYSERROR, "failed to retrieve TCP_CONNECTION_INFO for socket");
return -1;
}
if (cur_lq) {
*cur_lq = info.tcpi_tfo_syn_data_acked;
}
if (max_lq) {
*max_lq = 0;
}
return 0;
}
#endif
#ifdef HAVE_LQ_SO_LISTENQ
int fpm_socket_get_listening_queue(int sock, unsigned *cur_lq, unsigned *max_lq)
{
int val;
socklen_t len = sizeof(val);
if (cur_lq) {
if (0 > getsockopt(sock, SOL_SOCKET, SO_LISTENQLEN, &val, &len)) {
return -1;
}
*cur_lq = val;
}
if (max_lq) {
if (0 > getsockopt(sock, SOL_SOCKET, SO_LISTENQLIMIT, &val, &len)) {
return -1;
}
*max_lq = val;
}
return 0;
}
#endif
#else
int fpm_socket_get_listening_queue(int sock, unsigned *cur_lq, unsigned *max_lq)
{
return -1;
}
#endif
int fpm_socket_unix_test_connect(struct sockaddr_un *sock, size_t socklen) /* {{{ */
{
int fd;
if (!sock || sock->sun_family != AF_UNIX) {
return -1;
}
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
return -1;
}
if (connect(fd, (struct sockaddr *)sock, socklen) == -1) {
close(fd);
return -1;
}
close(fd);
return 0;
}
/* }}} */
| 15,402 | 21.921131 | 124 |
c
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_sockets.h
|
/* (c) 2007,2008 Andrei Nigmatulin */
#ifndef FPM_MISC_H
#define FPM_MISC_H 1
#include <sys/types.h>
#include <sys/socket.h>
#if defined(__FreeBSD__)
#include <sys/sysctl.h>
#endif
#include <sys/un.h>
#include <unistd.h>
#include <fcntl.h>
#include "fpm_worker_pool.h"
/*
On Linux, FreeBSD, OpenBSD and macOS, backlog negative values are truncated to SOMAXCONN
*/
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__linux__) || defined(__APPLE__)
#define FPM_BACKLOG_DEFAULT -1
#else
#define FPM_BACKLOG_DEFAULT 511
#endif
#define FPM_ENV_SOCKET_SET_MAX 256
#define FPM_ENV_SOCKET_SET_SIZE 128
enum fpm_address_domain fpm_sockets_domain_from_address(char *addr);
int fpm_sockets_init_main(void);
int fpm_socket_get_listening_queue(int sock, unsigned *cur_lq, unsigned *max_lq);
int fpm_socket_unix_test_connect(struct sockaddr_un *sock, size_t socklen);
static inline int fd_set_blocked(int fd, int blocked) /* {{{ */
{
int flags = fcntl(fd, F_GETFL);
if (flags < 0) {
return -1;
}
if (blocked) {
flags &= ~O_NONBLOCK;
} else {
flags |= O_NONBLOCK;
}
return fcntl(fd, F_SETFL, flags);
}
/* }}} */
#endif
| 1,141 | 20.54717 | 92 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_stdio.c
|
/* (c) 2007,2008 Andrei Nigmatulin */
#include "fpm_config.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include "php_syslog.h"
#include "php_network.h"
#include "fpm.h"
#include "fpm_children.h"
#include "fpm_cleanup.h"
#include "fpm_events.h"
#include "fpm_sockets.h"
#include "fpm_stdio.h"
#include "zlog.h"
static int fd_stderr_original = -1;
static int fd_stdout[2];
static int fd_stderr[2];
int fpm_stdio_init_main(void)
{
int fd = open("/dev/null", O_RDWR);
if (0 > fd) {
zlog(ZLOG_SYSERROR, "failed to init stdio: open(\"/dev/null\")");
return -1;
}
if (0 > dup2(fd, STDIN_FILENO) || 0 > dup2(fd, STDOUT_FILENO)) {
zlog(ZLOG_SYSERROR, "failed to init stdio: dup2()");
close(fd);
return -1;
}
close(fd);
return 0;
}
static inline int fpm_use_error_log(void) {
/*
* the error_log is NOT used when running in foreground
* and from a tty (user looking at output).
* So, error_log is used by
* - SysV init launch php-fpm as a daemon
* - Systemd launch php-fpm in foreground
*/
#ifdef HAVE_UNISTD_H
if (fpm_global_config.daemonize || (!isatty(STDERR_FILENO) && !fpm_globals.force_stderr)) {
#else
if (fpm_global_config.daemonize) {
#endif
return 1;
}
return 0;
}
int fpm_stdio_init_final(void)
{
if (0 > fpm_stdio_redirect_stderr_to_error_log() ||
0 > fpm_stdio_redirect_stderr_to_dev_null_for_syslog()) {
return -1;
}
zlog_set_launched();
return 0;
}
/* }}} */
int fpm_stdio_save_original_stderr(void)
{
/* STDERR fd gets lost after calling fpm_stdio_init_final() (check GH-8555) so it can be saved.
* It should be used only when PHP-FPM is not daemonized otherwise it might break some
* applications (e.g. GH-9754). */
zlog(ZLOG_DEBUG, "saving original STDERR fd: dup()");
fd_stderr_original = dup(STDERR_FILENO);
if (0 > fd_stderr_original) {
zlog(ZLOG_SYSERROR, "failed to save original STDERR fd, access.log records may appear in error_log: dup()");
return -1;
}
return 0;
}
int fpm_stdio_restore_original_stderr(int close_after_restore)
{
/* Restore original STDERR fd if it was previously saved. */
if (-1 != fd_stderr_original) {
zlog(ZLOG_DEBUG, "restoring original STDERR fd: dup2()");
if (0 > dup2(fd_stderr_original, STDERR_FILENO)) {
zlog(ZLOG_SYSERROR, "failed to restore original STDERR fd, access.log records may appear in error_log: dup2()");
return -1;
} else {
if (close_after_restore) {
close(fd_stderr_original);
}
}
}
return 0;
}
int fpm_stdio_redirect_stderr_to_error_log(void)
{
if (fpm_use_error_log()) {
/* prevent duping if logging to syslog */
if (fpm_globals.error_log_fd > 0 && fpm_globals.error_log_fd != STDERR_FILENO) {
/* there might be messages to stderr from other parts of the code, we need to log them all */
if (0 > dup2(fpm_globals.error_log_fd, STDERR_FILENO)) {
zlog(ZLOG_SYSERROR, "failed to tie stderr fd with error_log fd: dup2()");
return -1;
}
}
}
return 0;
}
int fpm_stdio_redirect_stderr_to_dev_null_for_syslog(void)
{
if (fpm_use_error_log()) {
#ifdef HAVE_SYSLOG_H
if (fpm_globals.error_log_fd == ZLOG_SYSLOG) {
/* dup to /dev/null when using syslog */
dup2(STDOUT_FILENO, STDERR_FILENO);
}
#endif
}
return 0;
}
int fpm_stdio_init_child(struct fpm_worker_pool_s *wp) /* {{{ */
{
#ifdef HAVE_SYSLOG_H
if (fpm_globals.error_log_fd == ZLOG_SYSLOG) {
php_closelog(); /* ensure to close syslog not to interrupt with PHP syslog code */
} else
#endif
/* Notice: child cannot use master error_log
* because not aware when being reopen
* else, should use if (!fpm_use_error_log())
*/
if (fpm_globals.error_log_fd > 0) {
close(fpm_globals.error_log_fd);
}
fpm_globals.error_log_fd = -1;
zlog_set_fd(-1);
return 0;
}
/* }}} */
#define FPM_STDIO_CMD_FLUSH "\0fscf"
int fpm_stdio_flush_child(void)
{
return write(STDERR_FILENO, FPM_STDIO_CMD_FLUSH, sizeof(FPM_STDIO_CMD_FLUSH));
}
static void fpm_stdio_child_said(struct fpm_event_s *ev, short which, void *arg) /* {{{ */
{
int fd = ev->fd;
char buf[1024];
struct fpm_child_s *child;
int is_stdout;
struct fpm_event_s *event;
int in_buf = 0, cmd_pos = 0, pos, start;
int read_fail = 0, create_log_stream;
struct zlog_stream *log_stream;
if (!arg) {
return;
}
child = (struct fpm_child_s *) arg;
is_stdout = (fd == child->fd_stdout);
if (is_stdout) {
event = &child->ev_stdout;
} else {
event = &child->ev_stderr;
}
create_log_stream = !child->log_stream;
if (create_log_stream) {
log_stream = child->log_stream = malloc(sizeof(struct zlog_stream));
zlog_stream_init_ex(log_stream, ZLOG_WARNING, STDERR_FILENO);
zlog_stream_set_decorating(log_stream, child->wp->config->decorate_workers_output);
zlog_stream_set_wrapping(log_stream, ZLOG_TRUE);
zlog_stream_set_msg_prefix(log_stream, STREAM_SET_MSG_PREFIX_FMT,
child->wp->config->name, (int) child->pid, is_stdout ? "stdout" : "stderr");
zlog_stream_set_msg_quoting(log_stream, ZLOG_TRUE);
zlog_stream_set_is_stdout(log_stream, is_stdout);
zlog_stream_set_child_pid(log_stream, (int)child->pid);
} else {
log_stream = child->log_stream;
// if fd type (stdout/stderr) or child's pid is changed,
// then the stream will be finished and msg's prefix will be reinitialized
if (log_stream->is_stdout != (unsigned int)is_stdout || log_stream->child_pid != (int)child->pid) {
zlog_stream_finish(log_stream);
zlog_stream_set_msg_prefix(log_stream, STREAM_SET_MSG_PREFIX_FMT,
child->wp->config->name, (int) child->pid, is_stdout ? "stdout" : "stderr");
zlog_stream_set_is_stdout(log_stream, is_stdout);
zlog_stream_set_child_pid(log_stream, (int)child->pid);
}
}
while (1) {
stdio_read:
in_buf = read(fd, buf, sizeof(buf) - 1);
if (in_buf <= 0) { /* no data */
if (in_buf == 0 || !PHP_IS_TRANSIENT_ERROR(errno)) {
/* pipe is closed or error */
read_fail = (in_buf < 0) ? in_buf : 1;
}
break;
}
start = 0;
if (cmd_pos > 0) {
if ((sizeof(FPM_STDIO_CMD_FLUSH) - cmd_pos) <= in_buf &&
!memcmp(buf, &FPM_STDIO_CMD_FLUSH[cmd_pos], sizeof(FPM_STDIO_CMD_FLUSH) - cmd_pos)) {
zlog_stream_finish(log_stream);
start = cmd_pos;
} else {
zlog_stream_str(log_stream, &FPM_STDIO_CMD_FLUSH[0], cmd_pos);
}
cmd_pos = 0;
}
for (pos = start; pos < in_buf; pos++) {
switch (buf[pos]) {
case '\n':
zlog_stream_str(log_stream, buf + start, pos - start);
zlog_stream_finish(log_stream);
start = pos + 1;
break;
case '\0':
if (pos + sizeof(FPM_STDIO_CMD_FLUSH) <= in_buf) {
if (!memcmp(buf + pos, FPM_STDIO_CMD_FLUSH, sizeof(FPM_STDIO_CMD_FLUSH))) {
zlog_stream_str(log_stream, buf + start, pos - start);
zlog_stream_finish(log_stream);
start = pos + sizeof(FPM_STDIO_CMD_FLUSH);
pos = start - 1;
}
} else if (!memcmp(buf + pos, FPM_STDIO_CMD_FLUSH, in_buf - pos)) {
cmd_pos = in_buf - pos;
zlog_stream_str(log_stream, buf + start, pos - start);
goto stdio_read;
}
break;
}
}
if (start < pos) {
zlog_stream_str(log_stream, buf + start, pos - start);
}
}
if (read_fail) {
if (create_log_stream) {
zlog_stream_set_msg_suffix(log_stream, NULL, ", pipe is closed");
zlog_stream_finish(log_stream);
}
if (read_fail < 0) {
zlog(ZLOG_SYSERROR, "unable to read what child %d said into %s", (int) child->pid, is_stdout ? "stdout" : "stderr");
}
fpm_event_del(event);
child->postponed_free = true;
if (is_stdout) {
close(child->fd_stdout);
child->fd_stdout = -1;
} else {
close(child->fd_stderr);
child->fd_stderr = -1;
}
}
}
/* }}} */
int fpm_stdio_prepare_pipes(struct fpm_child_s *child) /* {{{ */
{
if (0 == child->wp->config->catch_workers_output) { /* not required */
return 0;
}
if (0 > pipe(fd_stdout)) {
zlog(ZLOG_SYSERROR, "failed to prepare the stdout pipe");
return -1;
}
if (0 > pipe(fd_stderr)) {
zlog(ZLOG_SYSERROR, "failed to prepare the stderr pipe");
close(fd_stdout[0]);
close(fd_stdout[1]);
return -1;
}
if (0 > fd_set_blocked(fd_stdout[0], 0) || 0 > fd_set_blocked(fd_stderr[0], 0)) {
zlog(ZLOG_SYSERROR, "failed to unblock pipes");
close(fd_stdout[0]);
close(fd_stdout[1]);
close(fd_stderr[0]);
close(fd_stderr[1]);
return -1;
}
return 0;
}
/* }}} */
int fpm_stdio_parent_use_pipes(struct fpm_child_s *child) /* {{{ */
{
if (0 == child->wp->config->catch_workers_output) { /* not required */
return 0;
}
close(fd_stdout[1]);
close(fd_stderr[1]);
child->fd_stdout = fd_stdout[0];
child->fd_stderr = fd_stderr[0];
fpm_event_set(&child->ev_stdout, child->fd_stdout, FPM_EV_READ, fpm_stdio_child_said, child);
fpm_event_add(&child->ev_stdout, 0);
fpm_event_set(&child->ev_stderr, child->fd_stderr, FPM_EV_READ, fpm_stdio_child_said, child);
fpm_event_add(&child->ev_stderr, 0);
return 0;
}
/* }}} */
int fpm_stdio_discard_pipes(struct fpm_child_s *child) /* {{{ */
{
if (0 == child->wp->config->catch_workers_output) { /* not required */
return 0;
}
close(fd_stdout[1]);
close(fd_stderr[1]);
close(fd_stdout[0]);
close(fd_stderr[0]);
return 0;
}
/* }}} */
void fpm_stdio_child_use_pipes(struct fpm_child_s *child) /* {{{ */
{
if (child->wp->config->catch_workers_output) {
dup2(fd_stdout[1], STDOUT_FILENO);
dup2(fd_stderr[1], STDERR_FILENO);
close(fd_stdout[0]); close(fd_stdout[1]);
close(fd_stderr[0]); close(fd_stderr[1]);
} else {
/* stdout of parent is always /dev/null */
dup2(STDOUT_FILENO, STDERR_FILENO);
}
}
/* }}} */
int fpm_stdio_open_error_log(int reopen) /* {{{ */
{
int fd;
#ifdef HAVE_SYSLOG_H
if (!strcasecmp(fpm_global_config.error_log, "syslog")) {
php_openlog(fpm_global_config.syslog_ident, LOG_PID | LOG_CONS, fpm_global_config.syslog_facility);
fpm_globals.error_log_fd = ZLOG_SYSLOG;
if (fpm_use_error_log()) {
zlog_set_fd(fpm_globals.error_log_fd);
}
return 0;
}
#endif
fd = open(fpm_global_config.error_log, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
if (0 > fd) {
zlog(ZLOG_SYSERROR, "failed to open error_log (%s)", fpm_global_config.error_log);
return -1;
}
if (reopen) {
dup2(fd, fpm_globals.error_log_fd);
close(fd);
fd = fpm_globals.error_log_fd; /* for FD_CLOSEXEC to work */
} else {
fpm_globals.error_log_fd = fd;
if (fpm_use_error_log()) {
zlog_set_fd(fpm_globals.error_log_fd);
}
}
if (0 > fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC)) {
zlog(ZLOG_WARNING, "failed to change attribute of error_log");
}
return 0;
}
/* }}} */
| 10,587 | 25.14321 | 119 |
c
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_stdio.h
|
/* (c) 2007,2008 Andrei Nigmatulin */
#ifndef FPM_STDIO_H
#define FPM_STDIO_H 1
#include "fpm_worker_pool.h"
#define STREAM_SET_MSG_PREFIX_FMT "[pool %s] child %d said into %s: "
int fpm_stdio_init_main(void);
int fpm_stdio_init_final(void);
int fpm_stdio_init_child(struct fpm_worker_pool_s *wp);
int fpm_stdio_flush_child(void);
int fpm_stdio_prepare_pipes(struct fpm_child_s *child);
void fpm_stdio_child_use_pipes(struct fpm_child_s *child);
int fpm_stdio_parent_use_pipes(struct fpm_child_s *child);
int fpm_stdio_discard_pipes(struct fpm_child_s *child);
int fpm_stdio_open_error_log(int reopen);
int fpm_stdio_save_original_stderr(void);
int fpm_stdio_restore_original_stderr(int close_after_restore);
int fpm_stdio_redirect_stderr_to_dev_null_for_syslog(void);
int fpm_stdio_redirect_stderr_to_error_log(void);
#endif
| 832 | 32.32 | 69 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_systemd.c
|
#include "fpm_config.h"
#include <sys/types.h>
#include <systemd/sd-daemon.h>
#include "fpm.h"
#include "fpm_clock.h"
#include "fpm_worker_pool.h"
#include "fpm_scoreboard.h"
#include "zlog.h"
#include "fpm_systemd.h"
static void fpm_systemd(void)
{
static unsigned long int last=0;
struct fpm_worker_pool_s *wp;
unsigned long int requests=0, slow_req=0;
int active=0, idle=0;
for (wp = fpm_worker_all_pools; wp; wp = wp->next) {
if (wp->scoreboard) {
active += wp->scoreboard->active;
idle += wp->scoreboard->idle;
requests += wp->scoreboard->requests;
slow_req += wp->scoreboard->slow_rq;
}
}
/*
zlog(ZLOG_DEBUG, "systemd %s (Processes active:%d, idle:%d, Requests:%lu, slow:%lu, Traffic:%.3greq/sec)",
fpm_global_config.systemd_watchdog ? "watchdog" : "heartbeat",
active, idle, requests, slow_req, ((float)requests - last) * 1000.0 / fpm_global_config.systemd_interval);
*/
if (0 > sd_notifyf(0, "READY=1\n%s"
"STATUS=Processes active: %d, idle: %d, Requests: %lu, slow: %lu, Traffic: %.3greq/sec",
fpm_global_config.systemd_watchdog ? "WATCHDOG=1\n" : "",
active, idle, requests, slow_req, ((float)requests - last) * 1000.0 / fpm_global_config.systemd_interval)) {
zlog(ZLOG_NOTICE, "failed to notify status to systemd");
}
last = requests;
}
void fpm_systemd_heartbeat(struct fpm_event_s *ev, short which, void *arg) /* {{{ */
{
static struct fpm_event_s heartbeat;
if (fpm_globals.parent_pid != getpid()) {
return; /* sanity check */
}
if (which == FPM_EV_TIMEOUT) {
fpm_systemd();
return;
}
if (0 > sd_notifyf(0, "READY=1\n"
"STATUS=Ready to handle connections\n"
"MAINPID=%lu",
(unsigned long) getpid())) {
zlog(ZLOG_WARNING, "failed to notify start to systemd");
} else {
zlog(ZLOG_DEBUG, "have notify start to systemd");
}
/* first call without setting which to initialize the timer */
if (fpm_global_config.systemd_interval > 0) {
fpm_event_set_timer(&heartbeat, FPM_EV_PERSIST, &fpm_systemd_heartbeat, NULL);
fpm_event_add(&heartbeat, fpm_global_config.systemd_interval);
zlog(ZLOG_NOTICE, "systemd monitor interval set to %dms", fpm_global_config.systemd_interval);
} else {
zlog(ZLOG_NOTICE, "systemd monitor disabled");
}
}
/* }}} */
int fpm_systemd_conf(void)
{
char *watchdog;
int interval = 0;
watchdog = getenv("WATCHDOG_USEC");
if (watchdog) {
/* usec to msec, and half the configured delay */
interval = (int)(atol(watchdog) / 2000L);
zlog(ZLOG_DEBUG, "WATCHDOG_USEC=%s, interval=%d", watchdog, interval);
}
if (interval > 1000) {
if (fpm_global_config.systemd_interval > 0) {
zlog(ZLOG_WARNING, "systemd_interval option ignored");
}
zlog(ZLOG_NOTICE, "systemd watchdog configured to %.3gsec", (float)interval / 1000.0);
fpm_global_config.systemd_watchdog = 1;
fpm_global_config.systemd_interval = interval;
} else if (fpm_global_config.systemd_interval < 0) {
/* not set => default value */
fpm_global_config.systemd_interval = FPM_SYSTEMD_DEFAULT_HEARTBEAT;
} else {
/* sec to msec */
fpm_global_config.systemd_interval *= 1000;
}
return 0;
}
| 3,146 | 27.351351 | 112 |
c
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_unix.h
|
/* (c) 2007,2008 Andrei Nigmatulin */
#ifndef FPM_UNIX_H
#define FPM_UNIX_H 1
#include "fpm_worker_pool.h"
bool fpm_unix_test_config(struct fpm_worker_pool_s *wp);
int fpm_unix_resolve_socket_permissions(struct fpm_worker_pool_s *wp);
int fpm_unix_set_socket_permissions(struct fpm_worker_pool_s *wp, const char *path);
int fpm_unix_free_socket_permissions(struct fpm_worker_pool_s *wp);
int fpm_unix_init_child(struct fpm_worker_pool_s *wp);
int fpm_unix_init_main(void);
extern size_t fpm_pagesize;
#endif
| 516 | 24.85 | 84 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/fpm_worker_pool.h
|
/* (c) 2007,2008 Andrei Nigmatulin */
#ifndef FPM_WORKER_POOL_H
#define FPM_WORKER_POOL_H 1
#include "fpm_conf.h"
#include "fpm_shm.h"
struct fpm_worker_pool_s;
struct fpm_child_s;
struct fpm_child_stat_s;
struct fpm_shm_s;
enum fpm_address_domain {
FPM_AF_UNIX = 1,
FPM_AF_INET = 2
};
struct fpm_worker_pool_s {
struct fpm_worker_pool_s *next;
struct fpm_worker_pool_s *shared;
struct fpm_worker_pool_config_s *config;
char *user, *home; /* for setting env USER and HOME */
enum fpm_address_domain listen_address_domain;
int listening_socket;
int set_uid, set_gid; /* config uid and gid */
char *set_user; /* config user name */
int socket_uid, socket_gid, socket_mode;
/* runtime */
struct fpm_child_s *children;
int running_children;
int idle_spawn_rate;
int warn_max_children;
#if 0
int warn_lq;
#endif
struct fpm_scoreboard_s *scoreboard;
int log_fd;
char **limit_extensions;
/* for ondemand PM */
struct fpm_event_s *ondemand_event;
int socket_event_set;
#ifdef HAVE_FPM_ACL
void *socket_acl;
#endif
};
struct fpm_worker_pool_s *fpm_worker_pool_alloc(void);
void fpm_worker_pool_free(struct fpm_worker_pool_s *wp);
int fpm_worker_pool_init_main(void);
void fpm_worker_pool_free_limit_extensions(char **limit_extensions);
extern struct fpm_worker_pool_s *fpm_worker_all_pools;
#endif
| 1,350 | 21.516667 | 68 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/zlog.c
|
/* (c) 2004-2007 Andrei Nigmatulin */
#include "fpm_config.h"
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <stdarg.h>
#include <sys/time.h>
#include <errno.h>
#include "php_syslog.h"
#include "zlog.h"
#include "fpm.h"
#include "zend_portability.h"
/* buffer is used for fmt result and it should never be over 2048 */
#define MAX_BUF_LENGTH 2048
/* maximal length for wrapping prefix */
#define MAX_WRAPPING_PREFIX_LENGTH 512
#define EXTRA_SPACE_FOR_PREFIX 128
static int zlog_fd = -1;
static int zlog_level = ZLOG_NOTICE;
static int zlog_limit = ZLOG_DEFAULT_LIMIT;
static zlog_bool zlog_buffering = ZLOG_DEFAULT_BUFFERING;
static int launched = 0;
static void (*external_logger)(int, char *, size_t) = NULL;
static const char *level_names[] = {
[ZLOG_DEBUG] = "DEBUG",
[ZLOG_NOTICE] = "NOTICE",
[ZLOG_WARNING] = "WARNING",
[ZLOG_ERROR] = "ERROR",
[ZLOG_ALERT] = "ALERT",
};
#ifdef HAVE_SYSLOG_H
const int syslog_priorities[] = {
[ZLOG_DEBUG] = LOG_DEBUG,
[ZLOG_NOTICE] = LOG_NOTICE,
[ZLOG_WARNING] = LOG_WARNING,
[ZLOG_ERROR] = LOG_ERR,
[ZLOG_ALERT] = LOG_ALERT,
};
#endif
void zlog_set_external_logger(void (*logger)(int, char *, size_t)) /* {{{ */
{
external_logger = logger;
}
/* }}} */
const char *zlog_get_level_name(int log_level) /* {{{ */
{
if (log_level < 0) {
log_level = zlog_level;
} else if (log_level < ZLOG_DEBUG || log_level > ZLOG_ALERT) {
return "unknown value";
}
return level_names[log_level];
}
/* }}} */
void zlog_set_launched(void) /* {{{ */
{
launched = 1;
}
/* }}} */
size_t zlog_print_time(struct timeval *tv, char *timebuf, size_t timebuf_len) /* {{{ */
{
struct tm t;
size_t len;
len = strftime(timebuf, timebuf_len, "[%d-%b-%Y %H:%M:%S",
localtime_r((const time_t *) &tv->tv_sec, &t));
if (zlog_level == ZLOG_DEBUG) {
len += snprintf(timebuf + len, timebuf_len - len, ".%06d", (int) tv->tv_usec);
}
len += snprintf(timebuf + len, timebuf_len - len, "] ");
return len;
}
/* }}} */
int zlog_set_fd(int new_fd) /* {{{ */
{
int old_fd = zlog_fd;
zlog_fd = new_fd;
return old_fd;
}
/* }}} */
int zlog_set_level(int new_value) /* {{{ */
{
int old_value = zlog_level;
if (new_value < ZLOG_DEBUG || new_value > ZLOG_ALERT) return old_value;
zlog_level = new_value;
return old_value;
}
/* }}} */
int zlog_set_limit(int new_value) /* {{{ */
{
int old_value = zlog_limit;
zlog_limit = new_value;
return old_value;
}
/* }}} */
int zlog_set_buffering(zlog_bool buffering) /* {{{ */
{
int old_value = zlog_buffering;
zlog_buffering = buffering;
return old_value;
}
/* }}} */
static inline size_t zlog_truncate_buf(char *buf, size_t buf_size, size_t space_left) /* {{{ */
{
memcpy(buf + buf_size - sizeof("...") + 1 - space_left, "...", sizeof("...") - 1);
return buf_size - space_left;
}
/* }}} */
static inline void zlog_external(
int flags, char *buf, size_t buf_size, const char *fmt, va_list args) /* {{{ */
{
va_list ap;
size_t len;
va_copy(ap, args);
len = vsnprintf(buf, buf_size, fmt, ap);
va_end(ap);
if (len >= buf_size) {
len = zlog_truncate_buf(buf, buf_size, 0);
}
external_logger(flags & ZLOG_LEVEL_MASK, buf, len);
}
/* }}} */
static size_t zlog_buf_prefix(
const char *function, int line, int flags,
char *buf, size_t buf_size, int use_syslog) /* {{{ */
{
struct timeval tv;
size_t len = 0;
#ifdef HAVE_SYSLOG_H
if (use_syslog /* && !fpm_globals.is_child */) {
if (zlog_level == ZLOG_DEBUG) {
len += snprintf(buf, buf_size, "[%s] %s(), line %d: ",
level_names[flags & ZLOG_LEVEL_MASK], function, line);
} else {
len += snprintf(buf, buf_size, "[%s] ", level_names[flags & ZLOG_LEVEL_MASK]);
}
} else
#endif
{
if (!fpm_globals.is_child) {
gettimeofday(&tv, 0);
len = zlog_print_time(&tv, buf, buf_size);
}
if (zlog_level == ZLOG_DEBUG) {
if (!fpm_globals.is_child) {
len += snprintf(buf + len, buf_size - len, "%s: pid %d, %s(), line %d: ",
level_names[flags & ZLOG_LEVEL_MASK], getpid(), function, line);
} else {
len += snprintf(buf + len, buf_size - len, "%s: %s(), line %d: ",
level_names[flags & ZLOG_LEVEL_MASK], function, line);
}
} else {
len += snprintf(buf + len, buf_size - len, "%s: ",
level_names[flags & ZLOG_LEVEL_MASK]);
}
}
return len;
}
/* }}} */
void vzlog(const char *function, int line, int flags, const char *fmt, va_list args) /* {{{ */
{
char buf[MAX_BUF_LENGTH];
size_t buf_size = MAX_BUF_LENGTH;
size_t len = 0;
int truncated = 0;
int saved_errno;
if (external_logger) {
zlog_external(flags, buf, buf_size, fmt, args);
}
if ((flags & ZLOG_LEVEL_MASK) < zlog_level) {
return;
}
saved_errno = errno;
len = zlog_buf_prefix(function, line, flags, buf, buf_size, zlog_fd == ZLOG_SYSLOG);
if (len > buf_size - 1) {
truncated = 1;
} else {
len += vsnprintf(buf + len, buf_size - len, fmt, args);
if (len >= buf_size) {
truncated = 1;
}
}
if (!truncated) {
if (flags & ZLOG_HAVE_ERRNO) {
len += snprintf(buf + len, buf_size - len,
": %s (%d)", strerror(saved_errno), saved_errno);
if (len >= zlog_limit) {
truncated = 1;
}
}
}
if (truncated) {
len = zlog_truncate_buf(buf, zlog_limit < buf_size ? zlog_limit : buf_size, 1);
}
#ifdef HAVE_SYSLOG_H
if (zlog_fd == ZLOG_SYSLOG) {
buf[len] = '\0';
php_syslog(syslog_priorities[zlog_level], "%s", buf);
buf[len++] = '\n';
} else
#endif
{
buf[len++] = '\n';
zend_quiet_write(zlog_fd > -1 ? zlog_fd : STDERR_FILENO, buf, len);
}
if (zlog_fd != STDERR_FILENO && zlog_fd != -1 &&
!launched && (flags & ZLOG_LEVEL_MASK) >= ZLOG_NOTICE) {
zend_quiet_write(STDERR_FILENO, buf, len);
}
}
/* }}} */
void zlog_ex(const char *function, int line, int flags, const char *fmt, ...) /* {{{ */
{
va_list args;
va_start(args, fmt);
vzlog(function, line, flags, fmt, args);
va_end(args);
}
/* }}} */
/* predefine stream init that is used by zlog_msg_ex */
static inline void zlog_stream_init_internal(
struct zlog_stream *stream, int flags, size_t capacity, int fd);
void zlog_msg_ex(const char *function, int line, int flags,
const char *prefix, const char *msg) /* {{{ */
{
struct zlog_stream stream;
size_t prefix_len = strlen(prefix);
size_t msg_len = strlen(msg);
zlog_stream_init_internal(&stream, flags, msg_len + prefix_len, 0);
zlog_stream_prefix_ex(&stream, function, line);
zlog_stream_str(&stream, prefix, prefix_len);
zlog_stream_str(&stream, msg, msg_len);
zlog_stream_finish(&stream);
zlog_stream_destroy(&stream);
}
/* }}} */
/* STREAM OPS */
static zlog_bool zlog_stream_buf_alloc_ex(struct zlog_stream *stream, size_t needed) /* {{{ */
{
char *buf;
size_t size = stream->buf.size ?: stream->buf_init_size;
size = MIN(zlog_limit, MAX((stream->buf.data ? (size << 1) : size), needed));
buf = realloc(stream->buf.data, size);
if (buf == NULL) {
return 0;
}
stream->buf.data = buf;
stream->buf.size = size;
return 1;
}
/* }}} */
inline static zlog_bool zlog_stream_buf_alloc(struct zlog_stream *stream) /* {{{ */
{
/* if there is enough space in the buffer, we do not need to reallocate */
if (stream->buf.data && stream->buf.size >= MIN(zlog_limit, stream->buf_init_size)) {
return 1;
}
return zlog_stream_buf_alloc_ex(stream, 0);
}
/* }}} */
static inline ssize_t zlog_stream_direct_write_ex(
struct zlog_stream *stream, const char *buf, size_t len,
const char *append, size_t append_len) /* {{{ */
{
if (stream->use_fd) {
zend_quiet_write(stream->fd, buf, len);
if (append_len > 0) {
zend_quiet_write(stream->fd, append, append_len);
}
}
if (stream->use_stderr) {
zend_quiet_write(STDERR_FILENO, buf, len);
if (append_len > 0) {
zend_quiet_write(STDERR_FILENO, append, append_len);
}
}
return len;
}
/* }}} */
static ssize_t zlog_stream_direct_write(
struct zlog_stream *stream, const char *buf, size_t len) /* {{{ */
{
return zlog_stream_direct_write_ex(stream, buf, len, NULL, 0);
}
/* }}} */
static inline ssize_t zlog_stream_unbuffered_write(
struct zlog_stream *stream, const char *buf, size_t len) /* {{{ */
{
const char *append = NULL;
size_t append_len = 0, required_len, reserved_len;
ssize_t written;
if (stream->len == 0) {
stream->len = zlog_stream_prefix_ex(stream, stream->function, stream->line);
}
/* msg_suffix_len and msg_quote are used only for wrapping */
reserved_len = stream->len + stream->msg_suffix_len + stream->msg_quote;
required_len = reserved_len + len;
if (required_len >= zlog_limit) {
if (stream->wrap) {
size_t available_len;
if (required_len == zlog_limit) {
append = NULL;
append_len = 0;
} else {
append = "\n";
append_len = 1;
}
available_len = zlog_limit - reserved_len - 1;
zlog_stream_direct_write(stream, buf, available_len);
if (append != NULL) {
if (stream->msg_quote) {
zlog_stream_direct_write(stream, "\"", 1);
}
if (stream->msg_suffix) {
zlog_stream_direct_write(stream, stream->msg_suffix, stream->msg_suffix_len);
}
zlog_stream_direct_write(stream, append, append_len);
}
stream->len = 0;
written = zlog_stream_unbuffered_write(
stream, buf + available_len, len - available_len);
if (written > 0) {
return available_len + written;
}
return written;
}
/* this would be used in case of an option for disabling wrapping in direct write */
stream->full = 1;
if (required_len == zlog_limit) {
append = NULL;
} else {
append = "...";
append_len = sizeof("...") - 1;
len = zlog_limit - stream->len - append_len;
}
}
written = zlog_stream_direct_write_ex(stream, buf, len, append, append_len);
if (written > 0) {
/* currently written will be always len as the write is blocking
* - this should be address if we change to non-blocking write */
stream->len += written;
}
return written;
}
/* }}} */
static inline ssize_t zlog_stream_buf_copy_cstr(
struct zlog_stream *stream, const char *str, size_t str_len) /* {{{ */
{
if (stream->buf.size - stream->len <= str_len &&
!zlog_stream_buf_alloc_ex(stream, str_len + stream->len)) {
return -1;
}
memcpy(stream->buf.data + stream->len, str, str_len);
stream->len += str_len;
return str_len;
}
/* }}} */
static inline ssize_t zlog_stream_buf_copy_char(struct zlog_stream *stream, char c) /* {{{ */
{
if (stream->buf.size - stream->len < 1 && !zlog_stream_buf_alloc_ex(stream, 1)) {
return -1;
}
stream->buf.data[stream->len++] = c;
return 1;
}
/* }}} */
static ssize_t zlog_stream_buf_flush(struct zlog_stream *stream) /* {{{ */
{
ssize_t written;
#ifdef HAVE_SYSLOG_H
if (stream->use_syslog) {
zlog_stream_buf_copy_char(stream, '\0');
php_syslog(syslog_priorities[zlog_level], "%s", stream->buf.data);
--stream->len;
}
#endif
if (external_logger != NULL) {
external_logger(stream->flags & ZLOG_LEVEL_MASK,
stream->buf.data + stream->prefix_len, stream->len - stream->prefix_len);
}
zlog_stream_buf_copy_char(stream, '\n');
written = zlog_stream_direct_write(stream, stream->buf.data, stream->len);
stream->len = 0;
return written;
}
/* }}} */
static ssize_t zlog_stream_buf_append(
struct zlog_stream *stream, const char *str, size_t str_len) /* {{{ */
{
int over_limit = 0;
size_t available_len, required_len, reserved_len;
if (stream->len == 0) {
stream->len = zlog_stream_prefix_ex(stream, stream->function, stream->line);
}
/* msg_suffix_len and msg_quote are used only for wrapping */
reserved_len = stream->len + stream->msg_suffix_len + stream->msg_quote;
required_len = reserved_len + str_len;
if (required_len >= zlog_limit) {
over_limit = 1;
available_len = zlog_limit - reserved_len - 1;
} else {
available_len = str_len;
}
if (zlog_stream_buf_copy_cstr(stream, str, available_len) < 0) {
return -1;
}
if (!over_limit) {
return available_len;
}
if (stream->wrap) {
if (stream->msg_quote) {
zlog_stream_buf_copy_char(stream, '"');
}
if (stream->msg_suffix != NULL) {
zlog_stream_buf_copy_cstr(stream, stream->msg_suffix, stream->msg_suffix_len);
}
zlog_stream_buf_flush(stream);
zlog_stream_prefix_ex(stream, stream->function, stream->line);
return available_len + zlog_stream_buf_append(
stream, str + available_len, str_len - available_len);
}
stream->len = zlog_truncate_buf(stream->buf.data, stream->len, 0);
stream->full = 1;
return available_len;
}
/* }}} */
static inline void zlog_stream_init_internal(
struct zlog_stream *stream, int flags, size_t capacity, int fd) /* {{{ */
{
if (fd == 0) {
fd = zlog_fd;
}
memset(stream, 0, sizeof(struct zlog_stream));
stream->flags = flags;
stream->use_syslog = fd == ZLOG_SYSLOG;
stream->use_fd = fd > 0;
stream->use_buffer = zlog_buffering || external_logger != NULL || stream->use_syslog;
stream->buf_init_size = capacity;
stream->use_stderr = fd < 0 ||
(
fd != STDERR_FILENO && fd != STDOUT_FILENO && !launched &&
(flags & ZLOG_LEVEL_MASK) >= ZLOG_NOTICE
);
stream->prefix_buffer = (flags & ZLOG_LEVEL_MASK) >= zlog_level &&
(stream->use_fd || stream->use_stderr || stream->use_syslog);
stream->fd = fd > -1 ? fd : STDERR_FILENO;
}
/* }}} */
void zlog_stream_init(struct zlog_stream *stream, int flags) /* {{{ */
{
zlog_stream_init_internal(stream, flags, 1024, 0);
}
/* }}} */
void zlog_stream_init_ex(struct zlog_stream *stream, int flags, int fd) /* {{{ */
{
zlog_stream_init_internal(stream, flags, 1024, fd);
stream->wrap = 1;
}
/* }}} */
void zlog_stream_set_decorating(struct zlog_stream *stream, zlog_bool decorate) /* {{{ */
{
if (decorate) {
stream->decorate = 1;
} else {
stream->decorate = 0;
stream->msg_quote = 0;
stream->prefix_buffer = 0;
}
}
/* }}} */
void zlog_stream_set_wrapping(struct zlog_stream *stream, zlog_bool wrap) /* {{{ */
{
stream->wrap = wrap ? 1 : 0;
}
/* }}} */
void zlog_stream_set_is_stdout(struct zlog_stream *stream, zlog_bool is_stdout) /* {{{ */
{
stream->is_stdout = is_stdout ? 1 : 0;
}
/* }}} */
void zlog_stream_set_child_pid(struct zlog_stream *stream, int child_pid) /* {{{ */
{
stream->child_pid = child_pid;
}
/* }}} */
void zlog_stream_set_msg_quoting(struct zlog_stream *stream, zlog_bool quote) /* {{{ */
{
stream->msg_quote = quote && stream->decorate ? 1 : 0;
}
/* }}} */
zlog_bool zlog_stream_set_msg_prefix(struct zlog_stream *stream, const char *fmt, ...) /* {{{ */
{
char buf[MAX_WRAPPING_PREFIX_LENGTH];
size_t len;
va_list args;
if (!stream->decorate) {
return ZLOG_TRUE;
}
va_start(args, fmt);
len = vsnprintf(buf, MAX_WRAPPING_PREFIX_LENGTH - 1, fmt, args);
va_end(args);
if (stream->msg_prefix_len < len) {
stream->msg_prefix = stream->msg_prefix_len ? realloc(stream->msg_prefix, len + 1) : malloc(len + 1);
if (stream->msg_prefix == NULL) {
return ZLOG_FALSE;
}
}
memcpy(stream->msg_prefix, buf, len);
stream->msg_prefix[len] = 0;
stream->msg_prefix_len = len;
return len;
}
/* }}} */
zlog_bool zlog_stream_set_msg_suffix(
struct zlog_stream *stream, const char *suffix, const char *final_suffix) /* {{{ */
{
size_t len;
if (!stream->wrap || !stream->decorate) {
return ZLOG_TRUE;
}
if (suffix != NULL && final_suffix != NULL) {
stream->msg_suffix_len = strlen(suffix);
stream->msg_final_suffix_len = strlen(final_suffix);
len = stream->msg_suffix_len + stream->msg_final_suffix_len + 2;
if (stream->msg_suffix != NULL) {
free(stream->msg_suffix);
}
stream->msg_suffix = malloc(len);
if (stream->msg_suffix == NULL) {
return ZLOG_FALSE;
}
stream->msg_final_suffix = stream->msg_suffix + stream->msg_suffix_len + 1;
memcpy(stream->msg_suffix, suffix, stream->msg_suffix_len + 1);
memcpy(stream->msg_final_suffix, final_suffix, stream->msg_final_suffix_len + 1);
return ZLOG_TRUE;
}
if (suffix != NULL) {
stream->msg_suffix_len = strlen(suffix);
len = stream->msg_suffix_len + 1;
if (stream->msg_suffix != NULL) {
free(stream->msg_suffix);
}
stream->msg_suffix = malloc(len);
if (stream->msg_suffix == NULL) {
return ZLOG_FALSE;
}
memcpy(stream->msg_suffix, suffix, len);
return ZLOG_TRUE;
}
if (final_suffix != NULL) {
stream->msg_final_suffix_len = strlen(final_suffix);
len = stream->msg_final_suffix_len + 1;
if (stream->msg_final_suffix != NULL) {
free(stream->msg_final_suffix);
}
stream->msg_final_suffix = malloc(len);
if (stream->msg_final_suffix == NULL) {
return ZLOG_FALSE;
}
memcpy(stream->msg_final_suffix, final_suffix, len);
return ZLOG_TRUE;
}
return ZLOG_TRUE;
}
/* }}} */
ssize_t zlog_stream_prefix_ex(struct zlog_stream *stream, const char *function, int line) /* {{{ */
{
size_t len;
if (!stream->prefix_buffer) {
return 0;
}
if (stream->wrap && stream->function == NULL) {
stream->function = function;
stream->line = line;
}
if (stream->use_buffer) {
if (!zlog_stream_buf_alloc(stream)) {
return -1;
}
len = zlog_buf_prefix(
function, line, stream->flags,
stream->buf.data, stream->buf.size, stream->use_syslog);
stream->len = stream->prefix_len = len;
if (stream->msg_prefix != NULL) {
zlog_stream_buf_copy_cstr(stream, stream->msg_prefix, stream->msg_prefix_len);
}
if (stream->msg_quote) {
zlog_stream_buf_copy_char(stream, '"');
}
return stream->len;
} else {
char sbuf[1024];
ssize_t written;
len = zlog_buf_prefix(function, line, stream->flags, sbuf, 1024, stream->use_syslog);
written = zlog_stream_direct_write(stream, sbuf, len);
if (stream->msg_prefix != NULL) {
written += zlog_stream_direct_write(
stream, stream->msg_prefix, stream->msg_prefix_len);
}
if (stream->msg_quote) {
written += zlog_stream_direct_write(stream, "\"", 1);
}
return written;
}
}
/* }}} */
ssize_t zlog_stream_vformat(struct zlog_stream *stream, const char *fmt, va_list args) /* {{{ */
{
char sbuf[1024];
size_t len;
len = vsnprintf(sbuf, 1024, fmt, args);
return zlog_stream_str(stream, sbuf, len);
}
/* }}} */
ssize_t zlog_stream_format(struct zlog_stream *stream, const char *fmt, ...) /* {{{ */
{
ssize_t len;
va_list args;
va_start(args, fmt);
len = zlog_stream_vformat(stream, fmt, args);
va_end(args);
return len;
}
/* }}} */
ssize_t zlog_stream_str(struct zlog_stream *stream, const char *str, size_t str_len) /* {{{ */
{
/* do not write anything if the stream is full or str is empty */
if (str_len == 0 || stream->full) {
return 0;
}
/* reset stream if it is finished */
if (stream->finished) {
stream->finished = 0;
stream->len = 0;
stream->full = 0;
}
if (stream->use_buffer) {
return zlog_stream_buf_append(stream, str, str_len);
}
return zlog_stream_unbuffered_write(stream, str, str_len);
}
/* }}} */
static inline void zlog_stream_finish_buffer_suffix(struct zlog_stream *stream) /* {{{ */
{
if (stream->msg_quote) {
zlog_stream_buf_copy_char(stream, '"');
}
if (stream->msg_suffix != NULL) {
zlog_stream_buf_copy_cstr(stream, stream->msg_suffix, stream->msg_suffix_len);
}
if (stream->msg_final_suffix != NULL) {
if (stream->len + stream->msg_final_suffix_len >= zlog_limit) {
zlog_bool quoting = stream->msg_quote;
size_t final_suffix_wrap = stream->len + stream->msg_final_suffix_len + 1 - zlog_limit;
zlog_stream_buf_copy_cstr(
stream, stream->msg_final_suffix,
stream->msg_final_suffix_len - final_suffix_wrap);
zlog_stream_buf_copy_char(stream, '\n');
zlog_stream_buf_flush(stream);
stream->msg_quote = 0;
zlog_stream_prefix_ex(stream, stream->function, stream->line);
stream->msg_quote = quoting;
zlog_stream_buf_copy_cstr(
stream,
stream->msg_final_suffix + (stream->msg_final_suffix_len - final_suffix_wrap),
final_suffix_wrap);
zlog_stream_buf_copy_char(stream, '\n');
} else {
zlog_stream_buf_copy_cstr(
stream, stream->msg_final_suffix, stream->msg_final_suffix_len);
}
}
}
/* }}} */
static inline void zlog_stream_finish_direct_suffix(struct zlog_stream *stream) /* {{{ */
{
if (stream->msg_quote) {
zlog_stream_direct_write(stream, "\"", 1);
++stream->len;
}
if (stream->msg_suffix != NULL) {
/* we should always have space for wrap suffix so we don't have to check it */
zlog_stream_direct_write(stream, stream->msg_suffix, stream->msg_suffix_len);
stream->len += stream->msg_suffix_len;
}
if (stream->msg_final_suffix != NULL) {
if (stream->len + stream->msg_final_suffix_len >= zlog_limit) {
zlog_bool quoting = stream->msg_quote;
size_t final_suffix_wrap = stream->len + stream->msg_final_suffix_len + 1 - zlog_limit;
zlog_stream_direct_write_ex(
stream, stream->msg_final_suffix,
stream->msg_final_suffix_len - final_suffix_wrap, "\n", 1);
stream->msg_quote = 0;
zlog_stream_prefix_ex(stream, stream->function, stream->line);
stream->msg_quote = quoting;
zlog_stream_direct_write_ex(
stream,
stream->msg_final_suffix + (stream->msg_final_suffix_len - final_suffix_wrap),
final_suffix_wrap, "\n", 1);
} else {
zlog_stream_direct_write_ex(
stream, stream->msg_final_suffix, stream->msg_final_suffix_len, "\n", 1);
}
} else {
zlog_stream_direct_write(stream, "\n", 1);
}
}
/* }}} */
zlog_bool zlog_stream_finish(struct zlog_stream *stream) /* {{{ */
{
if (stream->finished || stream->len == 0) {
return ZLOG_TRUE;
}
if (stream->use_buffer) {
if (stream->decorate) {
zlog_stream_finish_buffer_suffix(stream);
}
zlog_stream_buf_flush(stream);
} else {
if (stream->decorate) {
zlog_stream_finish_direct_suffix(stream);
} else {
zlog_stream_direct_write(stream, "\n", 1);
}
}
stream->finished = 1;
return ZLOG_TRUE;
}
/* }}} */
void zlog_stream_destroy(struct zlog_stream *stream) /* {{{ */
{
if (stream->buf.data != NULL) {
free(stream->buf.data);
}
if (stream->msg_prefix != NULL) {
free(stream->msg_prefix);
}
if (stream->msg_suffix != NULL) {
free(stream->msg_suffix);
} else if (stream->msg_final_suffix != NULL) {
free(stream->msg_final_suffix);
}
}
/* }}} */
zlog_bool zlog_stream_close(struct zlog_stream *stream) /* {{{ */
{
zlog_bool finished = zlog_stream_finish(stream);
zlog_stream_destroy(stream);
return finished;
}
/* }}} */
| 22,159 | 24.529954 | 103 |
c
|
php-src
|
php-src-master/sapi/fpm/fpm/zlog.h
|
/* (c) 2004-2007 Andrei Nigmatulin */
#ifndef ZLOG_H
#define ZLOG_H 1
#include <stdarg.h>
#include <sys/types.h>
#define zlog(flags,...) zlog_ex(__func__, __LINE__, flags, __VA_ARGS__)
#define zlog_msg(flags, prefix, msg) zlog_msg_ex(__func__, __LINE__, flags, prefix, msg)
struct timeval;
typedef unsigned char zlog_bool;
#define ZLOG_TRUE 1
#define ZLOG_FALSE 0
void zlog_set_external_logger(void (*logger)(int, char *, size_t));
int zlog_set_fd(int new_fd);
int zlog_set_level(int new_value);
int zlog_set_limit(int new_value);
int zlog_set_buffering(zlog_bool buffering);
const char *zlog_get_level_name(int log_level);
void zlog_set_launched(void);
size_t zlog_print_time(struct timeval *tv, char *timebuf, size_t timebuf_len);
void vzlog(const char *function, int line, int flags, const char *fmt, va_list args);
void zlog_ex(const char *function, int line, int flags, const char *fmt, ...)
__attribute__ ((format(printf,4,5)));
void zlog_msg_ex(const char *function, int line, int flags,
const char *prefix, const char *msg);
#ifdef HAVE_SYSLOG_H
extern const int syslog_priorities[];
#endif
/* keep this same as FCGI_ERROR */
enum {
ZLOG_DEBUG = 1,
ZLOG_NOTICE = 2,
ZLOG_WARNING = 3,
ZLOG_ERROR = 4,
ZLOG_ALERT = 5,
};
#define ZLOG_LEVEL_MASK 7
#define ZLOG_HAVE_ERRNO 0x100
#define ZLOG_SYSERROR (ZLOG_ERROR | ZLOG_HAVE_ERRNO)
#define ZLOG_SYSLOG -2
/* STREAM */
struct zlog_stream_buffer {
char *data;
size_t size;
};
struct zlog_stream {
int flags;
unsigned int use_syslog:1;
unsigned int use_fd:1;
unsigned int use_buffer:1;
unsigned int use_stderr:1;
unsigned int prefix_buffer:1;
unsigned int finished:1;
unsigned int full:1;
unsigned int wrap:1;
unsigned int msg_quote:1;
unsigned int decorate:1;
unsigned int is_stdout:1;
int fd;
int line;
int child_pid;
const char *function;
struct zlog_stream_buffer buf;
size_t len;
size_t buf_init_size;
size_t prefix_len;
char *msg_prefix;
size_t msg_prefix_len;
char *msg_suffix;
size_t msg_suffix_len;
char *msg_final_suffix;
size_t msg_final_suffix_len;
};
void zlog_stream_init(struct zlog_stream *stream, int flags);
void zlog_stream_init_ex(struct zlog_stream *stream, int flags, int fd);
void zlog_stream_set_decorating(struct zlog_stream *stream, zlog_bool decorate);
void zlog_stream_set_wrapping(struct zlog_stream *stream, zlog_bool wrap);
void zlog_stream_set_is_stdout(struct zlog_stream *stream, zlog_bool is_stdout);
void zlog_stream_set_child_pid(struct zlog_stream *stream, int child_pid);
void zlog_stream_set_msg_quoting(struct zlog_stream *stream, zlog_bool quote);
zlog_bool zlog_stream_set_msg_prefix(struct zlog_stream *stream, const char *fmt, ...)
__attribute__ ((format(printf,2,3)));
zlog_bool zlog_stream_set_msg_suffix(
struct zlog_stream *stream, const char *suffix, const char *final_suffix);
#define zlog_stream_prefix(stream) \
zlog_stream_prefix_ex(stream, __func__, __LINE__)
ssize_t zlog_stream_prefix_ex(struct zlog_stream *stream, const char *function, int line);
ssize_t zlog_stream_format(struct zlog_stream *stream, const char *fmt, ...)
__attribute__ ((format(printf,2,3)));
ssize_t zlog_stream_vformat(struct zlog_stream *stream, const char *fmt, va_list args);
ssize_t zlog_stream_str(struct zlog_stream *stream, const char *str, size_t str_len);
zlog_bool zlog_stream_finish(struct zlog_stream *stream);
void zlog_stream_destroy(struct zlog_stream *stream);
zlog_bool zlog_stream_close(struct zlog_stream *stream);
/* default log limit */
#define ZLOG_DEFAULT_LIMIT 1024
/* minimum log limit */
#define ZLOG_MIN_LIMIT 512
/* default log buffering */
#define ZLOG_DEFAULT_BUFFERING 1
#endif
| 3,666 | 28.813008 | 90 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/events/devpoll.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Jerome Loyet <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "../fpm_config.h"
#include "../fpm_events.h"
#include "../fpm.h"
#include "../zlog.h"
#ifdef HAVE_DEVPOLL
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/devpoll.h>
#include <errno.h>
static int fpm_event_devpoll_init(int max);
static int fpm_event_devpoll_clean(void);
static int fpm_event_devpoll_wait(struct fpm_event_queue_s *queue, unsigned long int timeout);
static int fpm_event_devpoll_add(struct fpm_event_s *ev);
static int fpm_event_devpoll_remove(struct fpm_event_s *ev);
static struct fpm_event_module_s devpoll_module = {
.name = "/dev/poll",
.support_edge_trigger = 0,
.init = fpm_event_devpoll_init,
.clean = fpm_event_devpoll_clean,
.wait = fpm_event_devpoll_wait,
.add = fpm_event_devpoll_add,
.remove = fpm_event_devpoll_remove,
};
int dpfd = -1;
static struct pollfd *pollfds = NULL;
static struct pollfd *active_pollfds = NULL;
static int npollfds = 0;
#endif /* HAVE_DEVPOLL */
struct fpm_event_module_s *fpm_event_devpoll_module(void)
{
#ifdef HAVE_DEVPOLL
return &devpoll_module;
#else
return NULL;
#endif /* HAVE_DEVPOLL */
}
#ifdef HAVE_DEVPOLL
/*
* Init module
*/
static int fpm_event_devpoll_init(int max) /* {{{ */
{
int i;
/* open /dev/poll for future usages */
dpfd = open("/dev/poll", O_RDWR);
if (dpfd < 0) {
zlog(ZLOG_ERROR, "Unable to open /dev/poll");
return -1;
}
if (max < 1) {
return 0;
}
/* alloc and clear pollfds */
pollfds = malloc(sizeof(struct pollfd) * max);
if (!pollfds) {
zlog(ZLOG_ERROR, "poll: unable to allocate %d events", max);
return -1;
}
memset(pollfds, 0, sizeof(struct pollfd) * max);
/* set all fd to -1 in order to ensure it's not set */
for (i = 0; i < max; i++) {
pollfds[i].fd = -1;
}
/* alloc and clear active_pollfds */
active_pollfds = malloc(sizeof(struct pollfd) * max);
if (!active_pollfds) {
free(pollfds);
zlog(ZLOG_ERROR, "poll: unable to allocate %d events", max);
return -1;
}
memset(active_pollfds, 0, sizeof(struct pollfd) * max);
/* save max */
npollfds = max;
return 0;
}
/* }}} */
/*
* Clean the module
*/
static int fpm_event_devpoll_clean(void)
{
/* close /dev/poll if open */
if (dpfd > -1) {
close(dpfd);
dpfd = -1;
}
/* free pollfds */
if (pollfds) {
free(pollfds);
pollfds = NULL;
}
/* free active_pollfds */
if (active_pollfds) {
free(active_pollfds);
active_pollfds = NULL;
}
npollfds = 0;
return 0;
}
/*
* wait for events or timeout
*/
static int fpm_event_devpoll_wait(struct fpm_event_queue_s *queue, unsigned long int timeout) /* {{{ */
{
int ret, i;
struct fpm_event_queue_s *q;
struct dvpoll dopoll;
/* setup /dev/poll */
dopoll.dp_fds = active_pollfds;
dopoll.dp_nfds = npollfds;
dopoll.dp_timeout = (int)timeout;
/* wait for incoming event or timeout */
ret = ioctl(dpfd, DP_POLL, &dopoll);
if (ret < 0) {
/* trigger error unless signal interrupt */
if (errno != EINTR) {
zlog(ZLOG_WARNING, "/dev/poll: ioctl() returns %d", errno);
return -1;
}
}
/* iterate through triggered events */
for (i = 0; i < ret; i++) {
/* find the corresponding event */
q = queue;
while (q) {
/* found */
if (q->ev && q->ev->fd == active_pollfds[i].fd) {
/* fire the event */
fpm_event_fire(q->ev);
/* sanity check */
if (fpm_globals.parent_pid != getpid()) {
return -2;
}
break; /* next triggered event */
}
q = q->next; /* iterate */
}
}
return ret;
}
/* }}} */
/*
* Add a FD from the fd set
*/
static int fpm_event_devpoll_add(struct fpm_event_s *ev) /* {{{ */
{
struct pollfd pollfd;
/* fill pollfd with event information */
pollfd.fd = ev->fd;
pollfd.events = POLLIN;
pollfd.revents = 0;
/* add the event to the internal queue */
if (write(dpfd, &pollfd, sizeof(struct pollfd)) != sizeof(struct pollfd)) {
zlog(ZLOG_ERROR, "/dev/poll: Unable to add the event in the internal queue");
return -1;
}
/* mark the event as registered */
ev->index = ev->fd;
return 0;
}
/* }}} */
/*
* Remove a FD from the fd set
*/
static int fpm_event_devpoll_remove(struct fpm_event_s *ev) /* {{{ */
{
struct pollfd pollfd;
/* fill pollfd with the same information as fpm_event_devpoll_add */
pollfd.fd = ev->fd;
pollfd.events = POLLIN | POLLREMOVE;
pollfd.revents = 0;
/* add the event to the internal queue */
if (write(dpfd, &pollfd, sizeof(struct pollfd)) != sizeof(struct pollfd)) {
zlog(ZLOG_ERROR, "/dev/poll: Unable to remove the event in the internal queue");
return -1;
}
/* mark the event as registered */
ev->index = -1;
return 0;
}
/* }}} */
#endif /* HAVE_DEVPOLL */
| 5,630 | 22.17284 | 103 |
c
|
php-src
|
php-src-master/sapi/fpm/fpm/events/devpoll.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Jerome Loyet <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef FPM_EVENTS_DEVPOLL_H
#define FPM_EVENTS_DEVPOLL_H
#include "../fpm_config.h"
#include "../fpm_events.h"
struct fpm_event_module_s *fpm_event_devpoll_module(void);
#endif /* FPM_EVENTS_DEVPOLL_H */
| 1,203 | 45.307692 | 75 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/events/epoll.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Jerome Loyet <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "../fpm_config.h"
#include "../fpm_events.h"
#include "../fpm.h"
#include "../zlog.h"
#ifdef HAVE_EPOLL
#include <sys/epoll.h>
#include <errno.h>
static int fpm_event_epoll_init(int max);
static int fpm_event_epoll_clean(void);
static int fpm_event_epoll_wait(struct fpm_event_queue_s *queue, unsigned long int timeout);
static int fpm_event_epoll_add(struct fpm_event_s *ev);
static int fpm_event_epoll_remove(struct fpm_event_s *ev);
static struct fpm_event_module_s epoll_module = {
.name = "epoll",
.support_edge_trigger = 1,
.init = fpm_event_epoll_init,
.clean = fpm_event_epoll_clean,
.wait = fpm_event_epoll_wait,
.add = fpm_event_epoll_add,
.remove = fpm_event_epoll_remove,
};
static struct epoll_event *epollfds = NULL;
static int nepollfds = 0;
static int epollfd = -1;
#endif /* HAVE_EPOLL */
struct fpm_event_module_s *fpm_event_epoll_module(void)
{
#ifdef HAVE_EPOLL
return &epoll_module;
#else
return NULL;
#endif /* HAVE_EPOLL */
}
#ifdef HAVE_EPOLL
/*
* Init the module
*/
static int fpm_event_epoll_init(int max) /* {{{ */
{
if (max < 1) {
return 0;
}
/* init epoll */
epollfd = epoll_create(max + 1);
if (epollfd < 0) {
zlog(ZLOG_ERROR, "epoll: unable to initialize");
return -1;
}
/* allocate fds */
epollfds = malloc(sizeof(struct epoll_event) * max);
if (!epollfds) {
zlog(ZLOG_ERROR, "epoll: unable to allocate %d events", max);
return -1;
}
memset(epollfds, 0, sizeof(struct epoll_event) * max);
/* save max */
nepollfds = max;
return 0;
}
/* }}} */
/*
* Clean the module
*/
static int fpm_event_epoll_clean(void)
{
/* free epollfds */
if (epollfds) {
free(epollfds);
epollfds = NULL;
}
if (epollfd != -1) {
close(epollfd);
epollfd = -1;
}
nepollfds = 0;
return 0;
}
/*
* wait for events or timeout
*/
static int fpm_event_epoll_wait(struct fpm_event_queue_s *queue, unsigned long int timeout) /* {{{ */
{
int ret, i;
/* ensure we have a clean epoolfds before calling epoll_wait() */
memset(epollfds, 0, sizeof(struct epoll_event) * nepollfds);
/* wait for incoming event or timeout */
ret = epoll_wait(epollfd, epollfds, nepollfds, timeout);
if (ret == -1) {
/* trigger error unless signal interrupt */
if (errno != EINTR) {
zlog(ZLOG_WARNING, "epoll_wait() returns %d", errno);
return -1;
}
}
/* events have been triggered, let's fire them */
for (i = 0; i < ret; i++) {
/* do we have a valid ev ptr ? */
if (!epollfds[i].data.ptr) {
continue;
}
/* fire the event */
fpm_event_fire((struct fpm_event_s *)epollfds[i].data.ptr);
/* sanity check */
if (fpm_globals.parent_pid != getpid()) {
return -2;
}
}
return ret;
}
/* }}} */
/*
* Add a FD to the fd set
*/
static int fpm_event_epoll_add(struct fpm_event_s *ev) /* {{{ */
{
struct epoll_event e;
/* fill epoll struct */
#if SIZEOF_SIZE_T == 4
/* Completely initialize event data to prevent valgrind reports */
e.data.u64 = 0;
#endif
e.events = EPOLLIN;
e.data.fd = ev->fd;
e.data.ptr = (void *)ev;
if (ev->flags & FPM_EV_EDGE) {
e.events = e.events | EPOLLET;
}
/* add the event to epoll internal queue */
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ev->fd, &e) == -1) {
zlog(ZLOG_ERROR, "epoll: unable to add fd %d", ev->fd);
return -1;
}
/* mark the event as registered */
ev->index = ev->fd;
return 0;
}
/* }}} */
/*
* Remove a FD from the fd set
*/
static int fpm_event_epoll_remove(struct fpm_event_s *ev) /* {{{ */
{
struct epoll_event e;
/* fill epoll struct the same way we did in fpm_event_epoll_add() */
e.events = EPOLLIN;
e.data.fd = ev->fd;
e.data.ptr = (void *)ev;
if (ev->flags & FPM_EV_EDGE) {
e.events = e.events | EPOLLET;
}
/* remove the event from epoll internal queue */
if (epoll_ctl(epollfd, EPOLL_CTL_DEL, ev->fd, &e) == -1) {
zlog(ZLOG_ERROR, "epoll: unable to remove fd %d", ev->fd);
return -1;
}
/* mark the event as not registered */
ev->index = -1;
return 0;
}
/* }}} */
#endif /* HAVE_EPOLL */
| 4,979 | 22.271028 | 101 |
c
|
php-src
|
php-src-master/sapi/fpm/fpm/events/epoll.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Jerome Loyet <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef FPM_EVENTS_EPOLL_H
#define FPM_EVENTS_EPOLL_H
#include "../fpm_config.h"
#include "../fpm_events.h"
struct fpm_event_module_s *fpm_event_epoll_module(void);
#endif /* FPM_EVENTS_EPOLL_H */
| 1,195 | 45 | 75 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/events/kqueue.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Jerome Loyet <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "../fpm_config.h"
#include "../fpm_events.h"
#include "../fpm.h"
#include "../zlog.h"
#ifdef HAVE_KQUEUE
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include <errno.h>
static int fpm_event_kqueue_init(int max);
static int fpm_event_kqueue_clean(void);
static int fpm_event_kqueue_wait(struct fpm_event_queue_s *queue, unsigned long int timeout);
static int fpm_event_kqueue_add(struct fpm_event_s *ev);
static int fpm_event_kqueue_remove(struct fpm_event_s *ev);
static struct fpm_event_module_s kqueue_module = {
.name = "kqueue",
.support_edge_trigger = 1,
.init = fpm_event_kqueue_init,
.clean = fpm_event_kqueue_clean,
.wait = fpm_event_kqueue_wait,
.add = fpm_event_kqueue_add,
.remove = fpm_event_kqueue_remove,
};
static struct kevent *kevents = NULL;
static int nkevents = 0;
static int kfd = 0;
#endif /* HAVE_KQUEUE */
/*
* Return the module configuration
*/
struct fpm_event_module_s *fpm_event_kqueue_module(void) /* {{{ */
{
#ifdef HAVE_KQUEUE
return &kqueue_module;
#else
return NULL;
#endif /* HAVE_KQUEUE */
}
/* }}} */
#ifdef HAVE_KQUEUE
/*
* init kqueue and stuff
*/
static int fpm_event_kqueue_init(int max) /* {{{ */
{
if (max < 1) {
return 0;
}
kfd = kqueue();
if (kfd < 0) {
zlog(ZLOG_ERROR, "kqueue: unable to initialize");
return -1;
}
kevents = malloc(sizeof(struct kevent) * max);
if (!kevents) {
zlog(ZLOG_ERROR, "epoll: unable to allocate %d events", max);
return -1;
}
memset(kevents, 0, sizeof(struct kevent) * max);
nkevents = max;
return 0;
}
/* }}} */
/*
* release kqueue stuff
*/
static int fpm_event_kqueue_clean() /* {{{ */
{
if (kevents) {
free(kevents);
kevents = NULL;
}
nkevents = 0;
return 0;
}
/* }}} */
/*
* wait for events or timeout
*/
static int fpm_event_kqueue_wait(struct fpm_event_queue_s *queue, unsigned long int timeout) /* {{{ */
{
struct timespec t;
int ret, i;
/* ensure we have a clean kevents before calling kevent() */
memset(kevents, 0, sizeof(struct kevent) * nkevents);
/* convert ms to timespec struct */
t.tv_sec = timeout / 1000;
t.tv_nsec = (timeout % 1000) * 1000 * 1000;
/* wait for incoming event or timeout */
ret = kevent(kfd, NULL, 0, kevents, nkevents, &t);
if (ret == -1) {
/* trigger error unless signal interrupt */
if (errno != EINTR) {
zlog(ZLOG_WARNING, "epoll_wait() returns %d", errno);
return -1;
}
}
/* fire triggered events */
for (i = 0; i < ret; i++) {
if (kevents[i].udata) {
struct fpm_event_s *ev = (struct fpm_event_s *)kevents[i].udata;
fpm_event_fire(ev);
/* sanity check */
if (fpm_globals.parent_pid != getpid()) {
return -2;
}
}
}
return ret;
}
/* }}} */
/*
* Add a FD to to kevent queue
*/
static int fpm_event_kqueue_add(struct fpm_event_s *ev) /* {{{ */
{
struct kevent k;
int flags = EV_ADD;
if (ev->flags & FPM_EV_EDGE) {
flags = flags | EV_CLEAR;
}
EV_SET(&k, ev->fd, EVFILT_READ, flags, 0, 0, (void *)ev);
if (kevent(kfd, &k, 1, NULL, 0, NULL) < 0) {
zlog(ZLOG_ERROR, "kevent: unable to add event");
return -1;
}
/* mark the event as registered */
ev->index = ev->fd;
return 0;
}
/* }}} */
/*
* Remove a FD from the kevent queue
*/
static int fpm_event_kqueue_remove(struct fpm_event_s *ev) /* {{{ */
{
struct kevent k;
int flags = EV_DELETE;
if (ev->flags & FPM_EV_EDGE) {
flags = flags | EV_CLEAR;
}
EV_SET(&k, ev->fd, EVFILT_READ, flags, 0, 0, (void *)ev);
if (kevent(kfd, &k, 1, NULL, 0, NULL) < 0) {
zlog(ZLOG_ERROR, "kevent: unable to delete event");
return -1;
}
/* mark the event as not registered */
ev->index = -1;
return 0;
}
/* }}} */
#endif /* HAVE_KQUEUE */
| 4,672 | 21.795122 | 102 |
c
|
php-src
|
php-src-master/sapi/fpm/fpm/events/kqueue.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Jerome Loyet <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef FPM_EVENTS_KQUEUE_H
#define FPM_EVENTS_KQUEUE_H
#include "../fpm_config.h"
#include "../fpm_events.h"
struct fpm_event_module_s *fpm_event_kqueue_module(void);
#endif /* FPM_EVENTS_KQUEUE_H */
| 1,199 | 45.153846 | 75 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/events/poll.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Jerome Loyet <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "../fpm_config.h"
#include "../fpm_events.h"
#include "../fpm.h"
#include "../zlog.h"
#ifdef HAVE_POLL
#include <poll.h>
#include <errno.h>
#include <string.h>
static int fpm_event_poll_init(int max);
static int fpm_event_poll_clean(void);
static int fpm_event_poll_wait(struct fpm_event_queue_s *queue, unsigned long int timeout);
static int fpm_event_poll_add(struct fpm_event_s *ev);
static int fpm_event_poll_remove(struct fpm_event_s *ev);
static struct fpm_event_module_s poll_module = {
.name = "poll",
.support_edge_trigger = 0,
.init = fpm_event_poll_init,
.clean = fpm_event_poll_clean,
.wait = fpm_event_poll_wait,
.add = fpm_event_poll_add,
.remove = fpm_event_poll_remove,
};
static struct pollfd *pollfds = NULL;
static struct pollfd *active_pollfds = NULL;
static int npollfds = 0;
static int next_free_slot = 0;
#endif /* HAVE_POLL */
/*
* return the module configuration
*/
struct fpm_event_module_s *fpm_event_poll_module(void)
{
#ifdef HAVE_POLL
return &poll_module;
#else
return NULL;
#endif /* HAVE_POLL */
}
#ifdef HAVE_POLL
/*
* Init the module
*/
static int fpm_event_poll_init(int max)
{
int i;
if (max < 1) {
return 0;
}
/* alloc and clear pollfds */
pollfds = malloc(sizeof(struct pollfd) * max);
if (!pollfds) {
zlog(ZLOG_ERROR, "poll: unable to allocate %d events", max);
return -1;
}
memset(pollfds, 0, sizeof(struct pollfd) * max);
/* set all fd to -1 in order to ensure it's not set */
for (i = 0; i < max; i++) {
pollfds[i].fd = -1;
}
/* alloc and clear active_pollfds */
active_pollfds = malloc(sizeof(struct pollfd) * max);
if (!active_pollfds) {
free(pollfds);
zlog(ZLOG_ERROR, "poll: unable to allocate %d events", max);
return -1;
}
memset(active_pollfds, 0, sizeof(struct pollfd) * max);
/* save max */
npollfds = max;
return 0;
}
/*
* Clean the module
*/
static int fpm_event_poll_clean(void)
{
/* free pollfds */
if (pollfds) {
free(pollfds);
pollfds = NULL;
}
/* free active_pollfds */
if (active_pollfds) {
free(active_pollfds);
active_pollfds = NULL;
}
npollfds = 0;
return 0;
}
/*
* wait for events or timeout
*/
static int fpm_event_poll_wait(struct fpm_event_queue_s *queue, unsigned long int timeout) /* {{{ */
{
int ret;
struct fpm_event_queue_s *q;
if (npollfds > 0) {
/* copy pollfds because poll() alters it */
memcpy(active_pollfds, pollfds, sizeof(struct pollfd) * npollfds);
}
/* wait for incoming event or timeout */
ret = poll(active_pollfds, npollfds, timeout);
if (ret == -1) {
/* trigger error unless signal interrupt */
if (errno != EINTR) {
zlog(ZLOG_WARNING, "poll() returns %d", errno);
return -1;
}
}
/* events have been triggered */
if (ret > 0) {
/* trigger POLLIN events */
q = queue;
while (q) {
/* ensure ev->index is valid */
if (q->ev && q->ev->index >= 0 && q->ev->index < npollfds && q->ev->fd == active_pollfds[q->ev->index].fd) {
/* has the event has been triggered ? */
if (active_pollfds[q->ev->index].revents & POLLIN) {
/* fire the event */
fpm_event_fire(q->ev);
/* sanity check */
if (fpm_globals.parent_pid != getpid()) {
return -2;
}
}
}
q = q->next; /* iterate */
}
}
return ret;
}
/* }}} */
/*
* Add a FD to the fd set
*/
static int fpm_event_poll_add(struct fpm_event_s *ev) /* {{{ */
{
int i;
/* do we have a direct free slot */
if (pollfds[next_free_slot].fd == -1) {
/* register the event */
pollfds[next_free_slot].fd = ev->fd;
pollfds[next_free_slot].events = POLLIN;
/* remember the event place in the fd list and suppose next slot is free */
ev->index = next_free_slot++;
if (next_free_slot >= npollfds) {
next_free_slot = 0;
}
return 0;
}
/* let's search */
for (i = 0; i < npollfds; i++) {
if (pollfds[i].fd != -1) {
/* not free */
continue;
}
/* register the event */
pollfds[i].fd = ev->fd;
pollfds[i].events = POLLIN;
/* remember the event place in the fd list and suppose next slot is free */
ev->index = next_free_slot++;
if (next_free_slot >= npollfds) {
next_free_slot = 0;
}
return 0;
}
zlog(ZLOG_ERROR, "poll: not enough space to add event (fd=%d)", ev->fd);
return -1;
}
/* }}} */
/*
* Remove a FD from the fd set
*/
static int fpm_event_poll_remove(struct fpm_event_s *ev) /* {{{ */
{
int i;
/* do we have a direct access */
if (ev->index >= 0 && ev->index < npollfds && pollfds[ev->index].fd == ev->fd) {
/* remember this slot as free */
next_free_slot = ev->index;
/* clear event in pollfds */
pollfds[ev->index].fd = -1;
pollfds[ev->index].events = 0;
/* mark the event as not registered */
ev->index = -1;
return 0;
}
/* let's search */
for (i = 0; i < npollfds; i++) {
if (pollfds[i].fd != ev->fd) {
/* not found */
continue;
}
/* remember this slot as free */
next_free_slot = i;
/* clear event in pollfds */
pollfds[i].fd = -1;
pollfds[i].events = 0;
/* mark the event as not registered */
ev->index = -1;
return 0;
}
zlog(ZLOG_ERROR, "poll: unable to remove event: not found (fd=%d, index=%d)", ev->fd, ev->index);
return -1;
}
/* }}} */
#endif /* HAVE_POLL */
| 6,196 | 21.951852 | 111 |
c
|
php-src
|
php-src-master/sapi/fpm/fpm/events/poll.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Jerome Loyet <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef FPM_EVENTS_POLL_H
#define FPM_EVENTS_POLL_H
#include "../fpm_config.h"
#include "../fpm_events.h"
struct fpm_event_module_s *fpm_event_poll_module(void);
#endif /* FPM_EVENTS_POLL_H */
| 1,191 | 44.846154 | 75 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/events/port.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Jerome Loyet <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "../fpm_config.h"
#include "../fpm_events.h"
#include "../fpm.h"
#include "../zlog.h"
#ifdef HAVE_PORT
#include <port.h>
#include <poll.h>
#include <errno.h>
static int fpm_event_port_init(int max);
static int fpm_event_port_clean(void);
static int fpm_event_port_wait(struct fpm_event_queue_s *queue, unsigned long int timeout);
static int fpm_event_port_add(struct fpm_event_s *ev);
static int fpm_event_port_remove(struct fpm_event_s *ev);
static struct fpm_event_module_s port_module = {
.name = "port",
.support_edge_trigger = 0,
.init = fpm_event_port_init,
.clean = fpm_event_port_clean,
.wait = fpm_event_port_wait,
.add = fpm_event_port_add,
.remove = fpm_event_port_remove,
};
port_event_t *events = NULL;
int nevents = 0;
static int pfd = -1;
#endif /* HAVE_PORT */
struct fpm_event_module_s *fpm_event_port_module(void) /* {{{ */
{
#ifdef HAVE_PORT
return &port_module;
#else
return NULL;
#endif /* HAVE_PORT */
}
/* }}} */
#ifdef HAVE_PORT
/*
* Init the module
*/
static int fpm_event_port_init(int max) /* {{{ */
{
/* open port */
pfd = port_create();
if (pfd < 0) {
zlog(ZLOG_ERROR, "port: unable to initialize port_create()");
return -1;
}
if (max < 1) {
return 0;
}
/* alloc and clear active_pollfds */
events = malloc(sizeof(port_event_t) * max);
if (!events) {
zlog(ZLOG_ERROR, "port: Unable to allocate %d events", max);
return -1;
}
nevents = max;
return 0;
}
/* }}} */
/*
* Clean the module
*/
static int fpm_event_port_clean(void)
{
if (pfd > -1) {
close(pfd);
pfd = -1;
}
if (events) {
free(events);
events = NULL;
}
nevents = 0;
return 0;
}
/*
* wait for events or timeout
*/
static int fpm_event_port_wait(struct fpm_event_queue_s *queue, unsigned long int timeout) /* {{{ */
{
int ret;
unsigned int i, nget;
timespec_t t;
/* convert timeout into timespec_t */
t.tv_sec = (int)(timeout / 1000);
t.tv_nsec = (timeout % 1000) * 1000 * 1000;
/* wait for incoming event or timeout. We want at least one event or timeout */
nget = 1;
events[0].portev_user = (void *)-1; /* so we can double check that an event was returned */
ret = port_getn(pfd, events, nevents, &nget, &t);
if (ret < 0) {
/* trigger error unless signal interrupt or timeout */
if (errno != EINTR && errno != ETIME) {
zlog(ZLOG_WARNING, "poll() returns %d", errno);
return -1;
} else if (nget > 0 && events[0].portev_user == (void *)-1) {
/* This confusing API can return an event at the same time
* that it reports EINTR or ETIME. If that occurs, just
* report the event. With EINTR, nget can be > 0 without
* any event, so check that portev_user was filled in.
*
* See discussion thread
* http://marc.info/?l=opensolaris-networking-discuss&m=125071205204540
*/
nget = 0;
}
}
for (i = 0; i < nget; i++) {
struct fpm_event_s *ev;
/* do we have a ptr to the event ? */
if (!events[i].portev_user) {
continue;
}
ev = (struct fpm_event_s *)events[i].portev_user;
/* re-associate for next event */
fpm_event_port_add(ev);
/* fire the event */
fpm_event_fire(ev);
/* sanity check */
if (fpm_globals.parent_pid != getpid()) {
return -2;
}
}
return nget;
}
/* }}} */
/*
* Add a FD to the fd set
*/
static int fpm_event_port_add(struct fpm_event_s *ev) /* {{{ */
{
/* add the event to port */
if (port_associate(pfd, PORT_SOURCE_FD, ev->fd, POLLIN, (void *)ev) < 0) {
zlog(ZLOG_ERROR, "port: unable to add the event");
return -1;
}
return 0;
}
/* }}} */
/*
* Remove a FD from the fd set
*/
static int fpm_event_port_remove(struct fpm_event_s *ev) /* {{{ */
{
/* remove the event from port */
if (port_dissociate(pfd, PORT_SOURCE_FD, ev->fd) < 0) {
zlog(ZLOG_ERROR, "port: unable to add the event");
return -1;
}
return 0;
}
/* }}} */
#endif /* HAVE_PORT */
| 4,839 | 23.2 | 100 |
c
|
php-src
|
php-src-master/sapi/fpm/fpm/events/port.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Jerome Loyet <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef FPM_EVENTS_PORT_H
#define FPM_EVENTS_PORT_H
#include "../fpm_config.h"
#include "../fpm_events.h"
struct fpm_event_module_s *fpm_event_port_module(void);
#endif /* FPM_EVENTS_PORT_H */
| 1,191 | 44.846154 | 75 |
h
|
php-src
|
php-src-master/sapi/fpm/fpm/events/select.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Jerome Loyet <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef FPM_EVENTS_SELECT_H
#define FPM_EVENTS_SELECT_H
#include "../fpm_config.h"
#include "../fpm_events.h"
struct fpm_event_module_s *fpm_event_select_module(void);
#endif /* FPM_EVENTS_SELECT_H */
| 1,199 | 45.153846 | 75 |
h
|
php-src
|
php-src-master/sapi/fuzzer/fuzzer-execute-common.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Nikita Popov <[email protected]> |
+----------------------------------------------------------------------+
*/
#include <main/php.h>
#if defined(__FreeBSD__)
# include <sys/sysctl.h>
#endif
#include "fuzzer.h"
#include "fuzzer-sapi.h"
#include "zend_exceptions.h"
#define FILE_NAME "/tmp/fuzzer.php"
#define MAX_STEPS 1000
#define MAX_SIZE (8 * 1024)
static uint32_t steps_left;
static bool bailed_out = false;
/* Because the fuzzer is always compiled with clang,
* we can assume that we don't use global registers / hybrid VM. */
typedef int (ZEND_FASTCALL *opcode_handler_t)(zend_execute_data *);
static zend_always_inline void fuzzer_bailout(void) {
bailed_out = true;
zend_bailout();
}
static zend_always_inline void fuzzer_step(void) {
if (--steps_left == 0) {
/* Reset steps before bailing out, so code running after bailout (e.g. in
* destructors) will get another MAX_STEPS, rather than UINT32_MAX steps. */
steps_left = MAX_STEPS;
fuzzer_bailout();
}
}
static void (*orig_execute_ex)(zend_execute_data *execute_data);
static void fuzzer_execute_ex(zend_execute_data *execute_data) {
while (1) {
int ret;
fuzzer_step();
if ((ret = ((opcode_handler_t) EX(opline)->handler)(execute_data)) != 0) {
if (ret > 0) {
execute_data = EG(current_execute_data);
} else {
return;
}
}
}
}
static zend_op_array *(*orig_compile_string)(
zend_string *source_string, const char *filename, zend_compile_position position);
static zend_op_array *fuzzer_compile_string(
zend_string *str, const char *filename, zend_compile_position position) {
if (ZSTR_LEN(str) > MAX_SIZE) {
/* Avoid compiling huge inputs via eval(). */
fuzzer_bailout();
}
return orig_compile_string(str, filename, position);
}
static void (*orig_execute_internal)(zend_execute_data *execute_data, zval *return_value);
static void fuzzer_execute_internal(zend_execute_data *execute_data, zval *return_value) {
fuzzer_step();
uint32_t num_args = ZEND_CALL_NUM_ARGS(execute_data);
for (uint32_t i = 0; i < num_args; i++) {
/* Some internal functions like preg_replace() may be slow on large inputs.
* Limit the maximum size of string inputs. */
zval *arg = ZEND_CALL_VAR_NUM(execute_data, i);
if (Z_TYPE_P(arg) == IS_STRING && Z_STRLEN_P(arg) > MAX_SIZE) {
fuzzer_bailout();
}
}
orig_execute_internal(execute_data, return_value);
}
static void fuzzer_init_php_for_execute(const char *extra_ini) {
/* Compilation will often trigger fatal errors.
* Use tracked allocation mode to avoid leaks in that case. */
putenv("USE_TRACKED_ALLOC=1");
/* Just like other SAPIs, ignore SIGPIPEs. */
signal(SIGPIPE, SIG_IGN);
fuzzer_init_php(extra_ini);
orig_execute_ex = zend_execute_ex;
zend_execute_ex = fuzzer_execute_ex;
orig_execute_internal = zend_execute_internal ? zend_execute_internal : execute_internal;
zend_execute_internal = fuzzer_execute_internal;
orig_compile_string = zend_compile_string;
zend_compile_string = fuzzer_compile_string;
}
ZEND_ATTRIBUTE_UNUSED static void create_file(void) {
/* For opcache_invalidate() to work, the dummy file name used for fuzzing needs to
* actually exist. */
FILE *f = fopen(FILE_NAME, "w");
fclose(f);
}
ZEND_ATTRIBUTE_UNUSED static void opcache_invalidate(void) {
steps_left = MAX_STEPS;
zend_exception_save();
zval retval, func, args[2];
ZVAL_STRING(&func, "opcache_invalidate");
ZVAL_STRING(&args[0], FILE_NAME);
ZVAL_TRUE(&args[1]);
call_user_function(CG(function_table), NULL, &func, &retval, 2, args);
ZEND_ASSERT(Z_TYPE(retval) == IS_TRUE);
zval_ptr_dtor(&args[0]);
zval_ptr_dtor(&retval);
zval_ptr_dtor(&func);
zend_exception_restore();
}
ZEND_ATTRIBUTE_UNUSED char *get_opcache_path(void) {
/* Try relative to cwd. */
char *p = realpath("modules/opcache.so", NULL);
if (p) {
return p;
}
/* Try relative to binary location. */
char path[MAXPATHLEN];
#if defined(__FreeBSD__)
size_t pathlen = sizeof(path);
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
if (sysctl(mib, 4, path, &pathlen, NULL, 0) < 0) {
#else
if (readlink("/proc/self/exe", path, sizeof(path)) < 0) {
#endif
ZEND_ASSERT(0 && "Failed to get binary path");
return NULL;
}
/* Get basename. */
char *last_sep = strrchr(path, '/');
if (last_sep) {
*last_sep = '\0';
}
strlcat(path, "/modules/opcache.so", sizeof(path));
return realpath(path, NULL);
}
| 5,264 | 30.526946 | 90 |
h
|
php-src
|
php-src-master/sapi/fuzzer/fuzzer-execute.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Nikita Popov <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "fuzzer-execute-common.h"
int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
if (Size > MAX_SIZE) {
/* Large inputs have a large impact on fuzzer performance,
* but are unlikely to be necessary to reach new codepaths. */
return 0;
}
steps_left = MAX_STEPS;
fuzzer_do_request_from_buffer(
FILE_NAME, (const char *) Data, Size, /* execute */ 1, /* before_shutdown */ NULL);
return 0;
}
int LLVMFuzzerInitialize(int *argc, char ***argv) {
fuzzer_init_php_for_execute(NULL);
return 0;
}
| 1,520 | 40.108108 | 85 |
c
|
php-src
|
php-src-master/sapi/fuzzer/fuzzer-exif.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Stanislav Malyshev <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "fuzzer.h"
#include "Zend/zend.h"
#include "main/php_config.h"
#include "main/php_main.h"
#include "ext/standard/php_var.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "fuzzer-sapi.h"
int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
#if HAVE_EXIF
php_stream *stream;
zval stream_zv;
if (Size > 256 * 1024) {
/* Large inputs have a large impact on fuzzer performance,
* but are unlikely to be necessary to reach new codepaths. */
return 0;
}
if (fuzzer_request_startup() == FAILURE) {
return 0;
}
stream = php_stream_memory_create(TEMP_STREAM_DEFAULT);
php_stream_write(stream, (const char *) Data, Size);
php_stream_to_zval(stream, &stream_zv);
fuzzer_call_php_func_zval("exif_read_data", 1, &stream_zv);
zval_ptr_dtor(&stream_zv);
/* cleanup */
php_request_shutdown(NULL);
return 0;
#else
fprintf(stderr, "\n\nERROR:\nPHP built without EXIF, recompile with --enable-exif to use this fuzzer\n");
exit(1);
#endif
}
int LLVMFuzzerInitialize(int *argc, char ***argv) {
fuzzer_init_php(NULL);
/* fuzzer_shutdown_php(); */
return 0;
}
| 2,179 | 28.863014 | 106 |
c
|
php-src
|
php-src-master/sapi/fuzzer/fuzzer-function-jit.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Nikita Popov <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "fuzzer-execute-common.h"
int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
if (Size > MAX_SIZE) {
/* Large inputs have a large impact on fuzzer performance,
* but are unlikely to be necessary to reach new codepaths. */
return 0;
}
zend_string *jit_option = ZSTR_INIT_LITERAL("opcache.jit", 1);
/* First run without JIT to determine whether we bail out. We should not run JITed code if
* we bail out here, as the JIT code may loop infinitely. */
steps_left = MAX_STEPS;
bailed_out = false;
zend_alter_ini_entry_chars(
jit_option, "off", sizeof("off")-1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
fuzzer_do_request_from_buffer(
FILE_NAME, (const char *) Data, Size, /* execute */ 1, opcache_invalidate);
if (!bailed_out) {
steps_left = MAX_STEPS;
zend_alter_ini_entry_chars(jit_option,
"function", sizeof("function")-1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
zend_execute_ex = orig_execute_ex;
fuzzer_do_request_from_buffer(
FILE_NAME, (const char *) Data, Size, /* execute */ 1, opcache_invalidate);
zend_execute_ex = fuzzer_execute_ex;
}
zend_string_release(jit_option);
return 0;
}
int LLVMFuzzerInitialize(int *argc, char ***argv) {
char *opcache_path = get_opcache_path();
assert(opcache_path && "Failed to determine opcache path");
char ini_buf[512];
snprintf(ini_buf, sizeof(ini_buf),
"zend_extension=%s\n"
"opcache.validate_timestamps=0\n"
"opcache.file_update_protection=0\n"
"opcache.jit_buffer_size=256M",
opcache_path);
free(opcache_path);
create_file();
fuzzer_init_php_for_execute(ini_buf);
return 0;
}
| 2,597 | 36.652174 | 91 |
c
|
php-src
|
php-src-master/sapi/fuzzer/fuzzer-json.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Johannes Schlüter <[email protected]> |
| Stanislav Malyshev <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "fuzzer.h"
#include "Zend/zend.h"
#include "main/php_config.h"
#include "main/php_main.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include "fuzzer-sapi.h"
#include "ext/json/php_json_parser.h"
int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
char *data = malloc(Size+1);
memcpy(data, Data, Size);
data[Size] = '\0';
if (fuzzer_request_startup() == FAILURE) {
return 0;
}
for (int option = 0; option <=1; ++option) {
zval result;
php_json_parser parser;
php_json_parser_init(&parser, &result, data, Size, option, 10);
if (php_json_yyparse(&parser) == SUCCESS) {
zval_ptr_dtor(&result);
}
}
php_request_shutdown(NULL);
free(data);
return 0;
}
int LLVMFuzzerInitialize(int *argc, char ***argv) {
fuzzer_init_php(NULL);
/* fuzzer_shutdown_php(); */
return 0;
}
| 1,911 | 29.349206 | 75 |
c
|
php-src
|
php-src-master/sapi/fuzzer/fuzzer-mbregex.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Stanislav Malyshev <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "fuzzer.h"
#include "Zend/zend.h"
#include "main/php_config.h"
#include "main/php_main.h"
#include "oniguruma.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include "fuzzer-sapi.h"
int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
#ifdef HAVE_MBREGEX
char *args[2];
char *data = malloc(Size+1);
memcpy(data, Data, Size);
data[Size] = '\0';
if (fuzzer_request_startup() == FAILURE) {
return 0;
}
fuzzer_setup_dummy_frame();
args[0] = data;
args[1] = "test123";
fuzzer_call_php_func("mb_ereg", 2, args);
args[0] = data;
args[1] = "test123";
fuzzer_call_php_func("mb_eregi", 2, args);
args[0] = data;
args[1] = data;
fuzzer_call_php_func("mb_ereg", 2, args);
args[0] = data;
args[1] = data;
fuzzer_call_php_func("mb_eregi", 2, args);
fuzzer_request_shutdown();
free(data);
#else
fprintf(stderr, "\n\nERROR:\nPHP built without mbstring, recompile with --enable-mbstring to use this fuzzer\n");
exit(1);
#endif
return 0;
}
int LLVMFuzzerInitialize(int *argc, char ***argv) {
fuzzer_init_php(NULL);
/* The default parse depth limit allows stack overflows under asan. */
onig_set_parse_depth_limit(512);
/* fuzzer_shutdown_php(); */
return 0;
}
| 2,219 | 27.101266 | 114 |
c
|
php-src
|
php-src-master/sapi/fuzzer/fuzzer-parser.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Johannes Schlüter <[email protected]> |
| Stanislav Malyshev <[email protected]> |
+----------------------------------------------------------------------+
*/
#include <main/php.h>
#include <main/php_main.h>
#include <main/SAPI.h>
#include <ext/standard/info.h>
#include <ext/standard/php_var.h>
#include <main/php_variables.h>
#include "fuzzer.h"
#include "fuzzer-sapi.h"
int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
if (Size > 6 * 1024) {
/* Large inputs have a large impact on fuzzer performance and may cause stack overflows,
* but are unlikely to be necessary to reach new codepaths. */
return 0;
}
fuzzer_do_request_from_buffer(
"fuzzer.php", (const char *) Data, Size, /* execute */ 0, /* before_shutdown */ NULL);
return 0;
}
int LLVMFuzzerInitialize(int *argc, char ***argv) {
/* Compilation will often trigger fatal errors.
* Use tracked allocation mode to avoid leaks in that case. */
putenv("USE_TRACKED_ALLOC=1");
fuzzer_init_php(NULL);
/* fuzzer_shutdown_php(); */
return 0;
}
| 1,949 | 37.235294 | 90 |
c
|
php-src
|
php-src-master/sapi/fuzzer/fuzzer-sapi.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Johannes Schlüter <[email protected]> |
| Stanislav Malyshev <[email protected]> |
+----------------------------------------------------------------------+
*/
#include <main/php.h>
#include <main/php_main.h>
#include <main/SAPI.h>
#include <ext/standard/info.h>
#include <ext/standard/php_var.h>
#include <main/php_variables.h>
#include <zend_exceptions.h>
#ifdef __SANITIZE_ADDRESS__
# include "sanitizer/lsan_interface.h"
#endif
#include "fuzzer.h"
#include "fuzzer-sapi.h"
const char HARDCODED_INI[] =
"html_errors=0\n"
"implicit_flush=1\n"
"output_buffering=0\n"
"error_reporting=0\n"
/* Let the timeout be enforced by libfuzzer, not PHP. */
"max_execution_time=0\n"
/* Reduce oniguruma limits to speed up fuzzing */
"mbstring.regex_stack_limit=10000\n"
"mbstring.regex_retry_limit=10000\n"
/* For the "execute" fuzzer disable some functions that are likely to have
* undesirable consequences (shell execution, file system writes). */
"allow_url_include=0\n"
"allow_url_fopen=0\n"
"open_basedir=/tmp\n"
"disable_functions=dl,mail,mb_send_mail"
",shell_exec,exec,system,proc_open,popen,passthru,pcntl_exec"
",chdir,chgrp,chmod,chown,copy,file_put_contents,lchgrp,lchown,link,mkdir"
",move_uploaded_file,rename,rmdir,symlink,tempname,touch,unlink,fopen"
/* Networking code likes to wait and wait. */
",fsockopen,pfsockopen"
",stream_socket_pair,stream_socket_client,stream_socket_server"
/* crypt() can be very slow. */
",crypt"
/* openlog() has a known memory-management issue. */
",openlog"
/* Can cause long loops that bypass the executor step limit. */
"\ndisable_classes=InfiniteIterator"
;
static int startup(sapi_module_struct *sapi_module)
{
return php_module_startup(sapi_module, NULL);
}
static size_t ub_write(const char *str, size_t str_length)
{
/* quiet */
return str_length;
}
static void fuzzer_flush(void *server_context)
{
/* quiet */
}
static void send_header(sapi_header_struct *sapi_header, void *server_context)
{
}
static char* read_cookies(void)
{
/* TODO: fuzz these! */
return NULL;
}
static void register_variables(zval *track_vars_array)
{
php_import_environment_variables(track_vars_array);
}
static void log_message(const char *message, int level)
{
}
static sapi_module_struct fuzzer_module = {
"fuzzer", /* name */
"clang fuzzer", /* pretty name */
startup, /* startup */
php_module_shutdown_wrapper, /* shutdown */
NULL, /* activate */
NULL, /* deactivate */
ub_write, /* unbuffered write */
fuzzer_flush, /* flush */
NULL, /* get uid */
NULL, /* getenv */
php_error, /* error handler */
NULL, /* header handler */
NULL, /* send headers handler */
send_header, /* send header handler */
NULL, /* read POST data */
read_cookies, /* read Cookies */
register_variables, /* register server variables */
log_message, /* Log message */
NULL, /* Get request time */
NULL, /* Child terminate */
STANDARD_SAPI_MODULE_PROPERTIES
};
int fuzzer_init_php(const char *extra_ini)
{
#ifdef __SANITIZE_ADDRESS__
/* We're going to leak all the memory allocated during startup,
* so disable lsan temporarily. */
__lsan_disable();
#endif
sapi_startup(&fuzzer_module);
fuzzer_module.phpinfo_as_text = 1;
size_t ini_len = sizeof(HARDCODED_INI);
size_t extra_ini_len = extra_ini ? strlen(extra_ini) : 0;
if (extra_ini) {
ini_len += extra_ini_len + 1;
}
char *p = malloc(ini_len + 1);
fuzzer_module.ini_entries = p;
memcpy(p, HARDCODED_INI, sizeof(HARDCODED_INI) - 1);
p += sizeof(HARDCODED_INI) - 1;
if (extra_ini) {
*p++ = '\n';
memcpy(p, extra_ini, extra_ini_len);
p += extra_ini_len;
}
*p = '\0';
/*
* TODO: we might want to test both Zend and malloc MM, but testing with malloc
* is more likely to find bugs, so use that for now.
*/
putenv("USE_ZEND_ALLOC=0");
if (fuzzer_module.startup(&fuzzer_module)==FAILURE) {
return FAILURE;
}
#ifdef __SANITIZE_ADDRESS__
__lsan_enable();
#endif
return SUCCESS;
}
int fuzzer_request_startup(void)
{
if (php_request_startup() == FAILURE) {
php_module_shutdown();
return FAILURE;
}
#ifdef ZEND_SIGNALS
/* Some signal handlers will be overridden,
* don't complain about them during shutdown. */
SIGG(check) = 0;
#endif
return SUCCESS;
}
void fuzzer_request_shutdown(void)
{
zend_try {
/* Destroy thrown exceptions. This does not happen as part of request shutdown. */
if (EG(exception)) {
zend_object_release(EG(exception));
EG(exception) = NULL;
}
/* Some fuzzers (like unserialize) may create circular structures. Make sure we free them.
* Two calls are performed to handle objects with destructors. */
zend_gc_collect_cycles();
zend_gc_collect_cycles();
} zend_end_try();
php_request_shutdown(NULL);
}
/* Set up a dummy stack frame so that exceptions may be thrown. */
void fuzzer_setup_dummy_frame(void)
{
static zend_execute_data execute_data;
static zend_function func;
memset(&execute_data, 0, sizeof(zend_execute_data));
memset(&func, 0, sizeof(zend_function));
func.type = ZEND_INTERNAL_FUNCTION;
func.common.function_name = ZSTR_EMPTY_ALLOC();
execute_data.func = &func;
EG(current_execute_data) = &execute_data;
}
void fuzzer_set_ini_file(const char *file)
{
if (fuzzer_module.php_ini_path_override) {
free(fuzzer_module.php_ini_path_override);
}
fuzzer_module.php_ini_path_override = strdup(file);
}
int fuzzer_shutdown_php(void)
{
php_module_shutdown();
sapi_shutdown();
free((void *)fuzzer_module.ini_entries);
return SUCCESS;
}
int fuzzer_do_request_from_buffer(
char *filename, const char *data, size_t data_len, bool execute,
void (*before_shutdown)(void))
{
int retval = FAILURE; /* failure by default */
SG(options) |= SAPI_OPTION_NO_CHDIR;
SG(request_info).argc=0;
SG(request_info).argv=NULL;
if (fuzzer_request_startup() == FAILURE) {
return FAILURE;
}
// Commented out to avoid leaking the header callback.
//SG(headers_sent) = 1;
//SG(request_info).no_headers = 1;
php_register_variable("PHP_SELF", filename, NULL);
zend_first_try {
zend_file_handle file_handle;
zend_stream_init_filename(&file_handle, filename);
file_handle.primary_script = 1;
file_handle.buf = emalloc(data_len + ZEND_MMAP_AHEAD);
memcpy(file_handle.buf, data, data_len);
memset(file_handle.buf + data_len, 0, ZEND_MMAP_AHEAD);
file_handle.len = data_len;
/* Avoid ZEND_HANDLE_FILENAME for opcache. */
file_handle.type = ZEND_HANDLE_STREAM;
zend_op_array *op_array = zend_compile_file(&file_handle, ZEND_REQUIRE);
zend_destroy_file_handle(&file_handle);
if (op_array) {
if (execute) {
zend_execute(op_array, NULL);
}
zend_destroy_static_vars(op_array);
destroy_op_array(op_array);
efree(op_array);
}
} zend_end_try();
CG(compiled_filename) = NULL; /* ??? */
if (before_shutdown) {
before_shutdown();
}
fuzzer_request_shutdown();
return (retval == SUCCESS) ? SUCCESS : FAILURE;
}
// Call named PHP function with N zval arguments
void fuzzer_call_php_func_zval(const char *func_name, int nargs, zval *args) {
zval retval, func;
ZVAL_STRING(&func, func_name);
ZVAL_UNDEF(&retval);
call_user_function(CG(function_table), NULL, &func, &retval, nargs, args);
// TODO: check result?
/* to ensure retval is not broken */
php_var_dump(&retval, 0);
/* cleanup */
zval_ptr_dtor(&retval);
zval_ptr_dtor(&func);
}
// Call named PHP function with N string arguments
void fuzzer_call_php_func(const char *func_name, int nargs, char **params) {
zval args[nargs];
int i;
for(i=0;i<nargs;i++) {
ZVAL_STRING(&args[i], params[i]);
}
fuzzer_call_php_func_zval(func_name, nargs, args);
for(i=0;i<nargs;i++) {
zval_ptr_dtor(&args[i]);
ZVAL_UNDEF(&args[i]);
}
}
| 8,914 | 26.346626 | 92 |
c
|
php-src
|
php-src-master/sapi/fuzzer/fuzzer-sapi.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Johannes Schlüter <[email protected]> |
| Stanislav Malyshev <[email protected]> |
+----------------------------------------------------------------------+
*/
int fuzzer_init_php(const char *extra_ini);
int fuzzer_request_startup(void);
void fuzzer_request_shutdown(void);
void fuzzer_setup_dummy_frame(void);
void fuzzer_call_php_func(const char *func_name, int nargs, char **params);
void fuzzer_call_php_func_zval(const char *func_name, int nargs, zval *args);
int fuzzer_do_request_from_buffer(
char *filename, const char *data, size_t data_len, bool execute,
void (*before_shutdown)(void));
| 1,513 | 55.074074 | 77 |
h
|
php-src
|
php-src-master/sapi/fuzzer/fuzzer-tracing-jit.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Nikita Popov <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "fuzzer-execute-common.h"
int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
if (Size > MAX_SIZE) {
/* Large inputs have a large impact on fuzzer performance,
* but are unlikely to be necessary to reach new codepaths. */
return 0;
}
zend_string *jit_option = ZSTR_INIT_LITERAL("opcache.jit", 1);
/* First run without JIT to determine whether we bail out. We should not run JITed code if
* we bail out here, as the JIT code may loop infinitely. */
steps_left = MAX_STEPS;
bailed_out = false;
zend_alter_ini_entry_chars(
jit_option, "off", sizeof("off")-1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
fuzzer_do_request_from_buffer(
FILE_NAME, (const char *) Data, Size, /* execute */ 1, opcache_invalidate);
if (!bailed_out) {
steps_left = MAX_STEPS;
zend_alter_ini_entry_chars(jit_option,
"tracing", sizeof("tracing")-1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
zend_execute_ex = orig_execute_ex;
/* Trace & compile */
fuzzer_do_request_from_buffer(
FILE_NAME, (const char *) Data, Size, /* execute */ 1, NULL);
/* Execute trace */
fuzzer_do_request_from_buffer(
FILE_NAME, (const char *) Data, Size, /* execute */ 1, opcache_invalidate);
zend_execute_ex = fuzzer_execute_ex;
}
zend_string_release(jit_option);
return 0;
}
int LLVMFuzzerInitialize(int *argc, char ***argv) {
char *opcache_path = get_opcache_path();
assert(opcache_path && "Failed to determine opcache path");
char ini_buf[512];
snprintf(ini_buf, sizeof(ini_buf),
"zend_extension=%s\n"
"opcache.validate_timestamps=0\n"
"opcache.file_update_protection=0\n"
"opcache.jit_buffer_size=256M\n"
"opcache.jit_hot_func=1\n"
"opcache.jit_hot_loop=1\n"
"opcache.jit_hot_return=1\n"
"opcache.jit_hot_side_exit=1\n"
"opcache.jit_max_root_traces=32768",
opcache_path);
free(opcache_path);
create_file();
fuzzer_init_php_for_execute(ini_buf);
return 0;
}
| 2,902 | 36.217949 | 91 |
c
|
php-src
|
php-src-master/sapi/fuzzer/fuzzer-unserialize.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Johannes Schlüter <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "fuzzer.h"
#include "Zend/zend.h"
#include "main/php_config.h"
#include "main/php_main.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include "fuzzer-sapi.h"
#include "ext/standard/php_var.h"
int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
unsigned char *orig_data = malloc(Size+1);
memcpy(orig_data, Data, Size);
orig_data[Size] = '\0';
if (fuzzer_request_startup() == FAILURE) {
return 0;
}
fuzzer_setup_dummy_frame();
{
const unsigned char *data = orig_data;
zval result;
ZVAL_UNDEF(&result);
php_unserialize_data_t var_hash;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
php_var_unserialize(&result, (const unsigned char **) &data, data + Size, &var_hash);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
zval_ptr_dtor(&result);
}
free(orig_data);
fuzzer_request_shutdown();
return 0;
}
int LLVMFuzzerInitialize(int *argc, char ***argv) {
fuzzer_init_php(NULL);
/* fuzzer_shutdown_php(); */
return 0;
}
| 1,971 | 28 | 87 |
c
|
php-src
|
php-src-master/sapi/fuzzer/fuzzer-unserializehash.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "fuzzer.h"
#include "Zend/zend.h"
#include "main/php_config.h"
#include "main/php_main.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include "fuzzer-sapi.h"
#include "ext/standard/php_var.h"
int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t FullSize) {
const uint8_t *Start = memchr(Data, '|', FullSize);
if (!Start) {
return 0;
}
++Start;
size_t Size = (Data + FullSize) - Start;
unsigned char *orig_data = malloc(Size+1);
memcpy(orig_data, Start, Size);
orig_data[Size] = '\0';
if (fuzzer_request_startup() == FAILURE) {
return 0;
}
fuzzer_setup_dummy_frame();
{
const unsigned char *data = orig_data;
zval result;
ZVAL_UNDEF(&result);
php_unserialize_data_t var_hash;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
php_var_unserialize(&result, (const unsigned char **) &data, data + Size, &var_hash);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (Z_TYPE(result) == IS_OBJECT
&& zend_string_equals_literal(Z_OBJCE(result)->name, "HashContext")) {
zval args[2];
ZVAL_COPY_VALUE(&args[0], &result);
ZVAL_STRINGL(&args[1], (char *) Data, (Start - Data) - 1);
fuzzer_call_php_func_zval("hash_update", 2, args);
zval_ptr_dtor(&args[1]);
fuzzer_call_php_func_zval("hash_final", 1, args);
}
zval_ptr_dtor(&result);
}
free(orig_data);
fuzzer_request_shutdown();
return 0;
}
int LLVMFuzzerInitialize(int *argc, char ***argv) {
fuzzer_init_php(NULL);
/* fuzzer_shutdown_php(); */
return 0;
}
| 2,326 | 27.036145 | 87 |
c
|
php-src
|
php-src-master/sapi/fuzzer/fuzzer.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Johannes Schlüter <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php_version.h"
#define FUZZER_VERSION PHP_VERSION
| 1,056 | 54.631579 | 75 |
h
|
php-src
|
php-src-master/sapi/litespeed/lsapi_main_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: 3419f4e77bd091e09e0cfc55d81f443d5a3396ff */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_litespeed_request_headers, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
#define arginfo_getallheaders arginfo_litespeed_request_headers
#define arginfo_apache_request_headers arginfo_litespeed_request_headers
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_litespeed_response_headers, 0, 0, MAY_BE_ARRAY|MAY_BE_FALSE)
ZEND_END_ARG_INFO()
#define arginfo_apache_response_headers arginfo_litespeed_response_headers
#define arginfo_apache_get_modules arginfo_litespeed_request_headers
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_litespeed_finish_request, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
ZEND_FUNCTION(litespeed_request_headers);
ZEND_FUNCTION(litespeed_response_headers);
ZEND_FUNCTION(apache_get_modules);
ZEND_FUNCTION(litespeed_finish_request);
static const zend_function_entry ext_functions[] = {
ZEND_FE(litespeed_request_headers, arginfo_litespeed_request_headers)
ZEND_FALIAS(getallheaders, litespeed_request_headers, arginfo_getallheaders)
ZEND_FALIAS(apache_request_headers, litespeed_request_headers, arginfo_apache_request_headers)
ZEND_FE(litespeed_response_headers, arginfo_litespeed_response_headers)
ZEND_FALIAS(apache_response_headers, litespeed_response_headers, arginfo_apache_response_headers)
ZEND_FE(apache_get_modules, arginfo_apache_get_modules)
ZEND_FE(litespeed_finish_request, arginfo_litespeed_finish_request)
ZEND_FE_END
};
| 1,541 | 39.578947 | 108 |
h
|
php-src
|
php-src-master/sapi/litespeed/lsapidef.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: George Wang <[email protected]> |
+----------------------------------------------------------------------+
*/
/*
Copyright (c) 2002-2015, Lite Speed Technologies Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the Lite Speed Technologies Inc nor the
names of its contributors may be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _LSAPIDEF_H_
#define _LSAPIDEF_H_
#include <inttypes.h>
#if defined (c_plusplus) || defined (__cplusplus)
extern "C" {
#endif
enum
{
H_ACCEPT = 0,
H_ACC_CHARSET,
H_ACC_ENCODING,
H_ACC_LANG,
H_AUTHORIZATION,
H_CONNECTION,
H_CONTENT_TYPE,
H_CONTENT_LENGTH,
H_COOKIE,
H_COOKIE2,
H_HOST,
H_PRAGMA,
H_REFERER,
H_USERAGENT,
H_CACHE_CTRL,
H_IF_MODIFIED_SINCE,
H_IF_MATCH,
H_IF_NO_MATCH,
H_IF_RANGE,
H_IF_UNMOD_SINCE,
H_KEEP_ALIVE,
H_RANGE,
H_X_FORWARDED_FOR,
H_VIA,
H_TRANSFER_ENCODING
};
#define LSAPI_SOCK_FILENO 0
#define LSAPI_VERSION_B0 'L'
#define LSAPI_VERSION_B1 'S'
/* Values for m_flag in lsapi_packet_header */
#define LSAPI_ENDIAN_LITTLE 0
#define LSAPI_ENDIAN_BIG 1
#define LSAPI_ENDIAN_BIT 1
#if defined(__i386__)||defined( __x86_64 )||defined( __x86_64__ )
#define LSAPI_ENDIAN LSAPI_ENDIAN_LITTLE
#else
#define LSAPI_ENDIAN LSAPI_ENDIAN_BIG
#endif
/* Values for m_type in lsapi_packet_header */
#define LSAPI_BEGIN_REQUEST 1
#define LSAPI_ABORT_REQUEST 2
#define LSAPI_RESP_HEADER 3
#define LSAPI_RESP_STREAM 4
#define LSAPI_RESP_END 5
#define LSAPI_STDERR_STREAM 6
#define LSAPI_REQ_RECEIVED 7
#define LSAPI_CONN_CLOSE 8
#define LSAPI_INTERNAL_ERROR 9
#define LSAPI_MAX_HEADER_LEN 65535
#define LSAPI_MAX_DATA_PACKET_LEN 16384
#define LSAPI_RESP_HTTP_HEADER_MAX 32768
#define LSAPI_PACKET_HEADER_LEN 8
struct lsapi_packet_header
{
char m_versionB0; /* LSAPI protocol version */
char m_versionB1;
char m_type;
char m_flag;
union
{
int32_t m_iLen; /* include this header */
char m_bytes[4];
}m_packetLen;
};
/*
LSAPI request header packet
1. struct lsapi_req_header
2. struct lsapi_http_header_index
3. lsapi_header_offset * unknownHeaders
4. org http request header
5. request body if available
*/
struct lsapi_req_header
{
struct lsapi_packet_header m_pktHeader;
int32_t m_httpHeaderLen;
int32_t m_reqBodyLen;
int32_t m_scriptFileOff; /* path to the script file. */
int32_t m_scriptNameOff; /* decrypted URI, without pathinfo, */
int32_t m_queryStringOff; /* Query string inside env */
int32_t m_requestMethodOff;
int32_t m_cntUnknownHeaders;
int32_t m_cntEnv;
int32_t m_cntSpecialEnv;
} ;
struct lsapi_http_header_index
{
uint16_t m_headerLen[H_TRANSFER_ENCODING+1];
int32_t m_headerOff[H_TRANSFER_ENCODING+1];
} ;
struct lsapi_header_offset
{
int32_t nameOff;
int32_t nameLen;
int32_t valueOff;
int32_t valueLen;
} ;
struct lsapi_resp_info
{
int32_t m_cntHeaders;
int32_t m_status;
};
struct lsapi_resp_header
{
struct lsapi_packet_header m_pktHeader;
struct lsapi_resp_info m_respInfo;
};
#if defined (c_plusplus) || defined (__cplusplus)
}
#endif
#endif
| 5,646 | 28.108247 | 75 |
h
|
php-src
|
php-src-master/sapi/litespeed/lsapilib.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: George Wang <[email protected]> |
+----------------------------------------------------------------------+
*/
/*
Copyright (c) 2002-2018, Lite Speed Technologies Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the Lite Speed Technologies Inc nor the
names of its contributors may be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _LSAPILIB_H_
#define _LSAPILIB_H_
#if defined (c_plusplus) || defined (__cplusplus)
extern "C" {
#endif
#include "lsapidef.h"
#include <stddef.h>
#include <sys/time.h>
#include <sys/types.h>
struct LSAPI_key_value_pair
{
char * pKey;
char * pValue;
int keyLen;
int valLen;
};
struct lsapi_child_status;
#define LSAPI_MAX_RESP_HEADERS 1000
typedef struct lsapi_request
{
int m_fdListen;
int m_fd;
long m_lLastActive;
long m_lReqBegin;
char * m_pReqBuf;
int m_reqBufSize;
char * m_pRespBuf;
char * m_pRespBufEnd;
char * m_pRespBufPos;
char * m_pRespHeaderBuf;
char * m_pRespHeaderBufEnd;
char * m_pRespHeaderBufPos;
struct lsapi_child_status * child_status;
struct iovec * m_pIovec;
struct iovec * m_pIovecEnd;
struct iovec * m_pIovecCur;
struct iovec * m_pIovecToWrite;
struct lsapi_packet_header * m_respPktHeaderEnd;
struct lsapi_req_header * m_pHeader;
struct LSAPI_key_value_pair * m_pEnvList;
struct LSAPI_key_value_pair * m_pSpecialEnvList;
int m_envListSize;
int m_specialEnvListSize;
struct lsapi_http_header_index * m_pHeaderIndex;
struct lsapi_header_offset * m_pUnknownHeader;
char * m_pScriptFile;
char * m_pScriptName;
char * m_pQueryString;
char * m_pHttpHeader;
char * m_pRequestMethod;
int m_totalLen;
int m_reqState;
off_t m_reqBodyLen;
off_t m_reqBodyRead;
int m_bufProcessed;
int m_bufRead;
struct lsapi_packet_header m_respPktHeader[5];
struct lsapi_resp_header m_respHeader;
short m_respHeaderLen[LSAPI_MAX_RESP_HEADERS];
void * m_pAppData;
}LSAPI_Request;
extern LSAPI_Request g_req;
/* return: >0 continue, ==0 stop, -1 failed */
typedef int (*LSAPI_CB_EnvHandler )( const char * pKey, int keyLen,
const char * pValue, int valLen, void * arg );
int LSAPI_Init(void);
void LSAPI_Stop(void);
int LSAPI_Is_Listen_r( LSAPI_Request * pReq);
int LSAPI_InitRequest( LSAPI_Request * pReq, int fd );
int LSAPI_Accept_r( LSAPI_Request * pReq );
void LSAPI_Reset_r( LSAPI_Request * pReq );
int LSAPI_Finish_r( LSAPI_Request * pReq );
int LSAPI_Release_r( LSAPI_Request * pReq );
char * LSAPI_GetHeader_r( LSAPI_Request * pReq, int headerIndex );
int LSAPI_ForeachHeader_r( LSAPI_Request * pReq,
LSAPI_CB_EnvHandler fn, void * arg );
int LSAPI_ForeachOrgHeader_r( LSAPI_Request * pReq,
LSAPI_CB_EnvHandler fn, void * arg );
int LSAPI_ForeachEnv_r( LSAPI_Request * pReq,
LSAPI_CB_EnvHandler fn, void * arg );
int LSAPI_ForeachSpecialEnv_r( LSAPI_Request * pReq,
LSAPI_CB_EnvHandler fn, void * arg );
char * LSAPI_GetEnv_r( LSAPI_Request * pReq, const char * name );
ssize_t LSAPI_ReadReqBody_r( LSAPI_Request * pReq, char * pBuf, size_t len );
int LSAPI_ReqBodyGetChar_r( LSAPI_Request * pReq );
int LSAPI_ReqBodyGetLine_r( LSAPI_Request * pReq, char * pBuf, size_t bufLen, int *getLF );
int LSAPI_FinalizeRespHeaders_r( LSAPI_Request * pReq );
ssize_t LSAPI_Write_r( LSAPI_Request * pReq, const char * pBuf, size_t len );
ssize_t LSAPI_sendfile_r( LSAPI_Request * pReq, int fdIn, off_t* off, size_t size );
ssize_t LSAPI_Write_Stderr_r( LSAPI_Request * pReq, const char * pBuf, size_t len );
int LSAPI_Flush_r( LSAPI_Request * pReq );
int LSAPI_AppendRespHeader_r( LSAPI_Request * pReq, const char * pBuf, int len );
int LSAPI_AppendRespHeader2_r( LSAPI_Request * pReq, const char * pHeaderName,
const char * pHeaderValue );
int LSAPI_ErrResponse_r( LSAPI_Request * pReq, int code, const char ** pRespHeaders,
const char * pBody, int bodyLen );
static inline int LSAPI_SetRespStatus_r( LSAPI_Request * pReq, int code )
{
if ( !pReq )
return -1;
pReq->m_respHeader.m_respInfo.m_status = code;
return 0;
}
static inline int LSAPI_SetAppData_r( LSAPI_Request * pReq, void * data )
{
if ( !pReq )
return -1;
pReq->m_pAppData = data;
return 0;
}
static inline void * LSAPI_GetAppData_r( LSAPI_Request * pReq )
{
if ( !pReq )
return NULL;
return pReq->m_pAppData;
}
static inline char * LSAPI_GetQueryString_r( LSAPI_Request * pReq )
{
if ( pReq )
return pReq->m_pQueryString;
return NULL;
}
static inline char * LSAPI_GetScriptFileName_r( LSAPI_Request * pReq )
{
if ( pReq )
return pReq->m_pScriptFile;
return NULL;
}
static inline char * LSAPI_GetScriptName_r( LSAPI_Request * pReq )
{
if ( pReq )
return pReq->m_pScriptName;
return NULL;
}
static inline char * LSAPI_GetRequestMethod_r( LSAPI_Request * pReq)
{
if ( pReq )
return pReq->m_pRequestMethod;
return NULL;
}
static inline off_t LSAPI_GetReqBodyLen_r( LSAPI_Request * pReq )
{
if ( pReq )
return pReq->m_reqBodyLen;
return -1;
}
static inline off_t LSAPI_GetReqBodyRemain_r( LSAPI_Request * pReq )
{
if ( pReq )
return pReq->m_reqBodyLen - pReq->m_reqBodyRead;
return -1;
}
int LSAPI_End_Response_r(LSAPI_Request * pReq);
int LSAPI_Is_Listen(void);
static inline int LSAPI_Accept( void )
{ return LSAPI_Accept_r( &g_req ); }
static inline int LSAPI_Finish(void)
{ return LSAPI_Finish_r( &g_req ); }
static inline char * LSAPI_GetHeader( int headerIndex )
{ return LSAPI_GetHeader_r( &g_req, headerIndex ); }
static inline int LSAPI_ForeachHeader( LSAPI_CB_EnvHandler fn, void * arg )
{ return LSAPI_ForeachHeader_r( &g_req, fn, arg ); }
static inline int LSAPI_ForeachOrgHeader(
LSAPI_CB_EnvHandler fn, void * arg )
{ return LSAPI_ForeachOrgHeader_r( &g_req, fn, arg ); }
static inline int LSAPI_ForeachEnv( LSAPI_CB_EnvHandler fn, void * arg )
{ return LSAPI_ForeachEnv_r( &g_req, fn, arg ); }
static inline int LSAPI_ForeachSpecialEnv( LSAPI_CB_EnvHandler fn, void * arg )
{ return LSAPI_ForeachSpecialEnv_r( &g_req, fn, arg ); }
static inline char * LSAPI_GetEnv( const char * name )
{ return LSAPI_GetEnv_r( &g_req, name ); }
static inline char * LSAPI_GetQueryString(void)
{ return LSAPI_GetQueryString_r( &g_req ); }
static inline char * LSAPI_GetScriptFileName(void)
{ return LSAPI_GetScriptFileName_r( &g_req ); }
static inline char * LSAPI_GetScriptName(void)
{ return LSAPI_GetScriptName_r( &g_req ); }
static inline char * LSAPI_GetRequestMethod(void)
{ return LSAPI_GetRequestMethod_r( &g_req ); }
static inline off_t LSAPI_GetReqBodyLen(void)
{ return LSAPI_GetReqBodyLen_r( &g_req ); }
static inline off_t LSAPI_GetReqBodyRemain(void)
{ return LSAPI_GetReqBodyRemain_r( &g_req ); }
static inline ssize_t LSAPI_ReadReqBody( char * pBuf, size_t len )
{ return LSAPI_ReadReqBody_r( &g_req, pBuf, len ); }
static inline int LSAPI_ReqBodyGetChar(void)
{ return LSAPI_ReqBodyGetChar_r( &g_req ); }
static inline int LSAPI_ReqBodyGetLine( char * pBuf, int len, int *getLF )
{ return LSAPI_ReqBodyGetLine_r( &g_req, pBuf, len, getLF ); }
static inline int LSAPI_FinalizeRespHeaders(void)
{ return LSAPI_FinalizeRespHeaders_r( &g_req ); }
static inline ssize_t LSAPI_Write( const char * pBuf, ssize_t len )
{ return LSAPI_Write_r( &g_req, pBuf, len ); }
static inline ssize_t LSAPI_sendfile( int fdIn, off_t* off, size_t size )
{
return LSAPI_sendfile_r(&g_req, fdIn, off, size );
}
static inline ssize_t LSAPI_Write_Stderr( const char * pBuf, ssize_t len )
{ return LSAPI_Write_Stderr_r( &g_req, pBuf, len ); }
static inline int LSAPI_Flush(void)
{ return LSAPI_Flush_r( &g_req ); }
static inline int LSAPI_AppendRespHeader( char * pBuf, int len )
{ return LSAPI_AppendRespHeader_r( &g_req, pBuf, len ); }
static inline int LSAPI_SetRespStatus( int code )
{ return LSAPI_SetRespStatus_r( &g_req, code ); }
static inline int LSAPI_ErrResponse( int code, const char ** pRespHeaders, const char * pBody, int bodyLen )
{ return LSAPI_ErrResponse_r( &g_req, code, pRespHeaders, pBody, bodyLen ); }
static inline int LSAPI_End_Response(void)
{ return LSAPI_End_Response_r( &g_req ); }
int LSAPI_IsRunning(void);
int LSAPI_CreateListenSock( const char * pBind, int backlog );
typedef int (*fn_select_t)( int, fd_set *, fd_set *, fd_set *, struct timeval * );
int LSAPI_Init_Prefork_Server( int max_children, fn_select_t fp, int avoidFork );
void LSAPI_Set_Server_fd( int fd );
int LSAPI_Prefork_Accept_r( LSAPI_Request * pReq );
void LSAPI_No_Check_ppid(void);
void LSAPI_Set_Max_Reqs( int reqs );
void LSAPI_Set_Max_Idle( int secs );
void LSAPI_Set_Max_Children( int maxChildren );
void LSAPI_Set_Max_Idle_Children( int maxIdleChld );
void LSAPI_Set_Server_Max_Idle_Secs( int serverMaxIdle );
void LSAPI_Set_Max_Process_Time( int secs );
int LSAPI_Init_Env_Parameters( fn_select_t fp );
void LSAPI_Set_Slow_Req_Msecs( int msecs );
int LSAPI_Get_Slow_Req_Msecs(void);
int LSAPI_is_suEXEC_Daemon(void);
int LSAPI_Set_Restored_Parent_Pid(int pid);
typedef void (*LSAPI_On_Timer_pf)(int *forked_child_pid);
void LSAPI_Register_Pgrp_Timer_Callback(LSAPI_On_Timer_pf);
int LSAPI_Inc_Req_Processed(int cnt);
int LSAPI_Accept_Before_Fork(LSAPI_Request * pReq);
int LSAPI_Postfork_Child(LSAPI_Request * pReq);
int LSAPI_Postfork_Parent(LSAPI_Request * pReq);
#define LSAPI_LOG_LEVEL_BITS 0xff
#define LSAPI_LOG_FLAG_NONE 0
#define LSAPI_LOG_FLAG_DEBUG 1
#define LSAPI_LOG_FLAG_INFO 2
#define LSAPI_LOG_FLAG_NOTICE 3
#define LSAPI_LOG_FLAG_WARN 4
#define LSAPI_LOG_FLAG_ERROR 5
#define LSAPI_LOG_FLAG_CRIT 6
#define LSAPI_LOG_FLAG_FATAL 7
#define LSAPI_LOG_TIMESTAMP_BITS (0xff00)
#define LSAPI_LOG_TIMESTAMP_FULL (0x100)
#define LSAPI_LOG_TIMESTAMP_HMS (0x200)
#define LSAPI_LOG_TIMESTAMP_STDERR (0x400)
#define LSAPI_LOG_PID (0x10000)
void LSAPI_Log(int flag, const char * fmt, ...)
#if __GNUC__
__attribute__((format(printf, 2, 3)))
#endif
;
#if defined (c_plusplus) || defined (__cplusplus)
}
#endif
#endif
| 13,273 | 29.655889 | 108 |
h
|
php-src
|
php-src-master/sapi/litespeed/lscriu.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: George Wang <[email protected]> |
+----------------------------------------------------------------------+
*/
/*
Copyright (c) 2002-2018, Lite Speed Technologies Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the Lite Speed Technologies Inc nor the
names of its contributors may be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define HAVE_MSGHDR_MSG_CONTROL
#include "lsapilib.h"
#include <stdio.h>
#include <stdlib.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <sys/wait.h>
#include <sys/stat.h>
#if HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <semaphore.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#include <signal.h>
#include <time.h>
#include <sys/timeb.h>
#include <unistd.h>
#include "lscriu.h"
#include <Zend/zend_portability.h>
#define LSCRIU_PATH 256
// Begin CRIU inclusion
//CRIU inclusion
static int s_initial_start_reqs = 0;
static int s_requests_count = 0;
static int s_restored = 0;
static int (*s_lscapi_dump_me)(void) = NULL;
static int (*s_lscapi_prepare_me)(void) = NULL;
static int s_native = 0;
static int s_tried_checkpoint = 0;
static int s_criu_debug = 0;
static int s_fd_native = -1;
static char *s_criu_image_path = NULL;
static int s_pid = 0;
typedef enum
{
CRIU_GCOUNTER_SHM,
CRIU_GCOUNTER_SIG,
CRIU_GCOUNTER_PIPE
} GlobalCounterType_t;
static GlobalCounterType_t s_global_counter_type = CRIU_GCOUNTER_SHM;
#ifndef sighandler_t
typedef void (*sighandler_t)(int);
#endif
void lsapi_perror( const char * pMessage, int err_no );
void LSAPI_reset_server_state( void );
int LSAPI_Get_ppid(void);
#ifdef LSAPILIB_DEBUG_CRIU
#define lscriu_dbg(...) \
do { if (s_criu_debug) fprintf(stderr, __VA_ARGS__); } while(0)
#else
#define lscriu_dbg(...)
#endif
#define lscriu_err(...) fprintf(stderr, __VA_ARGS__)
#define SUN_PATH_MAX (sizeof(((struct sockaddr_un *)NULL)->sun_path))
typedef struct
{
pid_t m_iPidToDump;
char m_chImageDirectory[1024];
char m_chSocketDir[SUN_PATH_MAX];
char m_chServiceAddress[SUN_PATH_MAX];
} criu_native_dump_t;
typedef sem_t * (*psem_open_t) (const char *__name, int __oflag, ...);
typedef int (*psem_post_t) (sem_t *__sem);
typedef int (*psem_close_t) (sem_t *__sem);
psem_open_t psem_open = NULL;
psem_post_t psem_post = NULL;
psem_close_t psem_close = NULL;
static void lsapi_criu_signal(int signo, sighandler_t handler)
{
struct sigaction sa;
sigaction(signo, NULL, &sa);
if (sa.sa_handler == SIG_DFL) {
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handler;
sigaction(signo, &sa, NULL);
}
}
static void lsapi_siguser2(int sig)
{
// child requests counter for master process
++s_requests_count;
}
static void LSCRIU_Set_Initial_Start_Reqs(int reqs)
{
s_initial_start_reqs = reqs;
}
static void LSCRIU_Set_Global_Counter_Type(GlobalCounterType_t tp)
{
if ((tp == CRIU_GCOUNTER_SHM) || (tp == CRIU_GCOUNTER_SIG)
|| (tp == CRIU_GCOUNTER_PIPE)) {
s_global_counter_type = tp;
} else {
s_global_counter_type = CRIU_GCOUNTER_SHM;
}
}
static int LSCRIU_Get_Global_Counter_Type(void)
{
return s_global_counter_type;
}
static int LSCRIU_Init_Global_Counter(int value)
{
if (LSCRIU_Get_Global_Counter_Type() != CRIU_GCOUNTER_SHM
|| !s_initial_start_reqs) {
return 0;
}
return 0;
}
static void LSCRIU_Increase_Global_Counter(void)
{
if (LSCRIU_Get_Global_Counter_Type() != CRIU_GCOUNTER_SHM
|| !s_initial_start_reqs) {
return;
}
s_requests_count = LSAPI_Inc_Req_Processed(1);
}
static void LSCRIU_Get_Global_Counter(void)
{
if (!s_initial_start_reqs) {
return;
}
s_requests_count = LSAPI_Inc_Req_Processed(0);
}
static int LSCRIU_need_checkpoint(void)
{
if (!s_initial_start_reqs) {
return 0;
}
if (LSCRIU_Get_Global_Counter_Type() == CRIU_GCOUNTER_SHM
&& s_requests_count <= s_initial_start_reqs) {
LSCRIU_Get_Global_Counter();
}
if (s_initial_start_reqs > 0
&& s_requests_count >= s_initial_start_reqs) {
return 1;
}
return 0;
}
static int LSCRIU_load_liblscapi(void)
{
void *lib_handle = NULL;
void *pthread_lib_handle = NULL;
if (s_native)
return 0;
// Numerical signals indicates Apache
int error = 1;
char *last;
if (!(lib_handle = DL_LOAD(last = "liblscapi.so")) /*||
!(pthread_lib_handle = DL_LOAD(last = "libpthread.so"))*/)
fprintf(stderr, "LSCRIU (%d): failed to dlopen %s: %s - ignore CRIU\n",
s_pid, last, dlerror());
else if (!(s_lscapi_dump_me = dlsym(lib_handle, last = "lscapi_dump_me")) ||
!(s_lscapi_prepare_me = dlsym(lib_handle, last = "lscapi_prepare_me")) ||
!(psem_open = dlsym(pthread_lib_handle, last = "sem_open")) ||
!(psem_post = dlsym(pthread_lib_handle, last = "sem_post")) ||
!(psem_close = dlsym(pthread_lib_handle, last = "sem_close")))
fprintf(stderr, "LSCRIU (%d): failed to dlsym %s: %s - ignore CRIU\n",
s_pid, last, dlerror());
else
error = 0;
if (error) {
// close the dll handles so we release the resources
if (lib_handle)
dlclose(lib_handle);
if (pthread_lib_handle)
dlclose(pthread_lib_handle);
return -1;
}
return 0;
}
static void LSCRIU_Wink_Server_is_Ready(void)
{
char sem_name[60];
if (s_native) {
// Not used for native
return;
}
if (getenv("LSAPI_UNIQE"))
snprintf(sem_name, sizeof sem_name - 1, "lsphp[hash=%s].is_ready",
getenv("LSAPI_UNIQE"));
else
snprintf(sem_name, sizeof sem_name - 1, "lsphp[euid=0x%x].is_ready",
geteuid());
sem_t *is_ready_sem = psem_open(sem_name, O_RDWR);
if (is_ready_sem) {
if (psem_post(is_ready_sem) < 0)
lsapi_perror(sem_name, errno);
if (psem_close(is_ready_sem) < 0)
lsapi_perror(sem_name, errno);
}
else if (errno != ENOENT)
lsapi_perror(sem_name, errno);
}
static char *LSCRIU_Error_File_Name(char *pchFile, int max_len)
{
const char *pchDefaultSocketPath = "/tmp/";
const char *pchDefaultLogFileName = "lsws_error.log";
snprintf(pchFile, max_len, "%s%s", pchDefaultSocketPath,
pchDefaultLogFileName);
return pchFile;
}
#ifdef LSAPILIB_DEBUG_CRIU
static void LSCRIU_Debugging(void) {
char *pchCRIUDebug;
pchCRIUDebug = getenv("LSAPI_CRIU_DEBUG");
if (!pchCRIUDebug)
pchCRIUDebug = getenv("LSCAPI_CRIU_DEBUG");
//fprintf(stderr,"(%d) LSCRIU: CRIU debug environment variable: %s\n",
// s_pid, pchCRIUDebug);
// I've made it easy to turn on debugging. CloudLinux Apache sets
// LSCAPI_CRIU_DEBUG to nothing to indicate it's on. Sigh.
if ((!pchCRIUDebug) ||
((!*pchCRIUDebug) ||
(*pchCRIUDebug == '0') ||
(*pchCRIUDebug == 'f') ||
(*pchCRIUDebug == 'F') ||
(((*pchCRIUDebug == 'O') ||
(*pchCRIUDebug == 'o')) &&
((*(pchCRIUDebug + 1)) &&
((*(pchCRIUDebug + 1) == 'F') || (*(pchCRIUDebug + 1) == 'f'))))))
{
lscriu_dbg("LSCRIU (%d): CRIU Debugging disabled by environment\n", s_pid);
s_criu_debug = 0;
}
else {
s_criu_debug = 1;
lscriu_dbg("LSCRIU (%d): CRIU Debugging enabled by environment\n", s_pid);
fprintf(stderr,"LSCRIU (%d): CRIU debug environment variable: %s\n",
s_pid, pchCRIUDebug);
}
}
static void LSCRIU_Restored_Error(int iFatal, char *format, ...) {
// This routine deals with the awful situation of trying to get info while the stderr handle is closed on purpose.
int iOldUMask;
int iFd = -1;
char chFile[1024];
if (!iFatal) {
// LSCRIU_Debugging();
if (!s_criu_debug) {
// Debugging message and debugging is off
return;
}
}
if (!LSCRIU_Error_File_Name(chFile, sizeof(chFile))) {
// We're done here...nowhere to write
return;
}
iOldUMask = umask(0);
iFd = open( chFile, O_WRONLY | O_APPEND | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
umask(iOldUMask);
if (iFd >= 0) {
char chFullMessage[0x1000];
struct timeb sTimeb;
struct tm sTm;
ftime(&sTimeb);
localtime_r(&sTimeb.time,&sTm);
va_list ap;
va_start(ap, format);
char buf[0x1000];
vsnprintf(buf, sizeof(buf), format, ap);
va_end(ap);
int n = snprintf(chFullMessage, sizeof(chFullMessage),
"%04d-%02d-%02d %02d:%02d:%02d.%03d: LSCRIU (%d): %s %s\n",
sTm.tm_year + 1900,
sTm.tm_mon + 1,
sTm.tm_mday,
sTm.tm_hour,
sTm.tm_min,
sTm.tm_sec,
sTimeb.millitm,
s_pid,
iFatal ? "FATAL! " : "(debug) ",
buf);
if (n > (int)sizeof(chFullMessage))
n = sizeof(chFullMessage);
write(iFd, chFullMessage, n);
close(iFd);
}
}
#else // no debugging
static inline void LSCRIU_Debugging(void) {}
static inline void LSCRIU_Restored_Error(int iFatal, char *format, ...) {}
#endif
static int LSCRIU_Native_Dump(pid_t iPid,
char *pchImagePath,
int iFdNative) {
criu_native_dump_t criu_native_dump;
char *pchLastSlash;
memset(&criu_native_dump, 0, sizeof(criu_native_dump));
criu_native_dump.m_iPidToDump = iPid;
strncpy(criu_native_dump.m_chImageDirectory, pchImagePath,
sizeof(criu_native_dump.m_chImageDirectory));
pchLastSlash = strrchr(criu_native_dump.m_chSocketDir,'/');
if (pchLastSlash) {
pchLastSlash++;
(*pchLastSlash) = 0;
}
lscriu_dbg("LSCRIU (%d): Sent the dump request to the listener\n", s_pid);
if (write(iFdNative,
&criu_native_dump,
sizeof(criu_native_dump)) == -1) {
lscriu_err("LSCRIU (%d): Error sending dump request to the listener: %s\n",
s_pid, strerror(errno));
return(-1);
}
return 0;
}
static void LSCRIU_CloudLinux_Checkpoint(void)
{
int iRet;
if ((!s_native) && (!s_lscapi_dump_me)) {
lscriu_dbg("LSCRIU (%d): Not native and unable to dump - abandon one-time "
"dump\n", s_pid);
return;
}
iRet = s_lscapi_dump_me();
if (iRet < 0) {
lscriu_err("LSCRIU: CloudLinux dump of PID: %d, error: %s\n",
s_pid, strerror(errno));
}
if (iRet == 0) {
// Dumped. To continue the child must send us the handles back
lscriu_err("LSCRIU: Successful CloudLinux dump of PID: %d\n", s_pid);
}
else {
s_restored = 1;
LSAPI_reset_server_state();
/*
Here we have restored the php process, so we should to tell (via
semaphore) mod_lsapi that we are started and ready to receive data.
*/
LSCRIU_Wink_Server_is_Ready();
lscriu_err("LSCRIU: Successful CloudLinux restore of PID: %d, parent: %d.\n",
getpid(), getppid());
}
LSCRIU_Set_Initial_Start_Reqs(0);
}
static void LSCRIU_Wait_Dump_Finish_Or_Restored(int pid_parent)
{
// Now get restored. We know if we're restored if the ppid changes!
// If we're dumped, we're killed (no use worrying about that!).
time_t iTimeStart = 0;
time_t iTimeNow;
int iRestored = 0;
do {
usleep(1000);
time(&iTimeNow);
if (!iTimeStart) {
iTimeStart = iTimeNow;
}
else if ((pid_parent != getppid()) ||
(iTimeNow - iTimeStart > 10)) {
iRestored = 1;
}
else if (iTimeNow - iTimeStart > 5) {
LSCRIU_Restored_Error(1, "Timed out waiting to be dumped");
exit(1);
}
} while (!iRestored);
}
static void LSCRIU_try_checkpoint(int *forked_pid)
{
int iRet;
pid_t iPid;
pid_t iPidDump = getpid();
if (s_tried_checkpoint) {
lscriu_dbg("LSCRIU (%d): Already tried checkpoint - one time per customer\n",
iPidDump);
return;
}
lscriu_dbg("LSCRIU (%d): Trying checkpoint\n", iPidDump);
s_tried_checkpoint = 1;
if (!s_native) {
LSCRIU_CloudLinux_Checkpoint();
return;
}
lscriu_dbg("LSCRIU (%d): fork!\n", iPidDump);
iPid = fork();
if (iPid < 0) {
lscriu_err("LSCRIU (%d): Can't checkpoint due to a fork error: %s\n",
iPidDump, strerror(errno));
return;
}
if (iPid == 0) {
pid_t iPidParent = getppid();
setsid();
iRet = LSCRIU_Native_Dump(iPidDump,
s_criu_image_path,
s_fd_native);
close(s_fd_native);
LSCRIU_Wait_Dump_Finish_Or_Restored(iPidParent);
LSCRIU_Restored_Error(0, "Restored!");
LSAPI_reset_server_state();
s_restored = 1;
}
else {
if (forked_pid)
*forked_pid = iPid;
}
LSCRIU_Set_Initial_Start_Reqs(0);
}
static int init_native_env(void)
{
char *pchFd;
pchFd = getenv("LSAPI_CRIU_SYNC_FD");
if (!pchFd)
pchFd = getenv("LSCAPI_CRIU_SYNC_FD");
const char *image_path;
image_path = getenv("LSAPI_CRIU_IMAGE_PATH");
if (!pchFd) {
lscriu_err("LSCRIU (%d): LSAPI_CRIU_SYNC_FD internal environment "
"variable not set - contact Litespeed tech support\n", getpid());
return -1;
}
if (!image_path) {
lscriu_err("LSCRIU (%d): LSAPI_CRIU_IMAGE_PATH internal environment "
"variable not set - contact Litespeed tech support\n", getpid());
return -1;
}
lscriu_dbg("LSCRIU (%d): Checkpoint dump. ImagePath: %s\n",
getpid(), image_path);
s_fd_native = atoi(pchFd);
lscriu_dbg("LSCRIU (%d): Native checkpoint. Use filepointer %d (%s) to send "
"pid %d\n", getpid(), s_fd_native, pchFd, iPidDump);
s_criu_image_path = strdup(image_path);
return 0;
}
static int LSCRIU_Init_Env_Parameters(void)
{
const char *p;
int n;
p = getenv("LSAPI_INITIAL_START");
if (!p)
p = getenv("LSAPI_BACKEND_INITIAL_START");
if (p) {
n = atoi(p);
if (n > 0) {
lscriu_dbg("LSCRIU (%d): Set start requests based on environment (%d)\n",
getpid(), n);
LSCRIU_Set_Initial_Start_Reqs(n);
} else {
lscriu_dbg("LSCRIU (%d): LSAPI_INITIAL_START set to 0 disabled\n",
getpid());
return 0;
}
} else {
lscriu_dbg("LSCRIU (%d): LSAPI_INITIAL_START NOT set - disabled\n",
getpid());
return 0;
}
if (LSAPI_Is_Listen()) {
lscriu_dbg("LSCRIU (%d): Listening...\n", getpid());
GlobalCounterType_t gc_type = CRIU_GCOUNTER_SHM;
char *env;
if ((env = getenv("LSAPI_CRIU_USE_SHM"))) {
// CloudLinux doc: Off (shared memory) or Signals.
// Litespeed doc: On (shared memory) or Signals
// So just check the first character for an 'S' and if not, then
// use shared memory. Pipe support is lost (sigh).
if ((*env == 'S') || (*env == 's'))
gc_type = CRIU_GCOUNTER_SIG; // Just assume the rest is signals
// else use the default of shared memory
}
else if ((env = getenv("LSAPI_SIGNALS"))) {
if ((*env == '1') ||
(*env == 'Y') ||
(*env == 'y') ||
(*env == 'T') ||
(*env == 't') ||
(((*env == 'O') || (*env == 'o')) &&
((*(env + 1) == 'N') || (*(env + 1) == 'n'))))
gc_type = CRIU_GCOUNTER_SIG;
else if (*env == 2)
gc_type = CRIU_GCOUNTER_PIPE; // The only case for pipe
//else use the default of shared memory
}
if (gc_type != CRIU_GCOUNTER_SHM) {
lscriu_dbg("LSCRIU (%d): Use %s\n", getpid(),
gc_type == CRIU_GCOUNTER_SIG ? "signals" : "pipe");
lsapi_criu_signal(SIGUSR2, lsapi_siguser2);
}
else {
lscriu_dbg("LSCRIU (%d): Use shared memory\n", getpid());
}
LSCRIU_Set_Global_Counter_Type(gc_type);
}
else {
lscriu_dbg("LSCRIU (%d): NOT Listening\n", getpid());
}
char *criu_mode = NULL;
criu_mode = getenv("LSAPI_CRIU");
// 0 disabled
// 1 cloudlinux
// 2 native
if (criu_mode) {
if (*criu_mode == '0') {
lscriu_dbg("LSCRIU (%d): Disabled by environment.\n", getpid());
LSCRIU_Set_Initial_Start_Reqs(0);
}
else if (*criu_mode == '2') {
lscriu_dbg("LSCRIU (%d): Disabled by environment.\n", getpid());
s_native = 1;
}
}
if (s_native && init_native_env() == -1)
LSCRIU_Set_Initial_Start_Reqs(0);
//unset_lsapi_envs();
return 0;
}
void LSCRIU_inc_req_processed()
{
if (!LSCRIU_Get_Global_Counter_Type()) {
++s_requests_count;
}
lscriu_dbg("LSCRIU (%d): s_requests_count %d counter %d\n", getpid(),
s_requests_count, s_initial_start_reqs);
if (s_initial_start_reqs > 0 && s_requests_count <= s_initial_start_reqs) {
if (LSCRIU_Get_Global_Counter_Type() == CRIU_GCOUNTER_SHM) {
LSCRIU_Increase_Global_Counter();
if (s_requests_count >= s_initial_start_reqs) {
//Maybe this time we can stop to send signal and wait for
//1 second of select timeout
//kill( LSCRIU_Get_ppid(), SIGUSR2 );
lscriu_dbg("LSCRIU (%d): Time to dump main process with semaphore\n",
getpid());
}
} else {
kill(LSAPI_Get_ppid(), SIGUSR2);
lscriu_dbg("LSCRIU (%d): Send kill to main process with signals\n",
getpid());
}
}
}
static void LSCRIU_on_timer(int *forked_pid)
{
lscriu_dbg("LSCRIU (%d): LSCRIU_on_timer\n", getpid());
if (LSCRIU_need_checkpoint()) {
LSCRIU_try_checkpoint(forked_pid);
}
}
int LSCRIU_Init(void)
{
s_pid = getpid();
LSCRIU_Debugging();
LSCRIU_Init_Env_Parameters();
if (s_initial_start_reqs && !s_native) {
if (LSCRIU_load_liblscapi() == -1)
s_initial_start_reqs = 0;
}
if (s_initial_start_reqs) {
LSCRIU_Wink_Server_is_Ready();
lscriu_dbg("LSCRIU (%d): LSAPI_Register_Pgrp_Timer_Callback\n", s_pid);
LSAPI_Register_Pgrp_Timer_Callback(LSCRIU_on_timer);
LSCRIU_Init_Global_Counter(0);
}
return s_initial_start_reqs > 0;
}
| 21,541 | 29.086592 | 118 |
c
|
php-src
|
php-src-master/sapi/litespeed/lscriu.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: George Wang <[email protected]> |
+----------------------------------------------------------------------+
*/
/*
Copyright (c) 2002-2018, Lite Speed Technologies Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the Lite Speed Technologies Inc nor the
names of its contributors may be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _LSCRIU_H_
#define _LSCRIU_H_
#if defined (c_plusplus) || defined (__cplusplus)
extern "C" {
#endif
// return 1 if CRIU is available, return 0 if CRIU is not available
int LSCRIU_Init(void);
void LSCRIU_inc_req_processed(void);
#if defined (c_plusplus) || defined (__cplusplus)
}
#endif
#endif // LSCRIU_
| 2,885 | 42.727273 | 75 |
h
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: 08e29f02953f23bfce6ce04f435227b4e5e61545 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_phpdbg_break_next, 0, 0, IS_VOID, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_phpdbg_break_file, 0, 2, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, file, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, line, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_phpdbg_break_method, 0, 2, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, class, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, method, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_phpdbg_break_function, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, function, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_phpdbg_color, 0, 2, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, element, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, color, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_phpdbg_prompt, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, string, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_phpdbg_exec, 0, 1, MAY_BE_STRING|MAY_BE_BOOL)
ZEND_ARG_TYPE_INFO(0, context, IS_STRING, 0)
ZEND_END_ARG_INFO()
#define arginfo_phpdbg_clear arginfo_phpdbg_break_next
#define arginfo_phpdbg_start_oplog arginfo_phpdbg_break_next
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_phpdbg_end_oplog, 0, 0, IS_ARRAY, 1)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 0, "[]")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_phpdbg_get_executable, 0, 0, IS_ARRAY, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 0, "[]")
ZEND_END_ARG_INFO()
ZEND_FUNCTION(phpdbg_break_next);
ZEND_FUNCTION(phpdbg_break_file);
ZEND_FUNCTION(phpdbg_break_method);
ZEND_FUNCTION(phpdbg_break_function);
ZEND_FUNCTION(phpdbg_color);
ZEND_FUNCTION(phpdbg_prompt);
ZEND_FUNCTION(phpdbg_exec);
ZEND_FUNCTION(phpdbg_clear);
ZEND_FUNCTION(phpdbg_start_oplog);
ZEND_FUNCTION(phpdbg_end_oplog);
ZEND_FUNCTION(phpdbg_get_executable);
static const zend_function_entry ext_functions[] = {
ZEND_FE(phpdbg_break_next, arginfo_phpdbg_break_next)
ZEND_FE(phpdbg_break_file, arginfo_phpdbg_break_file)
ZEND_FE(phpdbg_break_method, arginfo_phpdbg_break_method)
ZEND_FE(phpdbg_break_function, arginfo_phpdbg_break_function)
ZEND_FE(phpdbg_color, arginfo_phpdbg_color)
ZEND_FE(phpdbg_prompt, arginfo_phpdbg_prompt)
ZEND_FE(phpdbg_exec, arginfo_phpdbg_exec)
ZEND_FE(phpdbg_clear, arginfo_phpdbg_clear)
ZEND_FE(phpdbg_start_oplog, arginfo_phpdbg_start_oplog)
ZEND_FE(phpdbg_end_oplog, arginfo_phpdbg_end_oplog)
ZEND_FE(phpdbg_get_executable, arginfo_phpdbg_get_executable)
ZEND_FE_END
};
static void register_phpdbg_symbols(int module_number)
{
REGISTER_STRING_CONSTANT("PHPDBG_VERSION", PHPDBG_VERSION, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHPDBG_COLOR_PROMPT", PHPDBG_COLOR_PROMPT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHPDBG_COLOR_NOTICE", PHPDBG_COLOR_NOTICE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHPDBG_COLOR_ERROR", PHPDBG_COLOR_ERROR, CONST_PERSISTENT);
}
| 3,162 | 37.573171 | 93 |
h
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_break.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "phpdbg.h"
#include "phpdbg_print.h"
#include "phpdbg_utils.h"
#include "phpdbg_break.h"
#include "phpdbg_bp.h"
#include "phpdbg_prompt.h"
ZEND_EXTERN_MODULE_GLOBALS(phpdbg)
#define PHPDBG_BREAK_COMMAND_D(f, h, a, m, l, s, flags) \
PHPDBG_COMMAND_D_EXP(f, h, a, m, l, s, &phpdbg_prompt_commands[9], flags)
/**
* Commands
*/
const phpdbg_command_t phpdbg_break_commands[] = {
PHPDBG_BREAK_COMMAND_D(at, "specify breakpoint by location and condition", '@', break_at, NULL, "*c", 0),
PHPDBG_BREAK_COMMAND_D(del, "delete breakpoint by identifier number", '~', break_del, NULL, "n", 0),
PHPDBG_END_COMMAND
};
PHPDBG_BREAK(at) /* {{{ */
{
phpdbg_set_breakpoint_at(param);
return SUCCESS;
} /* }}} */
PHPDBG_BREAK(del) /* {{{ */
{
phpdbg_delete_breakpoint(param->num);
return SUCCESS;
} /* }}} */
| 2,014 | 37.018868 | 129 |
c
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_break.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHPDBG_BREAK_H
#define PHPDBG_BREAK_H
#include "TSRM.h"
#include "phpdbg_cmd.h"
#define PHPDBG_BREAK(name) PHPDBG_COMMAND(break_##name)
/**
* Printer Forward Declarations
*/
PHPDBG_BREAK(at);
PHPDBG_BREAK(del);
extern const phpdbg_command_t phpdbg_break_commands[];
#endif /* PHPDBG_BREAK_H */
| 1,456 | 39.472222 | 75 |
h
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_btree.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHPDBG_BTREE_H
#define PHPDBG_BTREE_H
#include "zend.h"
typedef struct {
zend_ulong idx;
void *ptr;
} phpdbg_btree_result;
typedef union _phpdbg_btree_branch phpdbg_btree_branch;
union _phpdbg_btree_branch {
phpdbg_btree_branch *branches[2];
phpdbg_btree_result result;
};
typedef struct {
zend_ulong count;
zend_ulong depth;
bool persistent;
phpdbg_btree_branch *branch;
} phpdbg_btree;
typedef struct {
phpdbg_btree *tree;
zend_ulong cur;
zend_ulong end;
} phpdbg_btree_position;
void phpdbg_btree_init(phpdbg_btree *tree, zend_ulong depth);
void phpdbg_btree_clean(phpdbg_btree *tree);
phpdbg_btree_result *phpdbg_btree_find(phpdbg_btree *tree, zend_ulong idx);
phpdbg_btree_result *phpdbg_btree_find_closest(phpdbg_btree *tree, zend_ulong idx);
phpdbg_btree_position phpdbg_btree_find_between(phpdbg_btree *tree, zend_ulong lower_idx, zend_ulong higher_idx);
phpdbg_btree_result *phpdbg_btree_next(phpdbg_btree_position *pos);
int phpdbg_btree_delete(phpdbg_btree *tree, zend_ulong idx);
#define PHPDBG_BTREE_INSERT 1
#define PHPDBG_BTREE_UPDATE 2
#define PHPDBG_BTREE_OVERWRITE (PHPDBG_BTREE_INSERT | PHPDBG_BTREE_UPDATE)
int phpdbg_btree_insert_or_update(phpdbg_btree *tree, zend_ulong idx, void *ptr, int flags);
#define phpdbg_btree_insert(tree, idx, ptr) phpdbg_btree_insert_or_update(tree, idx, ptr, PHPDBG_BTREE_INSERT)
#define phpdbg_btree_update(tree, idx, ptr) phpdbg_btree_insert_or_update(tree, idx, ptr, PHPDBG_BTREE_UPDATE)
#define phpdbg_btree_overwrite(tree, idx, ptr) phpdbg_btree_insert_or_update(tree, idx, ptr, PHPDBG_BTREE_OVERWRITE)
/* debugging functions */
void phpdbg_btree_branch_dump(phpdbg_btree_branch *branch, zend_ulong depth);
void phpdbg_btree_dump(phpdbg_btree *tree);
#endif
| 2,891 | 39.732394 | 116 |
h
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_frame.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "zend.h"
#include "phpdbg.h"
#include "phpdbg_utils.h"
#include "phpdbg_frame.h"
#include "phpdbg_list.h"
#include "zend_smart_str.h"
ZEND_EXTERN_MODULE_GLOBALS(phpdbg)
static inline void phpdbg_append_individual_arg(smart_str *s, uint32_t i, zend_function *func, zval *arg) {
const zend_arg_info *arginfo = func->common.arg_info;
char *arg_name = NULL;
if (i) {
smart_str_appends(s, ", ");
}
if (i < func->common.num_args) {
if (arginfo) {
if (func->type == ZEND_INTERNAL_FUNCTION) {
arg_name = (char *) ((zend_internal_arg_info *) &arginfo[i])->name;
} else {
arg_name = ZSTR_VAL(arginfo[i].name);
}
}
smart_str_appends(s, arg_name ? arg_name : "?");
smart_str_appendc(s, '=');
}
{
char *arg_print = phpdbg_short_zval_print(arg, 40);
smart_str_appends(s, arg_print);
efree(arg_print);
}
}
zend_string *phpdbg_compile_stackframe(zend_execute_data *ex) {
smart_str s = {0};
zend_op_array *op_array = &ex->func->op_array;
uint32_t i = 0, first_extra_arg = op_array->num_args, num_args = ZEND_CALL_NUM_ARGS(ex);
zval *p = ZEND_CALL_ARG(ex, 1);
if (op_array->scope) {
smart_str_append(&s, op_array->scope->name);
smart_str_appends(&s, "::");
}
smart_str_append(&s, op_array->function_name);
smart_str_appendc(&s, '(');
if (ZEND_CALL_NUM_ARGS(ex) > first_extra_arg) {
while (i < first_extra_arg) {
phpdbg_append_individual_arg(&s, i, ex->func, p);
p++;
i++;
}
p = ZEND_CALL_VAR_NUM(ex, op_array->last_var + op_array->T);
}
while (i < num_args) {
phpdbg_append_individual_arg(&s, i, ex->func, p);
p++;
i++;
}
smart_str_appendc(&s, ')');
if (ex->func->type == ZEND_USER_FUNCTION) {
smart_str_appends(&s, " at ");
smart_str_append(&s, op_array->filename);
smart_str_appendc(&s, ':');
smart_str_append_unsigned(&s, ex->opline->lineno);
} else {
smart_str_appends(&s, " [internal function]");
}
return s.s;
}
void phpdbg_print_cur_frame_info(void) {
const char *file_chr = zend_get_executed_filename();
zend_string *file = zend_string_init(file_chr, strlen(file_chr), 0);
phpdbg_list_file(file, 3, zend_get_executed_lineno() - 1, zend_get_executed_lineno());
efree(file);
}
void phpdbg_restore_frame(void) /* {{{ */
{
if (PHPDBG_FRAME(num) == 0) {
return;
}
if (PHPDBG_FRAME(generator)) {
if (PHPDBG_FRAME(generator)->execute_data->call) {
PHPDBG_FRAME(generator)->frozen_call_stack = zend_generator_freeze_call_stack(PHPDBG_FRAME(generator)->execute_data);
}
PHPDBG_FRAME(generator) = NULL;
}
PHPDBG_FRAME(num) = 0;
/* move things back */
EG(current_execute_data) = PHPDBG_FRAME(execute_data);
} /* }}} */
void phpdbg_switch_frame(int frame) /* {{{ */
{
zend_execute_data *execute_data = PHPDBG_FRAME(num) ? PHPDBG_FRAME(execute_data) : EG(current_execute_data);
int i = 0;
if (PHPDBG_FRAME(num) == frame) {
phpdbg_notice("Already in frame #%d", frame);
return;
}
phpdbg_try_access {
while (execute_data) {
if (i++ == frame) {
break;
}
do {
execute_data = execute_data->prev_execute_data;
} while (execute_data && execute_data->opline == NULL);
}
} phpdbg_catch_access {
phpdbg_error("Couldn't switch frames, invalid data source");
return;
} phpdbg_end_try_access();
if (execute_data == NULL) {
phpdbg_error("No frame #%d", frame);
return;
}
phpdbg_restore_frame();
if (frame > 0) {
PHPDBG_FRAME(num) = frame;
/* backup things and jump back */
PHPDBG_FRAME(execute_data) = EG(current_execute_data);
EG(current_execute_data) = execute_data;
}
phpdbg_try_access {
zend_string *s = phpdbg_compile_stackframe(EG(current_execute_data));
phpdbg_notice("Switched to frame #%d: %.*s", frame, (int) ZSTR_LEN(s), ZSTR_VAL(s));
zend_string_release(s);
} phpdbg_catch_access {
phpdbg_notice("Switched to frame #%d", frame);
} phpdbg_end_try_access();
phpdbg_print_cur_frame_info();
} /* }}} */
static void phpdbg_dump_prototype(zval *tmp) /* {{{ */
{
zval *funcname, *class, class_zv, *args, *argstmp;
funcname = zend_hash_find(Z_ARRVAL_P(tmp), ZSTR_KNOWN(ZEND_STR_FUNCTION));
if ((class = zend_hash_find(Z_ARRVAL_P(tmp), ZSTR_KNOWN(ZEND_STR_OBJECT)))) {
ZVAL_NEW_STR(&class_zv, Z_OBJCE_P(class)->name);
class = &class_zv;
} else {
class = zend_hash_find(Z_ARRVAL_P(tmp), ZSTR_KNOWN(ZEND_STR_CLASS));
}
if (class) {
zval *type = zend_hash_find(Z_ARRVAL_P(tmp), ZSTR_KNOWN(ZEND_STR_TYPE));
phpdbg_out("%s%s%s(", Z_STRVAL_P(class), Z_STRVAL_P(type), Z_STRVAL_P(funcname));
} else {
phpdbg_out("%s(", Z_STRVAL_P(funcname));
}
args = zend_hash_find(Z_ARRVAL_P(tmp), ZSTR_KNOWN(ZEND_STR_ARGS));
if (args) {
const zend_function *func = NULL;
const zend_arg_info *arginfo = NULL;
bool is_variadic = 0;
int j = 0, m;
phpdbg_try_access {
/* assuming no autoloader call is necessary, class should have been loaded if it's in backtrace ... */
if ((func = phpdbg_get_function(Z_STRVAL_P(funcname), class ? Z_STRVAL_P(class) : NULL))) {
arginfo = func->common.arg_info;
}
} phpdbg_end_try_access();
m = func ? func->common.num_args : 0;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(args), argstmp) {
if (j) {
phpdbg_out(", ");
}
if (m && j < m) {
char *arg_name = NULL;
if (arginfo) {
if (func->type == ZEND_INTERNAL_FUNCTION) {
arg_name = (char *)((zend_internal_arg_info *)&arginfo[j])->name;
} else {
arg_name = ZSTR_VAL(arginfo[j].name);
}
}
if (!is_variadic) {
is_variadic = arginfo ? ZEND_ARG_IS_VARIADIC(&arginfo[j]) : 0;
}
phpdbg_out("%s=%s", arg_name ? arg_name : "?", is_variadic ? "[": "");
}
++j;
{
char *arg_print = phpdbg_short_zval_print(argstmp, 40);
php_printf("%s", arg_print);
efree(arg_print);
}
} ZEND_HASH_FOREACH_END();
if (is_variadic) {
phpdbg_out("]");
}
}
phpdbg_out(")");
}
void phpdbg_dump_backtrace(size_t num) /* {{{ */
{
HashPosition position;
zval zbacktrace;
zval *tmp;
zval startline, startfile;
const char *startfilename;
zval *file = &startfile, *line = &startline;
int i = 0, limit = num;
PHPDBG_OUTPUT_BACKUP();
if (limit < 0) {
phpdbg_error("Invalid backtrace size %d", limit);
PHPDBG_OUTPUT_BACKUP_RESTORE();
return;
}
phpdbg_try_access {
zend_fetch_debug_backtrace(&zbacktrace, 0, 0, limit);
} phpdbg_catch_access {
phpdbg_error("Couldn't fetch backtrace, invalid data source");
return;
} phpdbg_end_try_access();
Z_LVAL(startline) = zend_get_executed_lineno();
startfilename = zend_get_executed_filename();
Z_STR(startfile) = zend_string_init(startfilename, strlen(startfilename), 0);
zend_hash_internal_pointer_reset_ex(Z_ARRVAL(zbacktrace), &position);
tmp = zend_hash_get_current_data_ex(Z_ARRVAL(zbacktrace), &position);
while ((tmp = zend_hash_get_current_data_ex(Z_ARRVAL(zbacktrace), &position))) {
if (file) { /* userland */
phpdbg_out("frame #%d: ", i);
phpdbg_dump_prototype(tmp);
phpdbg_out(" at %s:"ZEND_LONG_FMT"\n", Z_STRVAL_P(file), Z_LVAL_P(line));
i++;
} else {
phpdbg_out(" => ");
phpdbg_dump_prototype(tmp);
phpdbg_out(" (internal function)\n");
}
file = zend_hash_find(Z_ARRVAL_P(tmp), ZSTR_KNOWN(ZEND_STR_FILE));
line = zend_hash_find(Z_ARRVAL_P(tmp), ZSTR_KNOWN(ZEND_STR_LINE));
zend_hash_move_forward_ex(Z_ARRVAL(zbacktrace), &position);
}
phpdbg_writeln("frame #%d: {main} at %s:"ZEND_LONG_FMT, i, Z_STRVAL_P(file), Z_LVAL_P(line));
zval_ptr_dtor_nogc(&zbacktrace);
zend_string_release(Z_STR(startfile));
PHPDBG_OUTPUT_BACKUP_RESTORE();
} /* }}} */
void phpdbg_open_generator_frame(zend_generator *gen) {
zend_string *s;
if (EG(current_execute_data) == gen->execute_data) {
return;
}
phpdbg_restore_frame();
PHPDBG_FRAME(num) = -1;
PHPDBG_FRAME(generator) = gen;
EG(current_execute_data) = gen->execute_data;
if (gen->frozen_call_stack) {
zend_generator_restore_call_stack(gen);
}
gen->execute_data->prev_execute_data = NULL;
s = phpdbg_compile_stackframe(EG(current_execute_data));
phpdbg_notice("Switched to generator with handle #%d: %.*s", gen->std.handle, (int) ZSTR_LEN(s), ZSTR_VAL(s));
zend_string_release(s);
phpdbg_print_cur_frame_info();
}
| 9,310 | 27.56135 | 120 |
c
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_frame.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHPDBG_FRAME_H
#define PHPDBG_FRAME_H
#include "TSRM.h"
zend_string *phpdbg_compile_stackframe(zend_execute_data *);
void phpdbg_restore_frame(void);
void phpdbg_switch_frame(int);
void phpdbg_dump_backtrace(size_t);
void phpdbg_open_generator_frame(zend_generator *);
#endif /* PHPDBG_FRAME_H */
| 1,455 | 45.967742 | 75 |
h
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_help.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHPDBG_HELP_H
#define PHPDBG_HELP_H
#include "TSRM.h"
#include "phpdbg.h"
#include "phpdbg_cmd.h"
#define PHPDBG_HELP(name) PHPDBG_COMMAND(help_##name)
/**
* Helper Forward Declarations
*/
PHPDBG_HELP(aliases);
extern const phpdbg_command_t phpdbg_help_commands[];
#define phpdbg_help_header() \
phpdbg_notice("version", "version=\"%s\"", "Welcome to phpdbg, the interactive PHP debugger, v%s", PHPDBG_VERSION);
#define phpdbg_help_footer() \
phpdbg_notice("issues", "url=\"%s\"", "Please report bugs to <%s>", PHPDBG_ISSUES);
typedef struct _phpdbg_help_text_t {
char *key;
char *text;
} phpdbg_help_text_t;
extern const phpdbg_help_text_t phpdbg_help_text[];
extern void phpdbg_do_help_cmd(const char *type);
#endif /* PHPDBG_HELP_H */
| 1,907 | 37.938776 | 116 |
h
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_info.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <[email protected]> |
| Authors: Joe Watkins <[email protected]> |
| Authors: Bob Weinand <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHPDBG_INFO_H
#define PHPDBG_INFO_H
#include "phpdbg_cmd.h"
#define PHPDBG_INFO(name) PHPDBG_COMMAND(info_##name)
PHPDBG_INFO(files);
PHPDBG_INFO(break);
PHPDBG_INFO(classes);
PHPDBG_INFO(funcs);
PHPDBG_INFO(error);
PHPDBG_INFO(constants);
PHPDBG_INFO(vars);
PHPDBG_INFO(globals);
PHPDBG_INFO(literal);
PHPDBG_INFO(memory);
extern const phpdbg_command_t phpdbg_info_commands[];
#endif /* PHPDBG_INFO_H */
| 1,565 | 38.15 | 75 |
h
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_io.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Anatol Belski <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phpdbg_io.h"
ZEND_EXTERN_MODULE_GLOBALS(phpdbg)
/* is easy to generalize ... but not needed for now */
PHPDBG_API int phpdbg_consume_stdin_line(char *buf) {
int bytes = PHPDBG_G(input_buflen), len = 0;
if (PHPDBG_G(input_buflen)) {
memcpy(buf, PHPDBG_G(input_buffer), bytes);
}
PHPDBG_G(last_was_newline) = 1;
do {
int i;
if (bytes <= 0) {
continue;
}
for (i = len; i < len + bytes; i++) {
if (buf[i] == '\x03') {
if (i != len + bytes - 1) {
memmove(buf + i, buf + i + 1, len + bytes - i - 1);
}
len--;
i--;
continue;
}
if (buf[i] == '\n') {
PHPDBG_G(input_buflen) = len + bytes - 1 - i;
if (PHPDBG_G(input_buflen)) {
memcpy(PHPDBG_G(input_buffer), buf + i + 1, PHPDBG_G(input_buflen));
}
if (i != PHPDBG_MAX_CMD - 1) {
buf[i + 1] = 0;
}
return i;
}
}
len += bytes;
} while ((bytes = phpdbg_mixed_read(PHPDBG_G(io)[PHPDBG_STDIN].fd, buf + len, PHPDBG_MAX_CMD - len, -1)) > 0);
if (bytes <= 0) {
PHPDBG_G(flags) |= PHPDBG_IS_QUITTING;
zend_bailout();
}
return bytes;
}
PHPDBG_API int phpdbg_mixed_read(int fd, char *ptr, int len, int tmo) {
int ret;
do {
ret = read(fd, ptr, len);
} while (ret == -1 && errno == EINTR);
return ret;
}
static int phpdbg_output_pager(int fd, const char *ptr, int len) {
int count = 0, bytes = 0;
const char *p = ptr, *endp = ptr + len;
while ((p = memchr(p, '\n', endp - p))) {
count++;
p++;
if (count % PHPDBG_G(lines) == 0) {
bytes += write(fd, ptr + bytes, (p - ptr) - bytes);
if (memchr(p, '\n', endp - p)) {
char buf[PHPDBG_MAX_CMD];
zend_quiet_write(fd, ZEND_STRL("\r---Type <return> to continue or q <return> to quit---"));
phpdbg_consume_stdin_line(buf);
if (*buf == 'q') {
break;
}
zend_quiet_write(fd, "\r", 1);
} else break;
}
}
if (bytes && count % PHPDBG_G(lines) != 0) {
bytes += write(fd, ptr + bytes, len - bytes);
} else if (!bytes) {
bytes += write(fd, ptr, len);
}
return bytes;
}
PHPDBG_API int phpdbg_mixed_write(int fd, const char *ptr, int len) {
if ((PHPDBG_G(flags) & PHPDBG_HAS_PAGINATION)
&& PHPDBG_G(io)[PHPDBG_STDOUT].fd == fd
&& PHPDBG_G(lines) > 0) {
return phpdbg_output_pager(fd, ptr, len);
}
return write(fd, ptr, len);
}
| 3,332 | 26.319672 | 111 |
c
|
php-src
|
php-src-master/sapi/phpdbg/phpdbg_io.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Anatol Belski <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHPDBG_IO_H
#define PHPDBG_IO_H
#include "phpdbg.h"
PHPDBG_API int phpdbg_consume_stdin_line(char *buf);
PHPDBG_API int phpdbg_mixed_read(int fd, char *ptr, int len, int tmo);
PHPDBG_API int phpdbg_mixed_write(int fd, const char *ptr, int len);
#endif /* PHPDBG_IO_H */
| 1,277 | 44.642857 | 75 |
h
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.