Milestone 5: deliver embedded RDP sessions and lifecycle hardening

This commit is contained in:
Keith Smith
2026-03-03 18:59:26 -07:00
parent 230a401386
commit 36006bd4aa
2941 changed files with 724359 additions and 77 deletions

390
third_party/FreeRDP/winpr/CMakeLists.txt vendored Normal file
View File

@@ -0,0 +1,390 @@
# WinPR: Windows Portable Runtime
# winpr cmake build script
#
# Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Include our extra modules
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../cmake/)
if(NOT FREERDP_UNIFIED_BUILD)
cmake_minimum_required(VERSION 3.13)
if(POLICY CMP0091)
cmake_policy(SET CMP0091 NEW)
endif()
project(WinPR LANGUAGES C)
include(ProjectCStandard)
include(CommonConfigOptions)
include(ConfigOptions)
# Enable coverity related pragma definitions
if(COVERITY_BUILD)
add_compile_definitions(COVERITY_BUILD)
endif()
# Default to build shared libs
include(ExportAllSymbols)
if(WITH_DEBUG_ALL)
message(
WARNING
"WITH_DEBUG_ALL=ON, the build will be slow and might leak sensitive information, do not use with release builds!"
)
set(DEFAULT_DEBUG_OPTION "ON" CACHE INTERNAL "debug default")
else()
set(DEFAULT_DEBUG_OPTION "OFF" CACHE INTERNAL "debug default")
endif()
# MSVC compatibility with system headers
add_compile_definitions(NONAMELESSUNION)
endif()
set(WINPR_PC_REQUIRES_PRIVATE "" CACHE INTERNAL "dependencies")
macro(winpr_pc_add_requires_private)
foreach(_lib ${ARGN})
list(APPEND WINPR_PC_REQUIRES_PRIVATE ${_lib})
endforeach()
set(WINPR_PC_REQUIRES_PRIVATE ${WINPR_PC_REQUIRES_PRIVATE} CACHE INTERNAL "dependencies")
endmacro()
if(WIN32 AND NOT UWP)
set(NATIVE_SSPI ON)
endif()
if((NOT ANDROID AND NOT IOS AND NOT UWP) AND NOT WITH_MBEDTLS)
set(TOOLS_DEFAULT ON)
else()
set(TOOLS_DEFAULT OFF)
endif()
if(WITH_MBEDTLS)
set(WITH_INTERNAL_RC4_DEFAULT ON)
set(WITH_INTERNAL_MD4_DEFAULT ON)
set(WITH_INTERNAL_MD5_DEFAULT OFF)
else()
set(WITH_INTERNAL_RC4_DEFAULT OFF)
set(WITH_INTERNAL_MD4_DEFAULT OFF)
set(WITH_INTERNAL_MD5_DEFAULT OFF)
endif()
option(WITH_WINPR_TOOLS "Build WinPR helper binaries" ${TOOLS_DEFAULT})
option(WITH_WINPR_DEPRECATED "Build WinPR deprecated symbols" OFF)
option(WITH_DEBUG_THREADS "Print thread debug messages, enables handle dump" ${DEFAULT_DEBUG_OPTION})
option(WITH_DEBUG_EVENTS "Print event debug messages, enables handle dump" ${DEFAULT_DEBUG_OPTION})
option(WITH_DEBUG_SYMBOLS "Pack debug symbols to installer" OFF)
option(WITH_NATIVE_SSPI "Use native SSPI modules" ${NATIVE_SSPI})
option(WITH_SMARTCARD_INSPECT "Enable SmartCard API Inspector" OFF)
option(WITH_DEBUG_MUTEX "Print mutex debug messages" ${DEFAULT_DEBUG_OPTION})
option(WITH_INTERNAL_RC4 "Use compiled in rc4 functions instead of OpenSSL/MBedTLS" ${WITH_INTERNAL_RC4_DEFAULT})
option(WITH_INTERNAL_MD4 "Use compiled in md4 hash functions instead of OpenSSL/MBedTLS" ${WITH_INTERNAL_MD4_DEFAULT})
option(WITH_INTERNAL_MD5 "Use compiled in md5 hash functions instead of OpenSSL/MBedTLS" ${WITH_INTERNAL_MD5_DEFAULT})
option(WITH_UNICODE_BUILTIN "Use built-in Unicode conversion (don't use system-provided libraries)" OFF)
option(WINPR_USE_LEGACY_RESOURCE_DIR "use a resource directory of <base>/WinPR instead of <base>/<product>" ON)
option(WINPR_USE_VENDOR_PRODUCT_CONFIG_DIR
"use a configuration <base>/<product>/<vendor>/ subdirectory instead of </base>/winpr" OFF
)
# This option MUST be off to avoid symbol conflicts when loading an external SSPI module library
option(SSPI_DLL "Define and export SSPI API symbols for usage as a Windows SSPI DLL replacement" OFF)
if(SSPI_DLL)
add_compile_definitions("SSPI_DLL")
endif()
option(WITH_DEBUG_NTLM "Print NTLM debug messages" ${DEFAULT_DEBUG_OPTION})
if(WITH_DEBUG_NTLM)
message(WARNING "WITH_DEBUG_NTLM=ON, the build might leak sensitive information, do not use with release builds!")
endif()
option(WITH_DEBUG_NLA "Print authentication related debug messages." ${DEFAULT_DEBUG_OPTION})
if(WITH_DEBUG_NLA)
message(WARNING "WITH_DEBUG_NLA=ON, the build might leak sensitive information, do not use with release builds!")
endif()
if(WITH_WINPR_DEPRECATED)
add_compile_definitions(WITH_WINPR_DEPRECATED)
endif()
# Include cmake modules
include(CheckIncludeFiles)
include(CheckLibraryExists)
include(CheckSymbolExists)
include(CheckStructHasMember)
include(TestBigEndian)
# Check for cmake compatibility (enable/disable features)
include(CheckCmakeCompat)
include(FindFeature)
include(FeatureSummary)
include(CheckCCompilerFlag)
include(InstallFreeRDPMan)
include(SetFreeRDPCMakeInstallDir)
include(CMakePackageConfigHelpers)
if(NOT WIN32)
add_compile_definitions(WINPR_CRITICAL_SECTION_DISABLE_SPINCOUNT)
endif()
# Soname versioning
include(GetProjectVersion)
get_project_version(WINPR_VERSION_MAJOR WINPR_VERSION_MINOR WINPR_VERSION_REVISION WINPR_VERSION_SUFFIX GIT_REVISION)
set(WINPR_VERSION "${WINPR_VERSION_MAJOR}.${WINPR_VERSION_MINOR}.${WINPR_VERSION_REVISION}")
set(WINPR_API_VERSION "${WINPR_VERSION_MAJOR}")
if(WINPR_VERSION_SUFFIX)
set(WINPR_VERSION_FULL "${WINPR_VERSION}-${WINPR_VERSION_SUFFIX}")
else()
set(WINPR_VERSION_FULL "${WINPR_VERSION}")
endif()
set(WINPR_RESOURCE_ROOT ${CMAKE_INSTALL_FULL_DATAROOTDIR})
# Quite the compatibility show here (newest to oldest):
# * <base>[/<vendor>]/<product>[<version>]
# * <base>[/<vendor>]/WinPR[<version>]
# * <base>/winpr
if(WINPR_USE_LEGACY_RESOURCE_DIR)
string(APPEND WINPR_RESOURCE_ROOT "/WinPR")
else()
if(WINPR_USE_VENDOR_PRODUCT_CONFIG_DIR)
string(APPEND WINPR_RESOURCE_ROOT "/${VENDOR}/")
endif()
string(APPEND WINPR_RESOURCE_ROOT "/${PRODUCT}")
if(WITH_RESOURCE_VERSIONING)
string(APPEND WINPR_RESOURCE_ROOT "${WINPR_VERSION_MAJOR}")
endif()
endif()
include(CheckTypeSize)
set(CMAKE_EXTRA_INCLUDE_FILES "sys/types.h")
check_type_size(ssize_t SSIZE_T)
set(CMAKE_EXTRA_INCLUDE_FILES "BaseTsd.h")
check_type_size(SSIZE_T WIN_SSIZE_T)
set(WINPR_HAVE_SSIZE_T ${HAVE_SSIZE_T})
set(WINPR_HAVE_WIN_SSIZE_T ${HAVE_WIN_SSIZE_T})
check_symbol_exists(strndup string.h WINPR_HAVE_STRNDUP)
check_include_files(unistd.h WINPR_HAVE_UNISTD_H)
check_include_files(execinfo.h WINPR_HAVE_EXECINFO_HEADER)
if(WINPR_HAVE_EXECINFO_HEADER)
check_symbol_exists(backtrace execinfo.h WINPR_HAVE_EXECINFO_BACKTRACE)
check_symbol_exists(backtrace_symbols execinfo.h WINPR_HAVE_EXECINFO_BACKTRACE_SYMBOLS)
check_symbol_exists(backtrace_symbols_fd execinfo.h WINPR_HAVE_EXECINFO_BACKTRACE_SYMBOLS_FD)
# Some implementations (e.g. Android NDK API < 33) provide execinfo.h but do not define
# the backtrace functions. Disable detection for these cases
if(WINPR_HAVE_EXECINFO_BACKTRACE AND WINPR_HAVE_EXECINFO_BACKTRACE_SYMBOLS
AND WINPR_HAVE_EXECINFO_BACKTRACE_SYMBOLS_FD
)
set(WINPR_HAVE_EXECINFO_H ON)
endif()
endif()
check_include_files(stdint.h WINPR_HAVE_STDINT_H)
check_include_files(inttypes.h WINPR_HAVE_INTTYPES_H)
check_include_files(stdbool.h WINPR_HAVE_STDBOOL_H)
if(NOT WINPR_HAVE_INTTYPES_H OR NOT WINPR_HAVE_STDINT_H OR NOT WINPR_HAVE_STDBOOL_H)
message(FATAL_ERROR "c11 headers stdint.h, stdbool.h and inttypes.h are required, giving up")
endif()
set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
if(NOT IOS)
find_package(Threads REQUIRED)
endif()
# Include files
if(NOT IOS)
check_include_files(fcntl.h WINPR_HAVE_FCNTL_H)
check_include_files(aio.h WINPR_HAVE_AIO_H)
check_include_files(sys/timerfd.h WINPR_HAVE_SYS_TIMERFD_H)
check_include_files(unistd.h WINPR_HAVE_UNISTD_H)
check_include_files(inttypes.h WINPR_HAVE_INTTYPES_H)
check_include_files(sys/filio.h WINPR_HAVE_SYS_FILIO_H)
check_include_files(sys/sockio.h WINPR_HAVE_SYS_SOCKIO_H)
check_include_files(syslog.h WINPR_HAVE_SYSLOG_H)
check_include_files(sys/select.h WINPR_HAVE_SYS_SELECT_H)
check_include_files(sys/eventfd.h WINPR_HAVE_SYS_EVENTFD_H)
check_include_files(unwind.h WINPR_HAVE_UNWIND_H)
if(WINPR_HAVE_SYS_EVENTFD_H)
check_symbol_exists(eventfd_read sys/eventfd.h WITH_EVENTFD_READ_WRITE)
endif()
include(CheckFunctionExists)
check_function_exists(strerror_r WINPR_HAVE_STRERROR_R)
check_function_exists(getlogin_r WINPR_HAVE_GETLOGIN_R)
check_function_exists(getpwuid_r WINPR_HAVE_GETPWUID_R)
check_struct_has_member("struct tm" tm_gmtoff time.h WINPR_HAVE_TM_GMTOFF)
else()
set(WINPR_HAVE_FCNTL_H 1)
set(WINPR_HAVE_UNISTD_H 1)
set(WINPR_HAVE_INTTYPES_H 1)
set(WINPR_HAVE_SYS_FILIO_H 1)
set(WINPR_HAVE_TM_GMTOFF 1)
endif()
if(UNIX OR CYGWIN)
if(FREEBSD)
list(APPEND CMAKE_REQUIRED_INCLUDES ${EPOLLSHIM_INCLUDE_DIR})
endif()
if(FREEBSD)
list(REMOVE_ITEM CMAKE_REQUIRED_INCLUDES ${EPOLLSHIM_INCLUDE_DIR})
endif()
option(WITH_POLL "Check for and include poll.h" ON)
if(WITH_POLL)
check_include_files(poll.h WINPR_HAVE_POLL_H)
endif()
endif()
if(NOT WIN32 AND NOT IOS)
if(NOT WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK_LIB)
check_library_exists(pthreads pthread_mutex_timedlock "" WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK_LIBS)
endif(NOT WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK_LIB)
if(NOT WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK_SYMBOL)
check_library_exists(pthread pthread_mutex_timedlock "" WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK_LIB)
endif(NOT WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK_SYMBOL)
list(APPEND CMAKE_REQUIRED_LIBRARIES pthread)
check_symbol_exists(pthread_mutex_timedlock pthread.h WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK_SYMBOL)
if(WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK_SYMBOL OR WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK_LIB
OR WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK_LIBS
)
set(WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK ON)
endif(WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK_SYMBOL OR WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK_LIB
OR WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK_LIBS
)
list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES pthread)
endif()
set(OPENSSL_FEATURE_TYPE "RECOMMENDED")
set(OPENSSL_FEATURE_PURPOSE "cryptography")
set(OPENSSL_FEATURE_DESCRIPTION "encryption, certificate validation, hashing functions")
set(MBEDTLS_FEATURE_TYPE "OPTIONAL")
set(MBEDTLS_FEATURE_PURPOSE "cryptography")
set(MBEDTLS_FEATURE_DESCRIPTION "encryption, certificate validation, hashing functions")
option(WITH_LIBRESSL "build with LibreSSL" OFF)
if(WITH_LIBRESSL)
find_package(LibreSSL REQUIRED)
set(OPENSSL_INCLUDE_DIR ${LIBRESSL_INCLUDE_DIR})
set(OPENSSL_LIBRARIES ${LIBRESSL_LIBRARIES})
set(OPENSSL_CRYPTO_LIBRARIES ${LIBRESSL_LIBRARIES})
set(WITH_OPENSSL ON)
set(OPENSSL_FOUND ON)
add_compile_definitions("WITH_LIBRESSL")
add_compile_definitions("WITH_OPENSSL")
else()
find_feature(OpenSSL ${OPENSSL_FEATURE_TYPE} ${OPENSSL_FEATURE_PURPOSE} ${OPENSSL_FEATURE_DESCRIPTION})
find_feature(MbedTLS ${MBEDTLS_FEATURE_TYPE} ${MBEDTLS_FEATURE_PURPOSE} ${MBEDTLS_FEATURE_DESCRIPTION})
endif()
if(NOT OPENSSL_FOUND AND NOT MBEDTLS_FOUND AND NOT LibreSSL_FOUND)
message(FATAL_ERROR "OpenSSL or MBedTLS are required, none enabled/found")
endif()
if(WITH_OPENSSL AND OPENSSL_FOUND)
add_compile_definitions("WITH_OPENSSL")
winpr_pc_add_requires_private("libssl")
endif()
if(WITH_MBEDTLS AND MBEDTLS_FOUND)
add_compile_definitions("WITH_MBEDTLS")
endif()
enable_testing()
if(MSVC)
set(TESTING_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
else()
set(TESTING_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/Testing")
endif()
if(NOT WIN32 AND NOT IOS AND NOT ANDROID)
set(PKCS11_DEFAULT ON)
else()
set(PKCS11_DEFAULT OFF)
endif()
option(WITH_PKCS11 "encryption, certificate validation, hashing functions" ${PKCS11_DEFAULT})
if(WITH_PKCS11)
add_compile_definitions("WITH_PKCS11")
endif()
if(BUILD_SHARED_LIBS)
add_compile_definitions(WINPR_DLL)
endif()
add_compile_definitions(WINPR_EXPORTS)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/include)
set(WINPR_INCLUDE_DIR "include/winpr${WINPR_VERSION_MAJOR}")
add_subdirectory(libwinpr)
list(REMOVE_DUPLICATES WINPR_PC_REQUIRES_PRIVATE)
list(JOIN WINPR_PC_REQUIRES_PRIVATE " " WINPR_PC_REQUIRES_PRIVATE)
set(WINPR_PC_LIBRARY_PRIVATE "-ldl -lrt -lm -lpthread")
# Do not set Requires.Private if not a static build
if(BUILD_SHARED_LIBS)
set(WINPR_PC_REQUIRES_PRIVATE "")
set(WINPR_PC_LIBRARY_PRIVATE "")
endif()
if(WITH_WINPR_TOOLS)
add_subdirectory(tools)
endif()
if(BUILD_TESTING_INTERNAL OR BUILD_TESTING)
add_subdirectory(test)
endif()
add_subdirectory(include)
generate_and_install_freerdp_man_from_template("wlog" "7" "${WINPR_API_VERSION}")
# Exporting
export(PACKAGE winpr)
setfreerdpcmakeinstalldir(WINPR_CMAKE_INSTALL_DIR "WinPR${WINPR_VERSION_MAJOR}")
configure_package_config_file(
WinPRConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/WinPRConfig.cmake INSTALL_DESTINATION ${WINPR_CMAKE_INSTALL_DIR}
PATH_VARS WINPR_INCLUDE_DIR
)
write_basic_package_version_file(
${CMAKE_CURRENT_BINARY_DIR}/WinPRConfigVersion.cmake VERSION ${WINPR_VERSION} COMPATIBILITY SameMajorVersion
)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/WinPRConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/WinPRConfigVersion.cmake
DESTINATION ${WINPR_CMAKE_INSTALL_DIR}
)
install(EXPORT WinPRTargets DESTINATION ${WINPR_CMAKE_INSTALL_DIR})
include(pkg-config-install-prefix)
cleaning_configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/winpr.pc.in ${CMAKE_CURRENT_BINARY_DIR}/winpr${WINPR_VERSION_MAJOR}.pc @ONLY
)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/winpr${WINPR_VERSION_MAJOR}.pc DESTINATION ${PKG_CONFIG_PC_INSTALL_DIR})

View File

@@ -0,0 +1,26 @@
include(CMakeFindDependencyMacro)
if(NOT "@BUILD_SHARED_LIBS@")
if(NOT "@WITH_JSON_DISABLED@")
if("@JSONC_FOUND@" AND NOT "@WITH_CJSON_REQUIRED@")
find_dependency(JSONC)
elseif("@CJSON_FOUND@")
find_dependency(cJSON)
endif()
endif()
if("@WITH_URIPARSER@")
find_dependency(uriparser)
endif()
endif()
@PACKAGE_INIT@
set(WinPR_VERSION_MAJOR "@WINPR_VERSION_MAJOR@")
set(WinPR_VERSION_MINOR "@WINPR_VERSION_MINOR@")
set(WinPR_VERSION_REVISION "@WINPR_VERSION_REVISION@")
set(WITH_WINPR_JSON "@WITH_WINPR_JSON@")
set_and_check(WinPR_INCLUDE_DIR "@PACKAGE_WINPR_INCLUDE_DIR@")
include("${CMAKE_CURRENT_LIST_DIR}/WinPRTargets.cmake")

View File

@@ -0,0 +1,44 @@
# WinPR: Windows Portable Runtime
# winpr cmake build script
#
# Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cleaning_configure_file(config/version.h.in ${CMAKE_CURRENT_BINARY_DIR}/winpr/version.h)
cleaning_configure_file(config/build-config.h.in ${CMAKE_CURRENT_BINARY_DIR}/winpr/build-config.h)
cleaning_configure_file(config/buildflags.h.in ${CMAKE_CURRENT_BINARY_DIR}/winpr/buildflags.h)
cleaning_configure_file(config/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/winpr/config.h)
file(GLOB_RECURSE WINPR_PUBLIC_COMMON_HEADERS LIST_DIRECTORIES false "winpr/*.h")
set(WINPR_PUBLIC_TOOLS_HEADERS ${WINPR_PUBLIC_COMMON_HEADERS})
list(FILTER WINPR_PUBLIC_TOOLS_HEADERS INCLUDE REGEX ".*winpr/tools.*")
list(FILTER WINPR_PUBLIC_COMMON_HEADERS EXCLUDE REGEX ".*winpr/tools.*")
file(GLOB_RECURSE WINPR_PUBLIC_COMMON_BIN_HEADERS LIST_DIRECTORIES false "${CMAKE_CURRENT_BINARY_DIR}/*.h")
list(APPEND WINPR_PUBLIC_COMMON_HEADERS ${WINPR_PUBLIC_COMMON_BIN_HEADERS})
list(SORT WINPR_PUBLIC_COMMON_HEADERS)
set_property(TARGET winpr APPEND PROPERTY SOURCES ${WINPR_PUBLIC_COMMON_HEADERS})
if(WITH_WINPR_TOOLS)
set_property(TARGET winpr-tools APPEND PROPERTY SOURCES ${WINPR_PUBLIC_TOOLS_HEADERS})
endif()
add_library(winpr-headers INTERFACE)
target_sources(winpr-headers INTERFACE ${WINPR_PUBLIC_COMMON_HEADERS})
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/winpr DESTINATION ${WINPR_INCLUDE_DIR} FILES_MATCHING PATTERN "*.h")
install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/winpr DESTINATION ${WINPR_INCLUDE_DIR} FILES_MATCHING PATTERN "*.h")

View File

@@ -0,0 +1,23 @@
#ifndef WINPR_BUILD_CONFIG_H
#define WINPR_BUILD_CONFIG_H
#define WINPR_DATA_PATH "${WINPR_DATA_PATH}"
#define WINPR_KEYMAP_PATH "${WINPR_KEYMAP_PATH}"
#define WINPR_PLUGIN_PATH "${WINPR_PLUGIN_PATH}"
#define WINPR_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}"
#define WINPR_INSTALL_SYSCONFDIR "${CMAKE_INSTALL_FULL_SYSCONFDIR}"
#define WINPR_LIBRARY_PATH "${WINPR_LIBRARY_PATH}"
#define WINPR_ADDIN_PATH "${WINPR_ADDIN_PATH}"
#define WINPR_SHARED_LIBRARY_SUFFIX "${CMAKE_SHARED_LIBRARY_SUFFIX}"
#define WINPR_SHARED_LIBRARY_PREFIX "${CMAKE_SHARED_LIBRARY_PREFIX}"
#define WINPR_VENDOR_STRING "${VENDOR}"
#define WINPR_PRODUCT_STRING "${PRODUCT}"
#define WINPR_PROXY_PLUGINDIR "${WINPR_PROXY_PLUGINDIR}"
#endif /* WINPR_BUILD_CONFIG_H */

View File

@@ -0,0 +1,11 @@
#ifndef WINPR_BUILD_FLAGS_H
#define WINPR_BUILD_FLAGS_H
#define WINPR_CFLAGS "${CURRENT_C_FLAGS}"
#define WINPR_COMPILER_ID "${CMAKE_C_COMPILER_ID}"
#define WINPR_COMPILER_VERSION "${CMAKE_C_COMPILER_VERSION}"
#define WINPR_TARGET_ARCH "${TARGET_ARCH}"
#define WINPR_BUILD_CONFIG "${WINPR_BUILD_CONFIG}"
#define WINPR_BUILD_TYPE "${CURRENT_BUILD_CONFIG}"
#endif /* WINPR_BUILD_FLAGS_H */

View File

@@ -0,0 +1,51 @@
#ifndef WINPR_CONFIG_H
#define WINPR_CONFIG_H
/* Include files */
#cmakedefine WINPR_HAVE_FCNTL_H
#cmakedefine WINPR_HAVE_UNISTD_H
#cmakedefine WINPR_HAVE_INTTYPES_H
#cmakedefine WINPR_HAVE_STDBOOL_H
#cmakedefine WINPR_HAVE_AIO_H
#cmakedefine WINPR_HAVE_SYS_FILIO_H
#cmakedefine WINPR_HAVE_SYS_SELECT_H
#cmakedefine WINPR_HAVE_SYS_SOCKIO_H
#cmakedefine WINPR_HAVE_SYS_EVENTFD_H
#cmakedefine WINPR_HAVE_SYS_TIMERFD_H
#cmakedefine WINPR_HAVE_TM_GMTOFF
#cmakedefine WINPR_HAVE_AIO_H
#cmakedefine WINPR_HAVE_POLL_H
#cmakedefine WINPR_HAVE_SYSLOG_H
#cmakedefine WINPR_HAVE_JOURNALD_H
#cmakedefine WINPR_HAVE_PTHREAD_MUTEX_TIMEDLOCK
#cmakedefine WINPR_HAVE_EXECINFO_H
#cmakedefine WINPR_HAVE_GETLOGIN_R
#cmakedefine WINPR_HAVE_GETPWUID_R
#cmakedefine WINPR_HAVE_STRNDUP
#cmakedefine WINPR_HAVE_UNWIND_H
#cmakedefine WINPR_HAVE_SSIZE_T
#cmakedefine WINPR_HAVE_WIN_SSIZE_T
#cmakedefine WINPR_WITH_PNG
#cmakedefine WINPR_HAVE_STRERROR_R /** @since version 3.3.0 */
#cmakedefine WITH_EVENTFD_READ_WRITE
#cmakedefine WITH_NATIVE_SSPI
#cmakedefine WITH_INTERNAL_RC4
#cmakedefine WITH_INTERNAL_MD4
#cmakedefine WITH_INTERNAL_MD5
#cmakedefine WITH_WINPR_JSON /** @since version 3.6.0 */
#cmakedefine WITH_DEBUG_NTLM
#cmakedefine WITH_DEBUG_THREADS
#cmakedefine WITH_DEBUG_EVENTS
#cmakedefine WITH_DEBUG_MUTEX
#cmakedefine WINPR_UTILS_IMAGE_DIBv5 /** @since version 3.13.0 */
#cmakedefine WINPR_UTILS_IMAGE_WEBP /** @since version 3.3.0 */
#cmakedefine WINPR_UTILS_IMAGE_PNG /** @since version 3.3.0 */
#cmakedefine WINPR_UTILS_IMAGE_JPEG /** @since version 3.3.0 */
#endif /* WINPR_CONFIG_H */

View File

@@ -0,0 +1,32 @@
/**
* FreeRDP: A Remote Desktop Protocol Implementation
* Version includes
*
* Copyright 2013 Thincast Technologies GmbH
* Copyright 2013 Bernhard Miklautz <bernhard.miklautz@thincast.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_VERSION_H_
#define WINPR_VERSION_H_
#define WINPR_VERSION_MAJOR ${WINPR_VERSION_MAJOR}
#define WINPR_VERSION_MINOR ${WINPR_VERSION_MINOR}
#define WINPR_VERSION_REVISION ${WINPR_VERSION_REVISION}
#define WINPR_VERSION_SUFFIX "${WINPR_VERSION_SUFFIX}"
#define WINPR_API_VERSION "${WINPR_API_VERSION}"
#define WINPR_VERSION "${WINPR_VERSION}"
#define WINPR_VERSION_FULL "${WINPR_VERSION_FULL}"
#define WINPR_GIT_REVISION "${GIT_REVISION}"
#endif // _WINPR_VERSION_H_

View File

@@ -0,0 +1,224 @@
/**
* WinPR: Windows Portable Runtime
* ASN1 encoder / decoder
*
* Copyright 2022 David Fort <contact@hardening-consulting.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_ASN1_H_
#define WINPR_ASN1_H_
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/stream.h>
#define ER_TAG_MASK 0x1F
enum
{
ER_TAG_BOOLEAN = 0x01,
ER_TAG_INTEGER = 0x02,
ER_TAG_BIT_STRING = 0x03,
ER_TAG_OCTET_STRING = 0x04,
ER_TAG_NULL = 0x05,
ER_TAG_OBJECT_IDENTIFIER = 0x06,
ER_TAG_ENUMERATED = 0x0A,
ER_TAG_UTF8STRING = 0x0C,
ER_TAG_PRINTABLE_STRING = 0x13,
ER_TAG_IA5STRING = 0x16,
ER_TAG_UTCTIME = 0x17,
ER_TAG_GENERAL_STRING = 0x1B,
ER_TAG_GENERALIZED_TIME = 0x18,
ER_TAG_APP = 0x60,
ER_TAG_SEQUENCE = 0x30,
ER_TAG_SEQUENCE_OF = 0x30,
ER_TAG_SET = 0x31,
ER_TAG_SET_OF = 0x31,
ER_TAG_CONTEXTUAL = 0xA0
};
/** @brief rules for encoding */
typedef enum
{
WINPR_ASN1_BER,
WINPR_ASN1_DER
} WinPrAsn1EncodingRule;
typedef struct WinPrAsn1Encoder WinPrAsn1Encoder;
struct WinPrAsn1Decoder
{
WinPrAsn1EncodingRule encoding;
wStream source;
};
typedef struct WinPrAsn1Decoder WinPrAsn1Decoder;
/** @brief helper initializing a \b WinPrAsn1Decoder context
*
* @return The initialized context
* @since version 3.24.0
*/
static inline WinPrAsn1Decoder WinPrAsn1Decoder_init(void)
{
const wStream stream = Stream_Init();
const WinPrAsn1Decoder empty = { WINPR_ASN1_BER, stream };
return empty;
}
typedef BYTE WinPrAsn1_tag;
typedef BYTE WinPrAsn1_tagId;
typedef BOOL WinPrAsn1_BOOL;
typedef INT32 WinPrAsn1_INTEGER;
typedef INT32 WinPrAsn1_ENUMERATED;
typedef char* WinPrAsn1_STRING;
typedef char* WinPrAsn1_IA5STRING;
typedef struct
{
size_t len;
BYTE* data;
} WinPrAsn1_MemoryChunk;
typedef WinPrAsn1_MemoryChunk WinPrAsn1_OID;
typedef WinPrAsn1_MemoryChunk WinPrAsn1_OctetString;
typedef struct
{
UINT16 year;
UINT8 month;
UINT8 day;
UINT8 hour;
UINT8 minute;
UINT8 second;
char tz;
} WinPrAsn1_UTCTIME;
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
WINPR_API void WinPrAsn1FreeOID(WinPrAsn1_OID* poid);
WINPR_API void WinPrAsn1FreeOctetString(WinPrAsn1_OctetString* octets);
/* decoder functions */
WINPR_API void WinPrAsn1Decoder_Init(WinPrAsn1Decoder* dec, WinPrAsn1EncodingRule encoding,
wStream* source);
WINPR_API void WinPrAsn1Decoder_InitMem(WinPrAsn1Decoder* dec, WinPrAsn1EncodingRule encoding,
const BYTE* source, size_t len);
WINPR_API BOOL WinPrAsn1DecPeekTag(WinPrAsn1Decoder* dec, WinPrAsn1_tag* tag);
WINPR_API size_t WinPrAsn1DecReadTagAndLen(WinPrAsn1Decoder* dec, WinPrAsn1_tag* tag,
size_t* len);
WINPR_API size_t WinPrAsn1DecPeekTagAndLen(WinPrAsn1Decoder* dec, WinPrAsn1_tag* tag,
size_t* len);
WINPR_API size_t WinPrAsn1DecReadTagLenValue(WinPrAsn1Decoder* dec, WinPrAsn1_tag* tag,
size_t* len, WinPrAsn1Decoder* value);
WINPR_API size_t WinPrAsn1DecReadBoolean(WinPrAsn1Decoder* dec, WinPrAsn1_BOOL* target);
WINPR_API size_t WinPrAsn1DecReadInteger(WinPrAsn1Decoder* dec, WinPrAsn1_INTEGER* target);
WINPR_API size_t WinPrAsn1DecReadEnumerated(WinPrAsn1Decoder* dec,
WinPrAsn1_ENUMERATED* target);
WINPR_API size_t WinPrAsn1DecReadOID(WinPrAsn1Decoder* dec, WinPrAsn1_OID* target,
BOOL allocate);
WINPR_API size_t WinPrAsn1DecReadOctetString(WinPrAsn1Decoder* dec,
WinPrAsn1_OctetString* target, BOOL allocate);
WINPR_API size_t WinPrAsn1DecReadIA5String(WinPrAsn1Decoder* dec, WinPrAsn1_IA5STRING* target);
WINPR_API size_t WinPrAsn1DecReadGeneralString(WinPrAsn1Decoder* dec, WinPrAsn1_STRING* target);
WINPR_API size_t WinPrAsn1DecReadUtcTime(WinPrAsn1Decoder* dec, WinPrAsn1_UTCTIME* target);
WINPR_API size_t WinPrAsn1DecReadNull(WinPrAsn1Decoder* dec);
WINPR_API size_t WinPrAsn1DecReadApp(WinPrAsn1Decoder* dec, WinPrAsn1_tagId* tagId,
WinPrAsn1Decoder* setDec);
WINPR_API size_t WinPrAsn1DecReadSequence(WinPrAsn1Decoder* dec, WinPrAsn1Decoder* seqDec);
WINPR_API size_t WinPrAsn1DecReadSet(WinPrAsn1Decoder* dec, WinPrAsn1Decoder* setDec);
WINPR_API size_t WinPrAsn1DecReadContextualTag(WinPrAsn1Decoder* dec, WinPrAsn1_tagId* tagId,
WinPrAsn1Decoder* ctxtDec);
WINPR_API size_t WinPrAsn1DecPeekContextualTag(WinPrAsn1Decoder* dec, WinPrAsn1_tagId* tagId,
WinPrAsn1Decoder* ctxtDec);
WINPR_API size_t WinPrAsn1DecReadContextualBool(WinPrAsn1Decoder* dec, WinPrAsn1_tagId tagId,
BOOL* error, WinPrAsn1_BOOL* target);
WINPR_API size_t WinPrAsn1DecReadContextualInteger(WinPrAsn1Decoder* dec, WinPrAsn1_tagId tagId,
BOOL* error, WinPrAsn1_INTEGER* target);
WINPR_API size_t WinPrAsn1DecReadContextualOID(WinPrAsn1Decoder* dec, WinPrAsn1_tagId tagId,
BOOL* error, WinPrAsn1_OID* target,
BOOL allocate);
WINPR_API size_t WinPrAsn1DecReadContextualOctetString(WinPrAsn1Decoder* dec,
WinPrAsn1_tagId tagId, BOOL* error,
WinPrAsn1_OctetString* target,
BOOL allocate);
WINPR_API size_t WinPrAsn1DecReadContextualSequence(WinPrAsn1Decoder* dec,
WinPrAsn1_tagId tagId, BOOL* error,
WinPrAsn1Decoder* target);
WINPR_API wStream WinPrAsn1DecGetStream(WinPrAsn1Decoder* dec);
/* encoder functions */
WINPR_API void WinPrAsn1Encoder_Free(WinPrAsn1Encoder** penc);
WINPR_API WinPrAsn1Encoder* WinPrAsn1Encoder_New(WinPrAsn1EncodingRule encoding);
WINPR_API void WinPrAsn1Encoder_Reset(WinPrAsn1Encoder* enc);
WINPR_API BOOL WinPrAsn1EncAppContainer(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId);
WINPR_API BOOL WinPrAsn1EncSeqContainer(WinPrAsn1Encoder* enc);
WINPR_API BOOL WinPrAsn1EncContextualSeqContainer(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId);
WINPR_API BOOL WinPrAsn1EncSetContainer(WinPrAsn1Encoder* enc);
WINPR_API BOOL WinPrAsn1EncContextualSetContainer(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId);
WINPR_API BOOL WinPrAsn1EncContextualContainer(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId);
WINPR_API BOOL WinPrAsn1EncOctetStringContainer(WinPrAsn1Encoder* enc);
WINPR_API BOOL WinPrAsn1EncContextualOctetStringContainer(WinPrAsn1Encoder* enc,
WinPrAsn1_tagId tagId);
WINPR_API size_t WinPrAsn1EncEndContainer(WinPrAsn1Encoder* enc);
WINPR_API size_t WinPrAsn1EncRawContent(WinPrAsn1Encoder* enc, const WinPrAsn1_MemoryChunk* c);
WINPR_API size_t WinPrAsn1EncContextualRawContent(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId,
const WinPrAsn1_MemoryChunk* c);
WINPR_API size_t WinPrAsn1EncInteger(WinPrAsn1Encoder* enc, WinPrAsn1_INTEGER integer);
WINPR_API size_t WinPrAsn1EncContextualInteger(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId,
WinPrAsn1_INTEGER integer);
WINPR_API size_t WinPrAsn1EncBoolean(WinPrAsn1Encoder* enc, WinPrAsn1_BOOL b);
WINPR_API size_t WinPrAsn1EncContextualBoolean(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId,
WinPrAsn1_BOOL b);
WINPR_API size_t WinPrAsn1EncEnumerated(WinPrAsn1Encoder* enc, WinPrAsn1_ENUMERATED e);
WINPR_API size_t WinPrAsn1EncContextualEnumerated(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId,
WinPrAsn1_ENUMERATED e);
WINPR_API size_t WinPrAsn1EncOID(WinPrAsn1Encoder* enc, const WinPrAsn1_OID* oid);
WINPR_API size_t WinPrAsn1EncContextualOID(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId,
const WinPrAsn1_OID* oid);
WINPR_API size_t WinPrAsn1EncOctetString(WinPrAsn1Encoder* enc,
const WinPrAsn1_OctetString* octetstring);
WINPR_API size_t WinPrAsn1EncContextualOctetString(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId,
const WinPrAsn1_OctetString* octetstring);
WINPR_API size_t WinPrAsn1EncIA5String(WinPrAsn1Encoder* enc, WinPrAsn1_IA5STRING ia5);
WINPR_API size_t WinPrAsn1EncGeneralString(WinPrAsn1Encoder* enc, WinPrAsn1_STRING str);
WINPR_API size_t WinPrAsn1EncContextualIA5String(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId,
WinPrAsn1_IA5STRING ia5);
WINPR_API size_t WinPrAsn1EncUtcTime(WinPrAsn1Encoder* enc, const WinPrAsn1_UTCTIME* utc);
WINPR_API size_t WinPrAsn1EncContextualUtcTime(WinPrAsn1Encoder* enc, WinPrAsn1_tagId tagId,
const WinPrAsn1_UTCTIME* utc);
WINPR_API BOOL WinPrAsn1EncStreamSize(WinPrAsn1Encoder* enc, size_t* s);
WINPR_API BOOL WinPrAsn1EncToStream(WinPrAsn1Encoder* enc, wStream* s);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* WINPR_ASN1_H_ */

View File

@@ -0,0 +1,97 @@
/**
* WinPR: Windows Portable Runtime
* Runtime ASSERT macros
*
* Copyright 2021 Armin Novak <armin.novak@thincast.com>
* Copyright 2021 Thincast Technologies GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <stdlib.h>
#include <assert.h>
#include <winpr/config.h>
#include <winpr/platform.h>
#if defined(WITH_VERBOSE_WINPR_ASSERT) && (WITH_VERBOSE_WINPR_ASSERT != 0)
#define winpr_internal_assert(cond, file, fkt, line) \
do \
{ \
if (!(cond)) \
winpr_int_assert(#cond, (file), (fkt), (line)); \
} while (0)
#else
#define winpr_internal_assert(cond, file, fkt, line) assert(cond)
#endif
#ifdef __cplusplus
extern "C"
{
#endif
/* this function meant only to be used by WINPR_ASSERT
* it needs to be exported as our assert implementation calls this for debug logging.
*
* also export when WITH_VERBOSE_WINPR_ASSERT is disabled as other software might compile with
* it enabled
*/
WINPR_API WINPR_NORETURN(void winpr_int_assert(const char* condstr, const char* file,
const char* fkt, size_t line));
#ifdef __cplusplus
}
#endif
#define WINPR_ASSERT_AT(cond, file, fkt, line) \
do \
{ \
WINPR_PRAGMA_DIAG_PUSH \
WINPR_PRAGMA_DIAG_TAUTOLOGICAL_CONSTANT_OUT_OF_RANGE_COMPARE \
WINPR_PRAGMA_DIAG_TAUTOLOGICAL_VALUE_RANGE_COMPARE \
WINPR_PRAGMA_DIAG_IGNORED_UNKNOWN_PRAGMAS \
WINPR_DO_COVERITY_PRAGMA( \
coverity compliance block deviate 'CONSTANT_EXPRESSION_RESULT' 'WINPR_ASSERT') \
WINPR_DO_COVERITY_PRAGMA(coverity compliance block deviate : 2 'NO_EFFECT' 'WINPR_ASSERT') \
\
winpr_internal_assert((cond), (file), (fkt), (line)); \
\
WINPR_DO_COVERITY_PRAGMA( \
coverity compliance end_block 'CONSTANT_EXPRESSION_RESULT' 'NO_EFFECT') \
WINPR_PRAGMA_DIAG_POP \
} while (0)
#define WINPR_ASSERT(cond) WINPR_ASSERT_AT((cond), __FILE__, __func__, __LINE__)
#ifdef __cplusplus
extern "C"
{
#endif
#if defined(__cplusplus) && (__cplusplus >= 201703L) // C++ 17
#define WINPR_STATIC_ASSERT(cond) static_assert(cond)
#elif defined(__cplusplus) && (__cplusplus >= 201103L) // C++ 11
#define WINPR_STATIC_ASSERT(cond) static_assert(cond, #cond)
#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L) // C23
#define WINPR_STATIC_ASSERT(cond) static_assert(cond)
#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) // C11
#define WINPR_STATIC_ASSERT(cond) _Static_assert(cond, #cond)
#else
WINPR_PRAGMA_WARNING("static-assert macro not supported on this platform")
#define WINPR_STATIC_ASSERT(cond) assert(cond)
#endif
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,34 @@
/**
* WinPR: Windows Portable Runtime
* Compatibility header for runtime ASSERT macros
*
* Copyright 2024 Armin Novak <armin.novak@thincast.com>
* Copyright 2024 Thincast Technologies GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_ASSERT_H
#define WINPR_ASSERT_H
#include <stdlib.h>
#include <assert.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/wlog.h>
#include <winpr/debug.h>
#include <winpr/assert-api.h>
#include <winpr/cast.h>
#endif

View File

@@ -0,0 +1,200 @@
/**
* WinPR: Windows Portable Runtime
* Cryptography API: Next Generation
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_BCRYPT_H
#define WINPR_BCRYPT_H
#ifdef _WIN32
#include <bcrypt.h>
#else
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
typedef PVOID BCRYPT_HANDLE;
typedef PVOID BCRYPT_ALG_HANDLE;
typedef PVOID BCRYPT_KEY_HANDLE;
typedef PVOID BCRYPT_HASH_HANDLE;
typedef PVOID BCRYPT_SECRET_HANDLE;
static const WCHAR BCRYPT_RSA_ALGORITHM[] = { 'R', 'S', 'A', '\0' };
static const WCHAR BCRYPT_RSA_SIGN_ALGORITHM[] = { 'R', 'S', 'A', '_', 'S', 'I', 'G', 'N', '\0' };
static const WCHAR BCRYPT_DH_ALGORITHM[] = { 'D', 'H', '\0' };
static const WCHAR BCRYPT_DSA_ALGORITHM[] = { 'D', 'S', 'A', '\0' };
static const WCHAR BCRYPT_RC2_ALGORITHM[] = { 'R', 'C', '2', '\0' };
static const WCHAR BCRYPT_RC4_ALGORITHM[] = { 'R', 'C', '4', '\0' };
static const WCHAR BCRYPT_AES_ALGORITHM[] = { 'A', 'E', 'S', '\0' };
static const WCHAR BCRYPT_DES_ALGORITHM[] = { 'D', 'E', 'S', '\0' };
static const WCHAR BCRYPT_DESX_ALGORITHM[] = { 'D', 'E', 'S', 'X', '\0' };
static const WCHAR BCRYPT_3DES_ALGORITHM[] = { '3', 'D', 'E', 'S', '\0' };
static const WCHAR BCRYPT_3DES_112_ALGORITHM[] = { '3', 'D', 'E', 'S', '_', '1', '1', '2', '\0' };
static const WCHAR BCRYPT_MD2_ALGORITHM[] = { 'M', 'D', '2', '\0' };
static const WCHAR BCRYPT_MD4_ALGORITHM[] = { 'M', 'D', '4', '\0' };
static const WCHAR BCRYPT_MD5_ALGORITHM[] = { 'M', 'D', '5', '\0' };
static const WCHAR BCRYPT_SHA1_ALGORITHM[] = { 'S', 'H', 'A', '1', '\0' };
static const WCHAR BCRYPT_SHA256_ALGORITHM[] = { 'S', 'H', 'A', '2', '5', '6', '\0' };
static const WCHAR BCRYPT_SHA384_ALGORITHM[] = { 'S', 'H', 'A', '3', '8', '4', '\0' };
static const WCHAR BCRYPT_SHA512_ALGORITHM[] = { 'S', 'H', 'A', '5', '1', '2', '\0' };
static const WCHAR BCRYPT_AES_GMAC_ALGORITHM[] = { 'A', 'E', 'S', '-', 'G', 'M', 'A', 'C', '\0' };
static const WCHAR BCRYPT_AES_CMAC_ALGORITHM[] = { 'A', 'E', 'S', '-', 'C', 'M', 'A', 'C', '\0' };
static const WCHAR BCRYPT_ECDSA_P256_ALGORITHM[] = { 'E', 'C', 'D', 'S', 'A', '_',
'P', '2', '5', '6', '\0' };
static const WCHAR BCRYPT_ECDSA_P384_ALGORITHM[] = { 'E', 'C', 'D', 'S', 'A', '_',
'P', '3', '8', '4', '\0' };
static const WCHAR BCRYPT_ECDSA_P521_ALGORITHM[] = { 'E', 'C', 'D', 'S', 'A', '_',
'P', '5', '2', '1', '\0' };
static const WCHAR BCRYPT_ECDH_P256_ALGORITHM[] = { 'E', 'C', 'D', 'S', 'A', '_',
'P', '2', '5', '6', '\0' };
static const WCHAR BCRYPT_ECDH_P384_ALGORITHM[] = { 'E', 'C', 'D', 'S', 'A', '_',
'P', '3', '8', '4', '\0' };
static const WCHAR BCRYPT_ECDH_P521_ALGORITHM[] = { 'E', 'C', 'D', 'S', 'A', '_',
'P', '5', '2', '1', '\0' };
static const WCHAR BCRYPT_RNG_ALGORITHM[] = { 'R', 'N', 'G', '\0' };
static const WCHAR BCRYPT_RNG_FIPS186_DSA_ALGORITHM[] = { 'F', 'I', 'P', 'S', '1', '8', '6',
'D', 'S', 'A', 'R', 'N', 'G', '\0' };
static const WCHAR BCRYPT_RNG_DUAL_EC_ALGORITHM[] = { 'D', 'U', 'A', 'L', 'E',
'C', 'R', 'N', 'G', '\0' };
static const WCHAR BCRYPT_ECDSA_ALGORITHM[] = { 'E', 'C', 'D', 'S', 'A', '\0' };
static const WCHAR BCRYPT_ECDH_ALGORITHM[] = { 'E', 'C', 'D', 'H', '\0' };
static const WCHAR BCRYPT_XTS_AES_ALGORITHM[] = { 'X', 'T', 'S', '-', 'A', 'E', 'S', '\0' };
static const WCHAR MS_PRIMITIVE_PROVIDER[] = { 'M', 'i', 'c', 'r', 'o', 's', 'o', 'f', 't', ' ',
'P', 'r', 'i', 'm', 'i', 't', 'i', 'v', 'e', ' ',
'P', 'r', 'o', 'v', 'i', 'd', 'e', 'r', '\0' };
static const WCHAR MS_PLATFORM_CRYPTO_PROVIDER[] = { 'M', 'i', 'c', 'r', 'o', 's', 'o', 'f', 't',
' ', 'P', 'l', 'a', 't', 'f', 'o', 'r', 'm',
' ', 'C', 'r', 'y', 'p', 't', 'o', ' ', 'P',
'r', 'o', 'v', 'i', 'd', 'e', 'r', '\0' };
#define BCRYPT_ALG_HANDLE_HMAC_FLAG 0x00000008
#define BCRYPT_PROV_DISPATCH 0x00000001
static const WCHAR BCRYPT_OBJECT_LENGTH[] = { 'O', 'b', 'j', 'e', 'c', 't', 'L',
'e', 'n', 'g', 't', 'h', '\0' };
static const WCHAR BCRYPT_ALGORITHM_NAME[] = { 'A', 'l', 'g', 'o', 'r', 'i', 't',
'h', 'm', 'N', 'a', 'm', 'e', '\0' };
static const WCHAR BCRYPT_PROVIDER_HANDLE[] = { 'P', 'r', 'o', 'v', 'i', 'd', 'e', 'r',
'H', 'a', 'n', 'd', 'l', 'e', '\0' };
static const WCHAR BCRYPT_CHAINING_MODE[] = { 'C', 'h', 'a', 'i', 'n', 'i', 'n',
'g', 'M', 'o', 'd', 'e', '\0' };
static const WCHAR BCRYPT_BLOCK_LENGTH[] = { 'B', 'l', 'o', 'c', 'k', 'L',
'e', 'n', 'g', 't', 'h', '\0' };
static const WCHAR BCRYPT_KEY_LENGTH[] = { 'K', 'e', 'y', 'L', 'e', 'n', 'g', 't', 'h', '\0' };
static const WCHAR BCRYPT_KEY_OBJECT_LENGTH[] = { 'K', 'e', 'y', 'O', 'b', 'j', 'e', 'c',
't', 'L', 'e', 'n', 'g', 't', 'h', '\0' };
static const WCHAR BCRYPT_KEY_STRENGTH[] = { 'K', 'e', 'y', 'S', 't', 'r',
'e', 'n', 'g', 't', 'h', '\0' };
static const WCHAR BCRYPT_KEY_LENGTHS[] = {
'K', 'e', 'y', 'L', 'e', 'n', 'g', 't', 'h', 's', '\0'
};
static const WCHAR BCRYPT_BLOCK_SIZE_LIST[] = { 'B', 'l', 'o', 'c', 'k', 'S', 'i',
'z', 'e', 'L', 'i', 's', 't', '\0' };
static const WCHAR BCRYPT_EFFECTIVE_KEY_LENGTH[] = { 'E', 'f', 'f', 'e', 'c', 't', 'i',
'v', 'e', 'K', 'e', 'y', 'L', 'e',
'n', 'g', 't', 'h', '\0' };
static const WCHAR BCRYPT_HASH_LENGTH[] = { 'H', 'a', 's', 'h', 'D', 'i', 'g', 'e', 's',
't', 'L', 'e', 'n', 'g', 't', 'h', '\0' };
static const WCHAR BCRYPT_HASH_OID_LIST[] = { 'H', 'a', 's', 'h', 'O', 'I',
'D', 'L', 'i', 's', 't', '\0' };
static const WCHAR BCRYPT_PADDING_SCHEMES[] = { 'P', 'a', 'd', 'd', 'i', 'n', 'g', 'S',
'c', 'h', 'e', 'm', 'e', 's', '\0' };
static const WCHAR BCRYPT_SIGNATURE_LENGTH[] = { 'S', 'i', 'g', 'n', 'a', 't', 'u', 'r',
'e', 'L', 'e', 'n', 'g', 't', 'h', '\0' };
static const WCHAR BCRYPT_HASH_BLOCK_LENGTH[] = { 'H', 'a', 's', 'h', 'B', 'l', 'o', 'c',
'k', 'L', 'e', 'n', 'g', 't', 'h', '\0' };
static const WCHAR BCRYPT_AUTH_TAG_LENGTH[] = { 'A', 'u', 't', 'h', 'T', 'a', 'g',
'L', 'e', 'n', 'g', 't', 'h', '\0' };
static const WCHAR BCRYPT_PRIMITIVE_TYPE[] = { 'P', 'r', 'i', 'm', 'i', 't', 'i',
'v', 'e', 'T', 'y', 'p', 'e', '\0' };
static const WCHAR BCRYPT_IS_KEYED_HASH[] = { 'I', 's', 'K', 'e', 'y', 'e',
'd', 'H', 'a', 's', 'h', '\0' };
static const WCHAR BCRYPT_KEY_DATA_BLOB[] = { 'K', 'e', 'y', 'D', 'a', 't',
'a', 'B', 'l', 'o', 'b', '\0' };
#define BCRYPT_BLOCK_PADDING 0x00000001
#define BCRYPT_KEY_DATA_BLOB_MAGIC 0x4d42444b
#define BCRYPT_KEY_DATA_BLOB_VERSION1 0x1
typedef struct
{
ULONG dwMagic;
ULONG dwVersion;
ULONG cbKeyData;
} BCRYPT_KEY_DATA_BLOB_HEADER, *PBCRYPT_KEY_DATA_BLOB_HEADER;
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API NTSTATUS BCryptOpenAlgorithmProvider(BCRYPT_ALG_HANDLE* phAlgorithm, LPCWSTR pszAlgId,
LPCWSTR pszImplementation, ULONG dwFlags);
WINPR_API NTSTATUS BCryptCloseAlgorithmProvider(BCRYPT_ALG_HANDLE hAlgorithm, ULONG dwFlags);
WINPR_API NTSTATUS BCryptGetProperty(BCRYPT_HANDLE hObject, LPCWSTR pszProperty,
PUCHAR pbOutput, ULONG cbOutput, ULONG* pcbResult,
ULONG dwFlags);
WINPR_API NTSTATUS BCryptCreateHash(BCRYPT_ALG_HANDLE hAlgorithm, BCRYPT_HASH_HANDLE* phHash,
PUCHAR pbHashObject, ULONG cbHashObject, PUCHAR pbSecret,
ULONG cbSecret, ULONG dwFlags);
WINPR_API NTSTATUS BCryptDestroyHash(BCRYPT_HASH_HANDLE hHash);
WINPR_API NTSTATUS BCryptHashData(BCRYPT_HASH_HANDLE hHash, PUCHAR pbInput, ULONG cbInput,
ULONG dwFlags);
WINPR_API NTSTATUS BCryptFinishHash(BCRYPT_HASH_HANDLE hHash, PUCHAR pbOutput, ULONG cbOutput,
ULONG dwFlags);
WINPR_API NTSTATUS BCryptGenRandom(BCRYPT_ALG_HANDLE hAlgorithm, PUCHAR pbBuffer,
ULONG cbBuffer, ULONG dwFlags);
WINPR_API NTSTATUS BCryptGenerateSymmetricKey(BCRYPT_ALG_HANDLE hAlgorithm,
BCRYPT_KEY_HANDLE* phKey, PUCHAR pbKeyObject,
ULONG cbKeyObject, PUCHAR pbSecret,
ULONG cbSecret, ULONG dwFlags);
WINPR_API NTSTATUS BCryptGenerateKeyPair(BCRYPT_ALG_HANDLE hAlgorithm, BCRYPT_KEY_HANDLE* phKey,
ULONG dwLength, ULONG dwFlags);
WINPR_API NTSTATUS BCryptImportKey(BCRYPT_ALG_HANDLE hAlgorithm, BCRYPT_KEY_HANDLE hImportKey,
LPCWSTR pszBlobType, BCRYPT_KEY_HANDLE* phKey,
PUCHAR pbKeyObject, ULONG cbKeyObject, PUCHAR pbInput,
ULONG cbInput, ULONG dwFlags);
WINPR_API NTSTATUS BCryptDestroyKey(BCRYPT_KEY_HANDLE hKey);
WINPR_API NTSTATUS BCryptEncrypt(BCRYPT_KEY_HANDLE hKey, PUCHAR pbInput, ULONG cbInput,
VOID* pPaddingInfo, PUCHAR pbIV, ULONG cbIV, PUCHAR pbOutput,
ULONG cbOutput, ULONG* pcbResult, ULONG dwFlags);
WINPR_API NTSTATUS BCryptDecrypt(BCRYPT_KEY_HANDLE hKey, PUCHAR pbInput, ULONG cbInput,
VOID* pPaddingInfo, PUCHAR pbIV, ULONG cbIV, PUCHAR pbOutput,
ULONG cbOutput, ULONG* pcbResult, ULONG dwFlags);
#ifdef __cplusplus
}
#endif
#endif /* _WIN32 */
#endif /* WINPR_BCRYPT_H */

View File

@@ -0,0 +1,192 @@
/*
* WinPR: Windows Portable Runtime
* BitStream Utils
*
* Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_UTILS_BITSTREAM_H
#define WINPR_UTILS_BITSTREAM_H
#include <winpr/assert.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/crt.h>
#include <winpr/wlog.h>
typedef struct
{
const BYTE* buffer;
BYTE* pointer;
UINT32 position;
UINT32 length;
UINT32 capacity;
UINT32 mask;
UINT32 offset;
UINT32 prefetch;
UINT32 accumulator;
} wBitStream;
#define BITDUMP_MSB_FIRST 0x00000001
#define BITDUMP_STDERR 0x00000002
#ifdef __cplusplus
extern "C"
{
#endif
static inline void BitStream_Prefetch(wBitStream* _bs)
{
WINPR_ASSERT(_bs);
(_bs->prefetch) = 0;
const intptr_t diff = _bs->pointer - _bs->buffer;
if ((diff + 4) < (intptr_t)_bs->capacity)
(_bs->prefetch) |= ((UINT32)_bs->pointer[4] << 24);
if ((diff + 5) < (intptr_t)_bs->capacity)
(_bs->prefetch) |= ((UINT32)_bs->pointer[5] << 16);
if ((diff + 6) < (intptr_t)_bs->capacity)
(_bs->prefetch) |= ((UINT32)_bs->pointer[6] << 8);
if ((diff + 7) < (intptr_t)_bs->capacity)
(_bs->prefetch) |= ((UINT32)_bs->pointer[7] << 0);
}
static inline void BitStream_Fetch(wBitStream* _bs)
{
WINPR_ASSERT(_bs);
(_bs->accumulator) = 0;
const intptr_t diff = _bs->pointer - _bs->buffer;
if ((diff + 0) < (intptr_t)_bs->capacity)
(_bs->accumulator) |= ((UINT32)_bs->pointer[0] << 24);
if ((diff + 1) < (intptr_t)_bs->capacity)
(_bs->accumulator) |= ((UINT32)_bs->pointer[1] << 16);
if ((diff + 2) < (intptr_t)_bs->capacity)
(_bs->accumulator) |= ((UINT32)_bs->pointer[2] << 8);
if ((diff + 3) < (intptr_t)_bs->capacity)
(_bs->accumulator) |= ((UINT32)_bs->pointer[3] << 0);
BitStream_Prefetch(_bs);
}
static inline void BitStream_Flush(wBitStream* _bs)
{
WINPR_ASSERT(_bs);
const intptr_t diff = _bs->pointer - _bs->buffer;
if ((diff + 0) < (intptr_t)_bs->capacity)
_bs->pointer[0] = (_bs->accumulator >> 24) & 0xFF;
if ((diff + 1) < (intptr_t)_bs->capacity)
_bs->pointer[1] = (_bs->accumulator >> 16) & 0xFF;
if ((diff + 2) < (intptr_t)_bs->capacity)
_bs->pointer[2] = (_bs->accumulator >> 8) & 0xFF;
if ((diff + 3) < (intptr_t)_bs->capacity)
_bs->pointer[3] = (_bs->accumulator >> 0) & 0xFF;
}
static inline void BitStream_Shift(wBitStream* _bs, UINT32 _nbits)
{
WINPR_ASSERT(_bs);
if (_nbits == 0)
{
}
else if ((_nbits > 0) && (_nbits < 32))
{
_bs->accumulator <<= _nbits;
_bs->position += _nbits;
_bs->offset += _nbits;
if (_bs->offset < 32)
{
_bs->mask = (UINT32)((1UL << _nbits) - 1UL);
_bs->accumulator |= ((_bs->prefetch >> (32 - _nbits)) & _bs->mask);
_bs->prefetch <<= _nbits;
}
else
{
_bs->mask = (UINT32)((1UL << _nbits) - 1UL);
_bs->accumulator |= ((_bs->prefetch >> (32 - _nbits)) & _bs->mask);
_bs->prefetch <<= _nbits;
_bs->offset -= 32;
_bs->pointer += 4;
BitStream_Prefetch(_bs);
if (_bs->offset)
{
_bs->mask = (UINT32)((1UL << _bs->offset) - 1UL);
_bs->accumulator |= ((_bs->prefetch >> (32 - _bs->offset)) & _bs->mask);
_bs->prefetch <<= _bs->offset;
}
}
}
else
{
WLog_WARN("com.winpr.bitstream", "warning: BitStream_Shift(%u)", (unsigned)_nbits);
}
}
static inline void BitStream_Shift32(wBitStream* _bs)
{
WINPR_ASSERT(_bs);
BitStream_Shift(_bs, 16);
BitStream_Shift(_bs, 16);
}
static inline void BitStream_Write_Bits(wBitStream* _bs, UINT32 _bits, UINT32 _nbits)
{
WINPR_ASSERT(_bs);
_bs->position += _nbits;
_bs->offset += _nbits;
if (_bs->offset < 32)
{
_bs->accumulator |= (_bits << (32 - _bs->offset));
}
else
{
_bs->offset -= 32;
_bs->mask = ((1 << (_nbits - _bs->offset)) - 1);
_bs->accumulator |= ((_bits >> _bs->offset) & _bs->mask);
BitStream_Flush(_bs);
_bs->accumulator = 0;
_bs->pointer += 4;
if (_bs->offset)
{
_bs->mask = (UINT32)((1UL << _bs->offset) - 1);
_bs->accumulator |= ((_bits & _bs->mask) << (32 - _bs->offset));
}
}
}
static inline size_t BitStream_GetRemainingLength(wBitStream* _bs)
{
WINPR_ASSERT(_bs);
return (_bs->length - _bs->position);
}
WINPR_API void BitDump(const char* tag, UINT32 level, const BYTE* buffer, UINT32 length,
UINT32 flags);
WINPR_API UINT32 ReverseBits32(UINT32 bits, UINT32 nbits);
WINPR_API void BitStream_Attach(wBitStream* bs, const BYTE* buffer, UINT32 capacity);
WINPR_API void BitStream_Free(wBitStream* bs);
WINPR_ATTR_MALLOC(BitStream_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API wBitStream* BitStream_New(void);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_UTILS_BITSTREAM_H */

View File

@@ -0,0 +1,123 @@
/**
* WinPR: Windows Portable Runtime
* Cast macros
*
* Copyright 2024 Armin Novak <anovak@thincast.com>
* Copyright 2024 Thincast Technologies GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <stdint.h>
#include <winpr/assert-api.h>
/**
* @brief C++ safe cast macro
* @since version 3.10.1
*/
#ifdef __cplusplus
#define WINPR_CXX_COMPAT_CAST(t, val) static_cast<t>(val)
#else
#define WINPR_CXX_COMPAT_CAST(t, val) (t)(val)
#endif
#if defined(__GNUC__) || defined(__clang__)
/**
* @brief A macro to do dirty casts. Do not use without a good justification!
* @param ptr The pointer to cast
* @param dstType The data type to cast to
* @return The casted pointer
* @since version 3.9.0
*/
#define WINPR_REINTERPRET_CAST(ptr, srcType, dstType) \
__extension__({ \
union \
{ \
srcType src; \
dstType dst; \
} cnv; \
WINPR_STATIC_ASSERT(sizeof(srcType) == sizeof(dstType)); \
cnv.src = ptr; \
cnv.dst; \
})
/**
* @brief A macro to do dirty casts. Do not use without a good justification!
* @param ptr The pointer to cast
* @param dstType The data type to cast to
* @return The casted pointer
* @since version 3.9.0
*/
#define WINPR_CAST_CONST_PTR_AWAY(ptr, dstType) \
__extension__({ \
union \
{ \
__typeof(ptr) src; \
dstType dst; \
} cnv; \
cnv.src = ptr; \
cnv.dst; \
})
/**
* @brief A macro to do function pointer casts. Do not use without a good justification!
* @param ptr The pointer to cast
* @param dstType The data type to cast to
* @return The casted pointer
* @since version 3.9.0
*/
#define WINPR_FUNC_PTR_CAST(ptr, dstType) \
__extension__({ \
union \
{ \
__typeof(ptr) src; \
dstType dst; \
} cnv; \
WINPR_STATIC_ASSERT(sizeof(dstType) == sizeof(__typeof(ptr))); \
cnv.src = ptr; \
cnv.dst; \
})
#else
#define WINPR_REINTERPRET_CAST(ptr, srcType, dstType) (dstType) ptr
#define WINPR_CAST_CONST_PTR_AWAY(ptr, dstType) (dstType) ptr
#define WINPR_FUNC_PTR_CAST(ptr, dstType) (dstType)(uintptr_t) ptr
#endif
#if defined(__GNUC__) || defined(__clang__)
/**
* @brief A macro to do checked integer casts.
* will check if the value does change by casting to and from the target type and comparing the
* values. will also check if the sign of a value changes during conversion.
*
* @param type the type to cast to
* @param var the integer of unknown type to cast
* @return The casted integer
* @since version 3.10.1
*/
#define WINPR_ASSERTING_INT_CAST(type, ivar) \
__extension__({ \
__typeof(ivar) var = ivar; \
WINPR_ASSERT((var) == \
WINPR_CXX_COMPAT_CAST(__typeof(var), WINPR_CXX_COMPAT_CAST(type, (var)))); \
WINPR_ASSERT((((var) > 0) && (WINPR_CXX_COMPAT_CAST(type, (var)) > 0)) || \
(((var) <= 0) && WINPR_CXX_COMPAT_CAST(type, (var)) <= 0)); \
WINPR_CXX_COMPAT_CAST(type, (var)); \
})
#else
#define WINPR_ASSERTING_INT_CAST(type, var) WINPR_CXX_COMPAT_CAST(type, var)
#endif

View File

@@ -0,0 +1,109 @@
/**
* WinPR: Windows Portable Runtime
* Clipboard Functions
*
* Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_CLIPBOARD_H
#define WINPR_CLIPBOARD_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
typedef struct s_wClipboard wClipboard;
typedef void* (*CLIPBOARD_SYNTHESIZE_FN)(wClipboard* clipboard, UINT32 formatId, const void* data,
UINT32* pSize);
typedef struct
{
UINT32 streamId;
UINT32 listIndex;
} wClipboardFileSizeRequest;
typedef struct
{
UINT32 streamId;
UINT32 listIndex;
UINT32 nPositionLow;
UINT32 nPositionHigh;
UINT32 cbRequested;
} wClipboardFileRangeRequest;
typedef struct s_wClipboardDelegate wClipboardDelegate;
struct s_wClipboardDelegate
{
wClipboard* clipboard;
void* custom;
char* basePath;
UINT (*ClientRequestFileSize)(wClipboardDelegate*, const wClipboardFileSizeRequest*);
UINT(*ClipboardFileSizeSuccess)
(wClipboardDelegate*, const wClipboardFileSizeRequest*, UINT64 fileSize);
UINT(*ClipboardFileSizeFailure)
(wClipboardDelegate*, const wClipboardFileSizeRequest*, UINT errorCode);
UINT (*ClientRequestFileRange)(wClipboardDelegate*, const wClipboardFileRangeRequest*);
UINT(*ClipboardFileRangeSuccess)
(wClipboardDelegate*, const wClipboardFileRangeRequest*, const BYTE* data, UINT32 size);
UINT(*ClipboardFileRangeFailure)
(wClipboardDelegate*, const wClipboardFileRangeRequest*, UINT errorCode);
BOOL (*IsFileNameComponentValid)(LPCWSTR lpFileName);
};
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API void ClipboardLock(wClipboard* clipboard);
WINPR_API void ClipboardUnlock(wClipboard* clipboard);
WINPR_API BOOL ClipboardEmpty(wClipboard* clipboard);
WINPR_API UINT32 ClipboardCountFormats(wClipboard* clipboard);
WINPR_API UINT32 ClipboardGetFormatIds(wClipboard* clipboard, UINT32** ppFormatIds);
WINPR_API UINT32 ClipboardCountRegisteredFormats(wClipboard* clipboard);
WINPR_API UINT32 ClipboardGetRegisteredFormatIds(wClipboard* clipboard, UINT32** ppFormatIds);
WINPR_API UINT32 ClipboardRegisterFormat(wClipboard* clipboard, const char* name);
WINPR_API BOOL ClipboardRegisterSynthesizer(wClipboard* clipboard, UINT32 formatId,
UINT32 syntheticId,
CLIPBOARD_SYNTHESIZE_FN pfnSynthesize);
WINPR_API UINT32 ClipboardGetFormatId(wClipboard* clipboard, const char* name);
WINPR_API const char* ClipboardGetFormatName(wClipboard* clipboard, UINT32 formatId);
WINPR_API void* ClipboardGetData(wClipboard* clipboard, UINT32 formatId, UINT32* pSize);
WINPR_API BOOL ClipboardSetData(wClipboard* clipboard, UINT32 formatId, const void* data,
UINT32 size);
WINPR_API UINT64 ClipboardGetOwner(wClipboard* clipboard);
WINPR_API void ClipboardSetOwner(wClipboard* clipboard, UINT64 ownerId);
WINPR_API wClipboardDelegate* ClipboardGetDelegate(wClipboard* clipboard);
WINPR_API wClipboard* ClipboardCreate(void);
WINPR_API void ClipboardDestroy(wClipboard* clipboard);
WINPR_API const char* ClipboardGetFormatIdString(UINT32 formatId);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_CLIPBOARD_H */

View File

@@ -0,0 +1,200 @@
/**
* WinPR: Windows Portable Runtime
* Command-Line Utils
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_CMDLINE_H
#define WINPR_CMDLINE_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
/* Command-Line Argument Flags */
#define COMMAND_LINE_INPUT_FLAG_MASK 0x0000FFFF
#define COMMAND_LINE_OUTPUT_FLAG_MASK 0xFFFF0000
/* Command-Line Argument Input Flags */
#define COMMAND_LINE_VALUE_FLAG 0x00000001
#define COMMAND_LINE_VALUE_REQUIRED 0x00000002
#define COMMAND_LINE_VALUE_OPTIONAL 0x00000004
#define COMMAND_LINE_VALUE_BOOL 0x00000008
#define COMMAND_LINE_ADVANCED 0x00000100
#define COMMAND_LINE_PRINT 0x00000200
#define COMMAND_LINE_PRINT_HELP 0x00000400
#define COMMAND_LINE_PRINT_VERSION 0x00000800
#define COMMAND_LINE_PRINT_BUILDCONFIG 0x00001000
/* Command-Line Argument Output Flags */
#define COMMAND_LINE_ARGUMENT_PRESENT 0x80000000
#define COMMAND_LINE_VALUE_PRESENT 0x40000000
/* Command-Line Parsing Flags */
#define COMMAND_LINE_SIGIL_NONE 0x00000001
#define COMMAND_LINE_SIGIL_SLASH 0x00000002
#define COMMAND_LINE_SIGIL_DASH 0x00000004
#define COMMAND_LINE_SIGIL_DOUBLE_DASH 0x00000008
#define COMMAND_LINE_SIGIL_PLUS_MINUS 0x00000010
#define COMMAND_LINE_SIGIL_ENABLE_DISABLE 0x00000020
#define COMMAND_LINE_SIGIL_NOT_ESCAPED 0x00000040
#define COMMAND_LINE_SEPARATOR_COLON 0x00000100
#define COMMAND_LINE_SEPARATOR_EQUAL 0x00000200
#define COMMAND_LINE_SEPARATOR_SPACE 0x00000400
/* Suppress COMMAND_LINE_ERROR_NO_KEYWORD return. */
#define COMMAND_LINE_IGN_UNKNOWN_KEYWORD 0x00001000
#define COMMAND_LINE_SILENCE_PARSER 0x00002000
/* Command-Line Parsing Error Codes */
#define COMMAND_LINE_ERROR -1000
#define COMMAND_LINE_ERROR_NO_KEYWORD -1001
#define COMMAND_LINE_ERROR_UNEXPECTED_VALUE -1002
#define COMMAND_LINE_ERROR_MISSING_VALUE -1003
#define COMMAND_LINE_ERROR_MISSING_ARGUMENT -1004
#define COMMAND_LINE_ERROR_UNEXPECTED_SIGIL -1005
#define COMMAND_LINE_ERROR_MEMORY -1006
#define COMMAND_LINE_ERROR_LAST -1999
/* Command-Line Parsing Status Codes */
#define COMMAND_LINE_STATUS_PRINT -2001
#define COMMAND_LINE_STATUS_PRINT_HELP -2002
#define COMMAND_LINE_STATUS_PRINT_VERSION -2003
#define COMMAND_LINE_STATUS_PRINT_BUILDCONFIG -2004
#define COMMAND_LINE_STATUS_PRINT_LAST -2999
/* Command-Line Macros */
#define CommandLineSwitchStart(_arg) \
if (0) \
{ \
}
#define CommandLineSwitchCase(_arg, _name) else if (strcmp(_arg->Name, _name) == 0)
#define CommandLineSwitchDefault(_arg) else
#define CommandLineSwitchEnd(_arg)
#define BoolValueTrue ((LPSTR)1)
#define BoolValueFalse ((LPSTR)0)
typedef struct
{
LPCSTR Name;
DWORD Flags;
LPCSTR Format;
LPCSTR Default;
LPSTR Value;
LONG Index;
LPCSTR Alias;
LPCSTR Text;
} COMMAND_LINE_ARGUMENT_A;
typedef struct
{
LPCWSTR Name;
DWORD Flags;
LPCSTR Format;
LPWSTR Default;
LPWSTR Value;
LONG Index;
LPCWSTR Alias;
LPCWSTR Text;
} COMMAND_LINE_ARGUMENT_W;
#ifdef UNICODE
#define COMMAND_LINE_ARGUMENT COMMAND_LINE_ARGUMENT_W
#else
#define COMMAND_LINE_ARGUMENT COMMAND_LINE_ARGUMENT_A
#endif
typedef int (*COMMAND_LINE_PRE_FILTER_FN_A)(void* context, int index, int argc, LPSTR* argv);
typedef int (*COMMAND_LINE_PRE_FILTER_FN_W)(void* context, int index, int argc, LPWSTR* argv);
typedef int (*COMMAND_LINE_POST_FILTER_FN_A)(void* context, COMMAND_LINE_ARGUMENT_A* arg);
typedef int (*COMMAND_LINE_POST_FILTER_FN_W)(void* context, COMMAND_LINE_ARGUMENT_W* arg);
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API int CommandLineClearArgumentsA(COMMAND_LINE_ARGUMENT_A* options);
WINPR_API int CommandLineClearArgumentsW(COMMAND_LINE_ARGUMENT_W* options);
WINPR_API int CommandLineParseArgumentsA(int argc, LPSTR* argv,
COMMAND_LINE_ARGUMENT_A* options, DWORD flags,
void* context, COMMAND_LINE_PRE_FILTER_FN_A preFilter,
COMMAND_LINE_POST_FILTER_FN_A postFilter);
WINPR_API int CommandLineParseArgumentsW(int argc, LPWSTR* argv,
COMMAND_LINE_ARGUMENT_W* options, DWORD flags,
void* context, COMMAND_LINE_PRE_FILTER_FN_W preFilter,
COMMAND_LINE_POST_FILTER_FN_W postFilter);
WINPR_API const COMMAND_LINE_ARGUMENT_A*
CommandLineFindArgumentA(const COMMAND_LINE_ARGUMENT_A* options, LPCSTR Name);
WINPR_API const COMMAND_LINE_ARGUMENT_W*
CommandLineFindArgumentW(const COMMAND_LINE_ARGUMENT_W* options, LPCWSTR Name);
WINPR_API const COMMAND_LINE_ARGUMENT_A*
CommandLineFindNextArgumentA(const COMMAND_LINE_ARGUMENT_A* argument);
/** @brief free arrays allocated by CommandLineParseCommaSeparatedValues(Ex)
*
* @param ptr the pointer to free, may be \b nullptr
*
* @since version 3.10.0
*/
WINPR_API void CommandLineParserFree(char** ptr);
WINPR_ATTR_MALLOC(CommandLineParserFree, 1)
WINPR_ATTR_NODISCARD
WINPR_API char** CommandLineParseCommaSeparatedValues(const char* list, size_t* count);
WINPR_ATTR_MALLOC(CommandLineParserFree, 1)
WINPR_ATTR_NODISCARD
WINPR_API char** CommandLineParseCommaSeparatedValuesEx(const char* name, const char* list,
size_t* count);
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* CommandLineToCommaSeparatedValues(int argc, char* argv[]);
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* CommandLineToCommaSeparatedValuesEx(int argc, char* argv[],
const char* filters[], size_t number);
#ifdef __cplusplus
}
#endif
#ifdef UNICODE
#define CommandLineClearArguments CommandLineClearArgumentsW
#define CommandLineParseArguments CommandLineParseArgumentsW
#define CommandLineFindArgument CommandLineFindArgumentW
#else
#define CommandLineClearArguments CommandLineClearArgumentsA
#define CommandLineParseArguments CommandLineParseArgumentsA
#define CommandLineFindArgument CommandLineFindArgumentA
#endif
#endif /* WINPR_CMDLINE_H */

View File

@@ -0,0 +1,928 @@
/**
* WinPR: Windows Portable Runtime
* Collections
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_COLLECTIONS_H
#define WINPR_COLLECTIONS_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/assert.h>
#include <winpr/crt.h>
#include <winpr/synch.h>
#include <winpr/stream.h>
#ifdef __cplusplus
extern "C"
{
#endif
typedef void* (*OBJECT_NEW_FN)(const void* val);
typedef void (*OBJECT_INIT_FN)(void* obj);
typedef void (*OBJECT_UNINIT_FN)(void* obj);
typedef void (*OBJECT_FREE_FN)(void* obj);
typedef BOOL (*OBJECT_EQUALS_FN)(const void* objA, const void* objB);
/** @struct wObject
* @brief This struct contains function pointer to initialize/free objects
*
*/
typedef struct
{
OBJECT_NEW_FN fnObjectNew; /**< A new function that creates a clone of the input */
OBJECT_INIT_FN
fnObjectInit; /**< A function initializing an object, but not allocating it */
OBJECT_UNINIT_FN
fnObjectUninit; /**< A function to deinitialize an object, but not free it */
OBJECT_FREE_FN fnObjectFree; /**< A function freeing an object */
OBJECT_EQUALS_FN fnObjectEquals; /**< A function to compare two objects */
} wObject;
/* utility function with compatible arguments for string data */
/** @brief helper function to clone a string
* @param pvstr the source string to clone
* @return A clone of the source or \b nullptr
* @since version 3.3.0
*/
WINPR_API void* winpr_ObjectStringClone(const void* pvstr);
/** @brief helper function to clone a WCHAR string
* @param pvstr the source string to clone
* @return A clone of the source or \b nullptr
* @since version 3.3.0
*/
WINPR_API void* winpr_ObjectWStringClone(const void* pvstr);
/** @brief helper function to free a (WCHAR) string
* @param pvstr the string to free
* @since version 3.3.0
*/
WINPR_API void winpr_ObjectStringFree(void* pvstr);
/* System.Collections.Queue */
typedef struct s_wQueue wQueue;
/** @brief Return the number of elements in the queue
*
* @param queue A pointer to a queue, must not be \b nullptr
*
* @return the number of objects queued
*/
WINPR_API size_t Queue_Count(wQueue* queue);
/** @brief Return the allocated elements in the queue
*
* @param queue A pointer to a queue, must not be \b nullptr
*
* @return the number of objects allocated
*/
WINPR_API size_t Queue_Capacity(wQueue* queue);
/** @brief Mutex-Lock a queue
*
* @param queue A pointer to a queue, must not be \b nullptr
*/
WINPR_API void Queue_Lock(wQueue* queue);
/** @brief Mutex-Unlock a queue
*
* @param queue A pointer to a queue, must not be \b nullptr
*/
WINPR_API void Queue_Unlock(wQueue* queue);
/** @brief Get an event handle for the queue, usable by \b WaitForSingleObject or \b
* WaitForMultipleObjects
*
* @param queue A pointer to a queue, must not be \b nullptr
*/
WINPR_API HANDLE Queue_Event(wQueue* queue);
/** @brief Mutex-Lock a queue
*
* @param queue A pointer to a queue, must not be \b nullptr
*
* @return A pointer to a \b wObject that contains the allocation/cleanup handlers for queue
* elements
*/
WINPR_API wObject* Queue_Object(wQueue* queue);
/** @brief Remove all elements from a queue, call \b wObject cleanup functions \b fnObjectFree
*
* @param queue A pointer to a queue, must not be \b nullptr
*/
WINPR_API void Queue_Clear(wQueue* queue);
/** @brief Check if the queue contains an object
*
* @param queue A pointer to a queue, must not be \b nullptr
* @param obj The object to look for. \b fnObjectEquals is called internally
*
* @return \b TRUE if the object was found, \b FALSE otherwise.
*/
WINPR_API BOOL Queue_Contains(wQueue* queue, const void* obj);
/** \brief Pushes a new element into the queue.
* If a \b fnObjectNew is set, the element is copied and the queue takes
* ownership of the memory, otherwise the ownership stays with the caller.
*
* \param queue The queue to operate on
* \param obj A pointer to the object to queue
*
* \return TRUE for success, FALSE if failed.
*/
WINPR_API BOOL Queue_Enqueue(wQueue* queue, const void* obj);
/** \brief returns the element at the top of the queue. The element is removed from the queue,
* ownership of the element is passed on to the caller.
*
* \param queue The queue to check
*
* \return nullptr if empty, a pointer to the memory on top of the queue otherwise.
*/
WINPR_API void* Queue_Dequeue(wQueue* queue);
/** \brief returns the element at the top of the queue. The element is not removed from the
* queue, ownership of the element stays with the queue.
*
* \param queue The queue to check
*
* \return nullptr if empty, a pointer to the memory on top of the queue otherwise.
*/
WINPR_API void* Queue_Peek(wQueue* queue);
/** \brief Removes the element at the top of the queue. If fnObjectFree is set, the element is
* freed. This can be used in combination with Queue_Peek to handle an element and discard it
* with this function afterward. An alternative is Queue_Dequeue with calling the appropriate
* free function afterward.
*
* \param queue The queue to operate on
*/
WINPR_API void Queue_Discard(wQueue* queue);
/** @brief Clean up a queue, free all resources (e.g. calls \b Queue_Clear)
*
* @param queue The queue to free, may be \b nullptr
*/
WINPR_API void Queue_Free(wQueue* queue);
/** @brief Creates a new queue
*
* @param synchronized If \b TRUE all functions are thread safe, if \b FALSE no synchronization
* is done.
* @param capacity The initial capacity of the queue. If \b 0 or \b -1 default settings are
* applied.
* @param growthFactor allocation behaviour when the queue capacity should be increased. Larger
* values increase the allocation contingent. \b 0 or \b -1 apply default settings.
*
*
* @return A newly allocated queue or \b nullptr in case of failure
*/
WINPR_ATTR_MALLOC(Queue_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API wQueue* Queue_New(BOOL synchronized, SSIZE_T capacity, SSIZE_T growthFactor);
/* System.Collections.Stack */
typedef struct s_wStack wStack;
WINPR_API size_t Stack_Count(wStack* stack);
WINPR_API BOOL Stack_IsSynchronized(wStack* stack);
WINPR_API wObject* Stack_Object(wStack* stack);
WINPR_API void Stack_Clear(wStack* stack);
WINPR_API BOOL Stack_Contains(wStack* stack, const void* obj);
WINPR_API void Stack_Push(wStack* stack, void* obj);
WINPR_API void* Stack_Pop(wStack* stack);
WINPR_API void* Stack_Peek(wStack* stack);
WINPR_API void Stack_Free(wStack* stack);
WINPR_ATTR_MALLOC(Stack_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API wStack* Stack_New(BOOL synchronized);
/* System.Collections.ArrayList */
typedef struct s_wArrayList wArrayList;
WINPR_API size_t ArrayList_Capacity(wArrayList* arrayList);
WINPR_API size_t ArrayList_Count(wArrayList* arrayList);
WINPR_API size_t ArrayList_Items(wArrayList* arrayList, ULONG_PTR** ppItems);
WINPR_API BOOL ArrayList_IsFixedSized(wArrayList* arrayList);
WINPR_API BOOL ArrayList_IsReadOnly(wArrayList* arrayList);
WINPR_API BOOL ArrayList_IsSynchronized(wArrayList* arrayList);
WINPR_API void ArrayList_Lock(wArrayList* arrayList);
WINPR_API void ArrayList_Unlock(wArrayList* arrayList);
WINPR_API void* ArrayList_GetItem(wArrayList* arrayList, size_t index);
WINPR_API BOOL ArrayList_SetItem(wArrayList* arrayList, size_t index, const void* obj);
WINPR_API wObject* ArrayList_Object(wArrayList* arrayList);
typedef BOOL (*ArrayList_ForEachFkt)(void* data, size_t index, va_list ap);
WINPR_API BOOL ArrayList_ForEach(wArrayList* arrayList, ArrayList_ForEachFkt fkt, ...);
WINPR_API BOOL ArrayList_ForEachAP(wArrayList* arrayList, ArrayList_ForEachFkt fkt, va_list ap);
WINPR_API void ArrayList_Clear(wArrayList* arrayList);
WINPR_API BOOL ArrayList_Contains(wArrayList* arrayList, const void* obj);
#if defined(WITH_WINPR_DEPRECATED)
WINPR_DEPRECATED(WINPR_API int ArrayList_Add(wArrayList* arrayList, const void* obj));
#endif
WINPR_API BOOL ArrayList_Append(wArrayList* arrayList, const void* obj);
WINPR_API BOOL ArrayList_Insert(wArrayList* arrayList, size_t index, const void* obj);
WINPR_API BOOL ArrayList_Remove(wArrayList* arrayList, const void* obj);
WINPR_API BOOL ArrayList_RemoveAt(wArrayList* arrayList, size_t index);
WINPR_API SSIZE_T ArrayList_IndexOf(wArrayList* arrayList, const void* obj, SSIZE_T startIndex,
SSIZE_T count);
WINPR_API SSIZE_T ArrayList_LastIndexOf(wArrayList* arrayList, const void* obj,
SSIZE_T startIndex, SSIZE_T count);
WINPR_API void ArrayList_Free(wArrayList* arrayList);
WINPR_ATTR_MALLOC(ArrayList_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API wArrayList* ArrayList_New(BOOL synchronized);
/* System.Collections.DictionaryBase */
/* System.Collections.Specialized.ListDictionary */
typedef struct s_wListDictionary wListDictionary;
/** @brief Get the \b wObject function pointer struct for the \b key of the dictionary.
*
* @param listDictionary A dictionary to query, must not be \b nullptr
*
* @return a \b wObject used to initialize the key object, \b nullptr in case of failure
*/
WINPR_API wObject* ListDictionary_KeyObject(wListDictionary* listDictionary);
/** @brief Get the \b wObject function pointer struct for the \b value of the dictionary.
*
* @param listDictionary A dictionary to query, must not be \b nullptr
*
* @return a \b wObject used to initialize the value object, \b nullptr in case of failure
*/
WINPR_API wObject* ListDictionary_ValueObject(wListDictionary* listDictionary);
/** @brief Return the number of entries in the dictionary
*
* @param listDictionary A dictionary to query, must not be \b nullptr
*
* @return the number of entries
*/
WINPR_API size_t ListDictionary_Count(wListDictionary* listDictionary);
/** @brief mutex-lock a dictionary
*
* @param listDictionary A dictionary to query, must not be \b nullptr
*/
WINPR_API void ListDictionary_Lock(wListDictionary* listDictionary);
/** @brief mutex-unlock a dictionary
*
* @param listDictionary A dictionary to query, must not be \b nullptr
*/
WINPR_API void ListDictionary_Unlock(wListDictionary* listDictionary);
/** @brief mutex-lock a dictionary
*
* @param listDictionary A dictionary to query, must not be \b nullptr
* @param key The key identifying the entry, if set cloned with \b fnObjectNew
* @param value The value to store for the \b key. May be \b nullptr. if set cloned with \b
* fnObjectNew
*
* @return \b TRUE for successful addition, \b FALSE for failure
*/
WINPR_API BOOL ListDictionary_Add(wListDictionary* listDictionary, const void* key,
const void* value);
/** @brief Remove an item from the dictionary and return the value. Cleanup is up to the caller.
*
* @param listDictionary A dictionary to query, must not be \b nullptr
* @param key The key identifying the entry
*
* @return a pointer to the value stored or \b nullptr in case of failure or not found
*/
WINPR_API void* ListDictionary_Take(wListDictionary* listDictionary, const void* key);
/** @brief Remove an item from the dictionary and call \b fnObjectFree for key and value
*
* @param listDictionary A dictionary to query, must not be \b nullptr
* @param key The key identifying the entry
*/
WINPR_API void ListDictionary_Remove(wListDictionary* listDictionary, const void* key);
/** @brief Remove the head item from the dictionary and return the value. Cleanup is up to the
* caller.
*
* @param listDictionary A dictionary to query, must not be \b nullptr
*
* @return a pointer to the value stored or \b nullptr in case of failure or not found
*/
WINPR_API void* ListDictionary_Take_Head(wListDictionary* listDictionary);
/** @brief Remove the head item from the dictionary and call \b fnObjectFree for key and value
*
* @param listDictionary A dictionary to query, must not be \b nullptr
*/
WINPR_API void ListDictionary_Remove_Head(wListDictionary* listDictionary);
/** @brief Remove all items from the dictionary and call \b fnObjectFree for key and value
*
* @param listDictionary A dictionary to query, must not be \b nullptr
*/
WINPR_API void ListDictionary_Clear(wListDictionary* listDictionary);
/** @brief Check if a dictionary contains \b key (\b fnObjectEquals of the key object is called)
*
* @param listDictionary A dictionary to query, must not be \b nullptr
* @param key A key to look for
*
* @return \b TRUE if found, \b FALSE otherwise
*/
WINPR_API BOOL ListDictionary_Contains(wListDictionary* listDictionary, const void* key);
/** @brief return all keys the dictionary contains
*
* @param listDictionary A dictionary to query, must not be \b nullptr
* @param ppKeys A pointer to a \b ULONG_PTR array that will hold the result keys. Call \b free
* if no longer required
*
* @return the number of keys found in the dictionary or \b 0 if \b ppKeys is \b nullptr
*/
WINPR_API size_t ListDictionary_GetKeys(wListDictionary* listDictionary, ULONG_PTR** ppKeys);
/** @brief Get the value in the dictionary for a \b key. The ownership of the data stays with
* the dictionary.
*
* @param listDictionary A dictionary to query, must not be \b nullptr
* @param key A key to look for (\b fnObjectEquals of the key object is called)
*
* @return A pointer to the data in the dictionary or \b nullptr if not found
*/
WINPR_API void* ListDictionary_GetItemValue(wListDictionary* listDictionary, const void* key);
/** @brief Set the value in the dictionary for a \b key. The entry must already exist, \b value
* is copied if \b fnObjectNew is set
*
* @param listDictionary A dictionary to query, must not be \b nullptr
* @param key A key to look for (\b fnObjectEquals of the key object is called)
* @param value A pointer to the value to set
*
* @return \b TRUE for success, \b FALSE in case of failure
*/
WINPR_API BOOL ListDictionary_SetItemValue(wListDictionary* listDictionary, const void* key,
const void* value);
/** @brief Free memory allocated by a dictionary. Calls \b ListDictionary_Clear
*
* @param listDictionary A dictionary to query, may be \b nullptr
*/
WINPR_API void ListDictionary_Free(wListDictionary* listDictionary);
/** @brief allocate a new dictionary
*
* @param synchronized Create the dictionary with automatic mutex lock
*
* @return A newly allocated dictionary or \b nullptr in case of failure
*/
WINPR_ATTR_MALLOC(ListDictionary_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API wListDictionary* ListDictionary_New(BOOL synchronized);
/* System.Collections.Generic.LinkedList<T> */
typedef struct s_wLinkedList wLinkedList;
/** @brief Return the current number of elements in the linked list
*
* @param list A pointer to the list, must not be \b nullptr
*
* @return the number of elements in the list
*/
WINPR_API size_t LinkedList_Count(wLinkedList* list);
/** @brief Return the first element of the list, ownership stays with the list
*
* @param list A pointer to the list, must not be \b nullptr
*
* @return A pointer to the element or \b nullptr if empty
*/
WINPR_API void* LinkedList_First(wLinkedList* list);
/** @brief Return the last element of the list, ownership stays with the list
*
* @param list A pointer to the list, must not be \b nullptr
*
* @return A pointer to the element or \b nullptr if empty
*/
WINPR_API void* LinkedList_Last(wLinkedList* list);
/** @brief Check if the linked list contains a value
*
* @param list A pointer to the list, must not be \b nullptr
* @param value A value to check for
*
* @return \b TRUE if found, \b FALSE otherwise
*/
WINPR_API BOOL LinkedList_Contains(wLinkedList* list, const void* value);
/** @brief Remove all elements of the linked list. \b fnObjectUninit and \b fnObjectFree are
* called for each entry
*
* @param list A pointer to the list, must not be \b nullptr
*
*/
WINPR_API void LinkedList_Clear(wLinkedList* list);
/** @brief Add a new element at the start of the linked list. \b fnObjectNew and \b fnObjectInit
* is called for the new entry
*
* @param list A pointer to the list, must not be \b nullptr
* @param value The value to add
*
* @return \b TRUE if successful, \b FALSE otherwise.
*/
WINPR_API BOOL LinkedList_AddFirst(wLinkedList* list, const void* value);
/** @brief Add a new element at the end of the linked list. \b fnObjectNew and \b fnObjectInit
* is called for the new entry
*
* @param list A pointer to the list, must not be \b nullptr
* @param value The value to add
*
* @return \b TRUE if successful, \b FALSE otherwise.
*/
WINPR_API BOOL LinkedList_AddLast(wLinkedList* list, const void* value);
/** @brief Remove a element identified by \b value from the linked list. \b fnObjectUninit and
* \b fnObjectFree is called for the entry
*
* @param list A pointer to the list, must not be \b nullptr
* @param value The value to remove
*
* @return \b TRUE if successful, \b FALSE otherwise.
*/
WINPR_API BOOL LinkedList_Remove(wLinkedList* list, const void* value);
/** @brief Remove the first element from the linked list. \b fnObjectUninit and \b fnObjectFree
* is called for the entry
*
* @param list A pointer to the list, must not be \b nullptr
*
*/
WINPR_API void LinkedList_RemoveFirst(wLinkedList* list);
/** @brief Remove the last element from the linked list. \b fnObjectUninit and \b fnObjectFree
* is called for the entry
*
* @param list A pointer to the list, must not be \b nullptr
*
*/
WINPR_API void LinkedList_RemoveLast(wLinkedList* list);
/** @brief Move enumerator to the first element
*
* @param list A pointer to the list, must not be \b nullptr
*
*/
WINPR_API void LinkedList_Enumerator_Reset(wLinkedList* list);
/** @brief Return the value for the current position of the enumerator
*
* @param list A pointer to the list, must not be \b nullptr
*
* @return A pointer to the current entry or \b nullptr
*/
WINPR_API void* LinkedList_Enumerator_Current(wLinkedList* list);
/** @brief Move enumerator to the next element
*
* @param list A pointer to the list, must not be \b nullptr
*
* @return \b TRUE if the move was successful, \b FALSE if not (e.g. no more entries)
*/
WINPR_API BOOL LinkedList_Enumerator_MoveNext(wLinkedList* list);
/** @brief Free a linked list
*
* @param list A pointer to the list, may be \b nullptr
*/
WINPR_API void LinkedList_Free(wLinkedList* list);
/** @brief Allocate a linked list
*
* @return A pointer to the newly allocated linked list or \b nullptr in case of failure
*/
WINPR_ATTR_MALLOC(LinkedList_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API wLinkedList* LinkedList_New(void);
/** @brief Return the \b wObject function pointers for list elements
*
* @param list A pointer to the list, must not be \b nullptr
*
* @return A pointer to the wObject or \b nullptr in case of failure
*/
WINPR_API wObject* LinkedList_Object(wLinkedList* list);
/* System.Collections.Generic.KeyValuePair<TKey,TValue> */
/* Countdown Event */
typedef struct CountdownEvent wCountdownEvent;
/** @brief return the current event count of the CountdownEvent
*
* @param countdown A pointer to a CountdownEvent, must not be \b nullptr
*
* @return The current event count
*/
WINPR_API size_t CountdownEvent_CurrentCount(wCountdownEvent* countdown);
/** @brief return the initial event count of the CountdownEvent
*
* @param countdown A pointer to a CountdownEvent, must not be \b nullptr
*
* @return The initial event count
*/
WINPR_API size_t CountdownEvent_InitialCount(wCountdownEvent* countdown);
/** @brief return the current event state of the CountdownEvent
*
* @param countdown A pointer to a CountdownEvent, must not be \b nullptr
*
* @return \b TRUE if set, \b FALSE otherwise
*/
WINPR_API BOOL CountdownEvent_IsSet(wCountdownEvent* countdown);
/** @brief return the event HANDLE of the CountdownEvent to be used by \b WaitForSingleObject or
* \b WaitForMultipleObjects
*
* @param countdown A pointer to a CountdownEvent, must not be \b nullptr
*
* @return a \b HANDLE or \b nullptr in case of failure
*/
WINPR_API HANDLE CountdownEvent_WaitHandle(wCountdownEvent* countdown);
/** @brief add \b signalCount to the current event count of the CountdownEvent
*
* @param countdown A pointer to a CountdownEvent, must not be \b nullptr
* @param signalCount The amount to add to CountdownEvent
*
*/
WINPR_API void CountdownEvent_AddCount(wCountdownEvent* countdown, size_t signalCount);
/** @brief Increase the current event signal state of the CountdownEvent
*
* @param countdown A pointer to a CountdownEvent, must not be \b nullptr
* @param signalCount The amount of signaled events to add
*
* @return \b TRUE if event is set, \b FALSE otherwise
*/
WINPR_API BOOL CountdownEvent_Signal(wCountdownEvent* countdown, size_t signalCount);
/** @brief reset the CountdownEvent
*
* @param countdown A pointer to a CountdownEvent, must not be \b nullptr
*
*/
WINPR_API void CountdownEvent_Reset(wCountdownEvent* countdown, size_t count);
/** @brief Free a CountdownEvent
*
* @param countdown A pointer to a CountdownEvent, may be \b nullptr
*/
WINPR_API void CountdownEvent_Free(wCountdownEvent* countdown);
/** @brief Allocate a CountdownEvent with \b initialCount
*
* @param initialCount The initial value of the event
*
* @return The newly allocated event or \b nullptr in case of failure
*/
WINPR_ATTR_MALLOC(CountdownEvent_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API wCountdownEvent* CountdownEvent_New(size_t initialCount);
/* Hash Table */
typedef UINT32 (*HASH_TABLE_HASH_FN)(const void* key);
typedef struct s_wHashTable wHashTable;
typedef BOOL (*HASH_TABLE_FOREACH_FN)(const void* key, void* value, void* arg);
WINPR_API size_t HashTable_Count(wHashTable* table);
#if defined(WITH_WINPR_DEPRECATED)
WINPR_DEPRECATED(WINPR_API int HashTable_Add(wHashTable* table, const void* key,
const void* value));
#endif
WINPR_API BOOL HashTable_Insert(wHashTable* table, const void* key, const void* value);
WINPR_API BOOL HashTable_Remove(wHashTable* table, const void* key);
WINPR_API void HashTable_Clear(wHashTable* table);
WINPR_API BOOL HashTable_Contains(wHashTable* table, const void* key);
WINPR_API BOOL HashTable_ContainsKey(wHashTable* table, const void* key);
WINPR_API BOOL HashTable_ContainsValue(wHashTable* table, const void* value);
WINPR_API void* HashTable_GetItemValue(wHashTable* table, const void* key);
WINPR_API BOOL HashTable_SetItemValue(wHashTable* table, const void* key, const void* value);
WINPR_API size_t HashTable_GetKeys(wHashTable* table, ULONG_PTR** ppKeys);
WINPR_API BOOL HashTable_Foreach(wHashTable* table, HASH_TABLE_FOREACH_FN fn, VOID* arg);
WINPR_API UINT32 HashTable_PointerHash(const void* pointer);
WINPR_API BOOL HashTable_PointerCompare(const void* pointer1, const void* pointer2);
WINPR_API UINT32 HashTable_StringHash(const void* key);
WINPR_API BOOL HashTable_StringCompare(const void* string1, const void* string2);
WINPR_API void* HashTable_StringClone(const void* str);
WINPR_API void HashTable_StringFree(void* str);
WINPR_API void HashTable_Free(wHashTable* table);
WINPR_ATTR_MALLOC(HashTable_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API wHashTable* HashTable_New(BOOL synchronized);
WINPR_API void HashTable_Lock(wHashTable* table);
WINPR_API void HashTable_Unlock(wHashTable* table);
WINPR_API wObject* HashTable_KeyObject(wHashTable* table);
WINPR_API wObject* HashTable_ValueObject(wHashTable* table);
WINPR_API BOOL HashTable_SetHashFunction(wHashTable* table, HASH_TABLE_HASH_FN fn);
/* Utility function to setup hash table for strings */
WINPR_API BOOL HashTable_SetupForStringData(wHashTable* table, BOOL stringValues);
/* BufferPool */
typedef struct s_wBufferPool wBufferPool;
WINPR_API SSIZE_T BufferPool_GetPoolSize(wBufferPool* pool);
WINPR_API SSIZE_T BufferPool_GetBufferSize(wBufferPool* pool, const void* buffer);
WINPR_API void* BufferPool_Take(wBufferPool* pool, SSIZE_T bufferSize);
WINPR_API BOOL BufferPool_Return(wBufferPool* pool, void* buffer);
WINPR_API void BufferPool_Clear(wBufferPool* pool);
WINPR_API void BufferPool_Free(wBufferPool* pool);
WINPR_ATTR_MALLOC(BufferPool_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API wBufferPool* BufferPool_New(BOOL synchronized, SSIZE_T fixedSize, DWORD alignment);
/* ObjectPool */
typedef struct s_wObjectPool wObjectPool;
WINPR_API void* ObjectPool_Take(wObjectPool* pool);
WINPR_API void ObjectPool_Return(wObjectPool* pool, void* obj);
WINPR_API void ObjectPool_Clear(wObjectPool* pool);
WINPR_API wObject* ObjectPool_Object(wObjectPool* pool);
WINPR_API void ObjectPool_Free(wObjectPool* pool);
WINPR_ATTR_MALLOC(ObjectPool_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API wObjectPool* ObjectPool_New(BOOL synchronized);
/* Message Queue */
typedef struct s_wMessage wMessage;
typedef void (*MESSAGE_FREE_FN)(wMessage* message);
struct s_wMessage
{
UINT32 id;
void* context;
void* wParam;
void* lParam;
UINT64 time;
MESSAGE_FREE_FN Free;
};
typedef struct s_wMessageQueue wMessageQueue;
#define WMQ_QUIT 0xFFFFFFFF
WINPR_API wObject* MessageQueue_Object(wMessageQueue* queue);
WINPR_API HANDLE MessageQueue_Event(wMessageQueue* queue);
WINPR_API BOOL MessageQueue_Wait(wMessageQueue* queue);
/** @brief return the currently used number of elements in the queue
*
* @param queue A pointer to the queue to query. Must not be \b nullptr
*
* @return The number of elements in the queue
*/
WINPR_API size_t MessageQueue_Size(wMessageQueue* queue);
/** @brief return the currently allocated elements in the queue
*
* @param queue A pointer to the queue to query. Must not be \b nullptr
*
* @return The number of currently allocated elements in the queue
*/
WINPR_API size_t MessageQueue_Capacity(wMessageQueue* queue);
WINPR_API BOOL MessageQueue_Dispatch(wMessageQueue* queue, const wMessage* message);
WINPR_API BOOL MessageQueue_Post(wMessageQueue* queue, void* context, UINT32 type, void* wParam,
void* lParam);
WINPR_API BOOL MessageQueue_PostQuit(wMessageQueue* queue, int nExitCode);
WINPR_API int MessageQueue_Get(wMessageQueue* queue, wMessage* message);
WINPR_API int MessageQueue_Peek(wMessageQueue* queue, wMessage* message, BOOL remove);
/*! \brief Clears all elements in a message queue.
*
* \note If dynamically allocated data is part of the messages,
* a custom cleanup handler must be passed in the 'callback'
* argument for MessageQueue_New.
*
* \param queue The queue to clear.
*
* \return 0 in case of success or a error code otherwise.
*/
WINPR_API int MessageQueue_Clear(wMessageQueue* queue);
/*! \brief Frees resources allocated by a message queue.
* This function will only free resources allocated
* internally.
*
* \note Empty the queue before calling this function with
* 'MessageQueue_Clear', 'MessageQueue_Get' or
* 'MessageQueue_Peek' to free all resources allocated
* by the message contained.
*
* \param queue A pointer to the queue to be freed.
*/
WINPR_API void MessageQueue_Free(wMessageQueue* queue);
/*! \brief Creates a new message queue.
* If 'callback' is null, no custom cleanup will be done
* on message queue deallocation.
* If the 'callback' argument contains valid uninit or
* free functions those will be called by
* 'MessageQueue_Clear'.
*
* \param callback a pointer to custom initialization / cleanup functions.
* Can be nullptr if not used.
*
* \return A pointer to a newly allocated MessageQueue or nullptr.
*/
WINPR_ATTR_MALLOC(MessageQueue_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API wMessageQueue* MessageQueue_New(const wObject* callback);
/* Message Pipe */
typedef struct
{
wMessageQueue* In;
wMessageQueue* Out;
} wMessagePipe;
WINPR_API void MessagePipe_PostQuit(wMessagePipe* pipe, int nExitCode);
WINPR_API void MessagePipe_Free(wMessagePipe* pipe);
WINPR_ATTR_MALLOC(MessagePipe_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API wMessagePipe* MessagePipe_New(void);
/* Publisher/Subscriber Pattern */
typedef struct
{
DWORD Size;
const char* Sender;
} wEventArgs;
typedef void (*pEventHandler)(void* context, const wEventArgs* e);
#ifdef __cplusplus
#define WINPR_EVENT_CAST(t, val) reinterpret_cast<t>(val)
#else
#define WINPR_EVENT_CAST(t, val) (t)(val)
#endif
#define MAX_EVENT_HANDLERS 32
typedef struct
{
const char* EventName;
wEventArgs EventArgs;
size_t EventHandlerCount;
pEventHandler EventHandlers[MAX_EVENT_HANDLERS];
} wEventType;
#define EventArgsInit(_event_args, _sender) \
memset(_event_args, 0, sizeof(*_event_args)); \
(_event_args)->e.Size = sizeof(*_event_args); \
(_event_args)->e.Sender = _sender
#define DEFINE_EVENT_HANDLER(name) \
typedef void (*p##name##EventHandler)(void* context, const name##EventArgs* e)
#define DEFINE_EVENT_RAISE(name) \
static inline int PubSub_On##name(wPubSub* pubSub, void* context, const name##EventArgs* e) \
{ \
WINPR_ASSERT(e); \
return PubSub_OnEvent(pubSub, #name, context, &e->e); \
}
#define DEFINE_EVENT_SUBSCRIBE(name) \
static inline int PubSub_Subscribe##name(wPubSub* pubSub, p##name##EventHandler EventHandler) \
{ \
return PubSub_Subscribe(pubSub, #name, EventHandler); \
}
#define DEFINE_EVENT_UNSUBSCRIBE(name) \
static inline int PubSub_Unsubscribe##name(wPubSub* pubSub, \
p##name##EventHandler EventHandler) \
{ \
return PubSub_Unsubscribe(pubSub, #name, EventHandler); \
}
#define DEFINE_EVENT_BEGIN(name) \
typedef struct \
{ \
wEventArgs e;
#define DEFINE_EVENT_END(name) \
} \
name##EventArgs; \
DEFINE_EVENT_HANDLER(name); \
DEFINE_EVENT_RAISE(name) \
DEFINE_EVENT_SUBSCRIBE(name) \
DEFINE_EVENT_UNSUBSCRIBE(name)
#define DEFINE_EVENT_ENTRY(name) \
{ \
#name, { sizeof(name##EventArgs), nullptr }, 0, \
{ \
nullptr \
} \
}
typedef struct s_wPubSub wPubSub;
WINPR_API void PubSub_Lock(wPubSub* pubSub);
WINPR_API void PubSub_Unlock(wPubSub* pubSub);
WINPR_API wEventType* PubSub_GetEventTypes(wPubSub* pubSub, size_t* count);
WINPR_API void PubSub_AddEventTypes(wPubSub* pubSub, wEventType* events, size_t count);
WINPR_API wEventType* PubSub_FindEventType(wPubSub* pubSub, const char* EventName);
WINPR_API int PubSub_Subscribe(wPubSub* pubSub, const char* EventName, ...);
WINPR_API int PubSub_Unsubscribe(wPubSub* pubSub, const char* EventName, ...);
WINPR_API int PubSub_OnEvent(wPubSub* pubSub, const char* EventName, void* context,
const wEventArgs* e);
WINPR_API void PubSub_Free(wPubSub* pubSub);
WINPR_ATTR_MALLOC(PubSub_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API wPubSub* PubSub_New(BOOL synchronized);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_COLLECTIONS_H */

View File

@@ -0,0 +1,510 @@
/**
* WinPR: Windows Portable Runtime
* Serial Communication API
*
* Copyright 2011 O.S. Systems Software Ltda.
* Copyright 2011 Eduardo Fiss Beloni <beloni@ossystems.com.br>
* Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_COMM_H
#define WINPR_COMM_H
#include <winpr/collections.h>
#include <winpr/file.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#define NOPARITY 0
#define ODDPARITY 1
#define EVENPARITY 2
#define MARKPARITY 3
#define SPACEPARITY 4
#define ONESTOPBIT 0
#define ONE5STOPBITS 1
#define TWOSTOPBITS 2
#ifndef IGNORE
#define IGNORE 0
#endif
#define CBR_110 110
#define CBR_300 300
#define CBR_600 600
#define CBR_1200 1200
#define CBR_2400 2400
#define CBR_4800 4800
#define CBR_9600 9600
#define CBR_14400 14400
#define CBR_19200 19200
#define CBR_38400 38400
#define CBR_56000 56000
#define CBR_57600 57600
#define CBR_115200 115200
#define CBR_128000 128000
#define CBR_256000 256000
#define CE_RXOVER 0x0001
#define CE_OVERRUN 0x0002
#define CE_RXPARITY 0x0004
#define CE_FRAME 0x0008
#define CE_BREAK 0x0010
#define CE_TXFULL 0x0100
#define CE_PTO 0x0200
#define CE_IOE 0x0400
#define CE_DNS 0x0800
#define CE_OOP 0x1000
#define CE_MODE 0x8000
#define IE_BADID (-1)
#define IE_OPEN (-2)
#define IE_NOPEN (-3)
#define IE_MEMORY (-4)
#define IE_DEFAULT (-5)
#define IE_HARDWARE (-10)
#define IE_BYTESIZE (-11)
#define IE_BAUDRATE (-12)
#define EV_RXCHAR 0x0001
#define EV_RXFLAG 0x0002
#define EV_TXEMPTY 0x0004
#define EV_CTS 0x0008
#define EV_DSR 0x0010
#define EV_RLSD 0x0020
#define EV_BREAK 0x0040
#define EV_ERR 0x0080
#define EV_RING 0x0100
#define EV_PERR 0x0200
#define EV_RX80FULL 0x0400
#define EV_EVENT1 0x0800
#define EV_EVENT2 0x1000
#define SETXOFF 1
#define SETXON 2
#define SETRTS 3
#define CLRRTS 4
#define SETDTR 5
#define CLRDTR 6
#define RESETDEV 7
#define SETBREAK 8
#define CLRBREAK 9
#define PURGE_TXABORT 0x0001
#define PURGE_RXABORT 0x0002
#define PURGE_TXCLEAR 0x0004
#define PURGE_RXCLEAR 0x0008
#define LPTx 0x80
#define MS_CTS_ON ((DWORD)0x0010)
#define MS_DSR_ON ((DWORD)0x0020)
#define MS_RING_ON ((DWORD)0x0040)
#define MS_RLSD_ON ((DWORD)0x0080)
#define SP_SERIALCOMM ((DWORD)0x00000001)
#define PST_UNSPECIFIED ((DWORD)0x00000000)
#define PST_RS232 ((DWORD)0x00000001)
#define PST_PARALLELPORT ((DWORD)0x00000002)
#define PST_RS422 ((DWORD)0x00000003)
#define PST_RS423 ((DWORD)0x00000004)
#define PST_RS449 ((DWORD)0x00000005)
#define PST_MODEM ((DWORD)0x00000006)
#define PST_FAX ((DWORD)0x00000021)
#define PST_SCANNER ((DWORD)0x00000022)
#define PST_NETWORK_BRIDGE ((DWORD)0x00000100)
#define PST_LAT ((DWORD)0x00000101)
#define PST_TCPIP_TELNET ((DWORD)0x00000102)
#define PST_X25 ((DWORD)0x00000103)
#define PCF_DTRDSR ((DWORD)0x0001)
#define PCF_RTSCTS ((DWORD)0x0002)
#define PCF_RLSD ((DWORD)0x0004)
#define PCF_PARITY_CHECK ((DWORD)0x0008)
#define PCF_XONXOFF ((DWORD)0x0010)
#define PCF_SETXCHAR ((DWORD)0x0020)
#define PCF_TOTALTIMEOUTS ((DWORD)0x0040)
#define PCF_INTTIMEOUTS ((DWORD)0x0080)
#define PCF_SPECIALCHARS ((DWORD)0x0100)
#define PCF_16BITMODE ((DWORD)0x0200)
#define SP_PARITY ((DWORD)0x0001)
#define SP_BAUD ((DWORD)0x0002)
#define SP_DATABITS ((DWORD)0x0004)
#define SP_STOPBITS ((DWORD)0x0008)
#define SP_HANDSHAKING ((DWORD)0x0010)
#define SP_PARITY_CHECK ((DWORD)0x0020)
#define SP_RLSD ((DWORD)0x0040)
#define BAUD_075 ((DWORD)0x00000001)
#define BAUD_110 ((DWORD)0x00000002)
#define BAUD_134_5 ((DWORD)0x00000004)
#define BAUD_150 ((DWORD)0x00000008)
#define BAUD_300 ((DWORD)0x00000010)
#define BAUD_600 ((DWORD)0x00000020)
#define BAUD_1200 ((DWORD)0x00000040)
#define BAUD_1800 ((DWORD)0x00000080)
#define BAUD_2400 ((DWORD)0x00000100)
#define BAUD_4800 ((DWORD)0x00000200)
#define BAUD_7200 ((DWORD)0x00000400)
#define BAUD_9600 ((DWORD)0x00000800)
#define BAUD_14400 ((DWORD)0x00001000)
#define BAUD_19200 ((DWORD)0x00002000)
#define BAUD_38400 ((DWORD)0x00004000)
#define BAUD_56K ((DWORD)0x00008000)
#define BAUD_128K ((DWORD)0x00010000)
#define BAUD_115200 ((DWORD)0x00020000)
#define BAUD_57600 ((DWORD)0x00040000)
#define BAUD_USER ((DWORD)0x10000000)
#define DATABITS_5 ((WORD)0x0001)
#define DATABITS_6 ((WORD)0x0002)
#define DATABITS_7 ((WORD)0x0004)
#define DATABITS_8 ((WORD)0x0008)
#define DATABITS_16 ((WORD)0x0010)
#define DATABITS_16X ((WORD)0x0020)
#define STOPBITS_10 ((WORD)0x0001)
#define STOPBITS_15 ((WORD)0x0002)
#define STOPBITS_20 ((WORD)0x0004)
#define PARITY_NONE ((WORD)0x0100)
#define PARITY_ODD ((WORD)0x0200)
#define PARITY_EVEN ((WORD)0x0400)
#define PARITY_MARK ((WORD)0x0800)
#define PARITY_SPACE ((WORD)0x1000)
#define COMMPROP_INITIALIZED ((DWORD)0xE73CF52E)
#define DTR_CONTROL_DISABLE 0x00
#define DTR_CONTROL_ENABLE 0x01
#define DTR_CONTROL_HANDSHAKE 0x02
#define RTS_CONTROL_DISABLE 0x00
#define RTS_CONTROL_ENABLE 0x01
#define RTS_CONTROL_HANDSHAKE 0x02
#define RTS_CONTROL_TOGGLE 0x03
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa363214%28v=vs.85%29.aspx
typedef struct
{
DWORD DCBlength;
DWORD BaudRate;
DWORD fBinary : 1;
DWORD fParity : 1;
DWORD fOutxCtsFlow : 1;
DWORD fOutxDsrFlow : 1;
DWORD fDtrControl : 2;
DWORD fDsrSensitivity : 1;
DWORD fTXContinueOnXoff : 1;
DWORD fOutX : 1;
DWORD fInX : 1;
DWORD fErrorChar : 1;
DWORD fNull : 1;
DWORD fRtsControl : 2;
DWORD fAbortOnError : 1;
DWORD fDummy2 : 17;
WORD wReserved;
WORD XonLim;
WORD XoffLim;
BYTE ByteSize;
BYTE Parity;
BYTE StopBits;
BYTE XonChar;
BYTE XoffChar;
BYTE ErrorChar;
BYTE EofChar;
BYTE EvtChar;
WORD wReserved1;
} DCB, *LPDCB;
typedef struct
{
DWORD dwSize;
WORD wVersion;
WORD wReserved;
DCB dcb;
DWORD dwProviderSubType;
DWORD dwProviderOffset;
DWORD dwProviderSize;
WCHAR wcProviderData[1];
} COMMCONFIG, *LPCOMMCONFIG;
typedef struct
{
WORD wPacketLength;
WORD wPacketVersion;
DWORD dwServiceMask;
DWORD dwReserved1;
DWORD dwMaxTxQueue;
DWORD dwMaxRxQueue;
DWORD dwMaxBaud;
DWORD dwProvSubType;
DWORD dwProvCapabilities;
DWORD dwSettableParams;
DWORD dwSettableBaud;
WORD wSettableData;
WORD wSettableStopParity;
DWORD dwCurrentTxQueue;
DWORD dwCurrentRxQueue;
DWORD dwProvSpec1;
DWORD dwProvSpec2;
WCHAR wcProvChar[1];
} COMMPROP, *LPCOMMPROP;
typedef struct
{
DWORD ReadIntervalTimeout;
DWORD ReadTotalTimeoutMultiplier;
DWORD ReadTotalTimeoutConstant;
DWORD WriteTotalTimeoutMultiplier;
DWORD WriteTotalTimeoutConstant;
} COMMTIMEOUTS, *LPCOMMTIMEOUTS;
typedef struct
{
DWORD fCtsHold : 1;
DWORD fDsrHold : 1;
DWORD fRlsdHold : 1;
DWORD fXoffHold : 1;
DWORD fXoffSent : 1;
DWORD fEof : 1;
DWORD fTxim : 1;
DWORD fReserved : 25;
DWORD cbInQue;
DWORD cbOutQue;
} COMSTAT, *LPCOMSTAT;
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API BOOL BuildCommDCBA(LPCSTR lpDef, LPDCB lpDCB);
WINPR_API BOOL BuildCommDCBW(LPCWSTR lpDef, LPDCB lpDCB);
WINPR_API BOOL BuildCommDCBAndTimeoutsA(LPCSTR lpDef, LPDCB lpDCB,
LPCOMMTIMEOUTS lpCommTimeouts);
WINPR_API BOOL BuildCommDCBAndTimeoutsW(LPCWSTR lpDef, LPDCB lpDCB,
LPCOMMTIMEOUTS lpCommTimeouts);
WINPR_API BOOL CommConfigDialogA(LPCSTR lpszName, HWND hWnd, LPCOMMCONFIG lpCC);
WINPR_API BOOL CommConfigDialogW(LPCWSTR lpszName, HWND hWnd, LPCOMMCONFIG lpCC);
WINPR_API BOOL GetCommConfig(HANDLE hCommDev, LPCOMMCONFIG lpCC, LPDWORD lpdwSize);
WINPR_API BOOL SetCommConfig(HANDLE hCommDev, LPCOMMCONFIG lpCC, DWORD dwSize);
WINPR_API BOOL GetCommMask(HANDLE hFile, PDWORD lpEvtMask);
WINPR_API BOOL SetCommMask(HANDLE hFile, DWORD dwEvtMask);
WINPR_API BOOL GetCommModemStatus(HANDLE hFile, PDWORD lpModemStat);
WINPR_API BOOL GetCommProperties(HANDLE hFile, LPCOMMPROP lpCommProp);
WINPR_API BOOL GetCommState(HANDLE hFile, LPDCB lpDCB);
WINPR_API BOOL SetCommState(HANDLE hFile, LPDCB lpDCB);
WINPR_API BOOL GetCommTimeouts(HANDLE hFile, LPCOMMTIMEOUTS lpCommTimeouts);
WINPR_API BOOL SetCommTimeouts(HANDLE hFile, LPCOMMTIMEOUTS lpCommTimeouts);
WINPR_API BOOL GetDefaultCommConfigA(LPCSTR lpszName, LPCOMMCONFIG lpCC, LPDWORD lpdwSize);
WINPR_API BOOL GetDefaultCommConfigW(LPCWSTR lpszName, LPCOMMCONFIG lpCC, LPDWORD lpdwSize);
WINPR_API BOOL SetDefaultCommConfigA(LPCSTR lpszName, LPCOMMCONFIG lpCC, DWORD dwSize);
WINPR_API BOOL SetDefaultCommConfigW(LPCWSTR lpszName, LPCOMMCONFIG lpCC, DWORD dwSize);
WINPR_API BOOL SetCommBreak(HANDLE hFile);
WINPR_API BOOL ClearCommBreak(HANDLE hFile);
WINPR_API BOOL ClearCommError(HANDLE hFile, PDWORD lpErrors, LPCOMSTAT lpStat);
WINPR_API BOOL PurgeComm(HANDLE hFile, DWORD dwFlags);
WINPR_API BOOL SetupComm(HANDLE hFile, DWORD dwInQueue, DWORD dwOutQueue);
WINPR_API BOOL EscapeCommFunction(HANDLE hFile, DWORD dwFunc);
WINPR_API BOOL TransmitCommChar(HANDLE hFile, char cChar);
WINPR_API BOOL WaitCommEvent(HANDLE hFile, PDWORD lpEvtMask, LPOVERLAPPED lpOverlapped);
#ifdef UNICODE
#define BuildCommDCB BuildCommDCBW
#define BuildCommDCBAndTimeouts BuildCommDCBAndTimeoutsW
#define CommConfigDialog CommConfigDialogW
#define GetDefaultCommConfig GetDefaultCommConfigW
#define SetDefaultCommConfig SetDefaultCommConfigW
#else
#define BuildCommDCB BuildCommDCBA
#define BuildCommDCBAndTimeouts BuildCommDCBAndTimeoutsA
#define CommConfigDialog CommConfigDialogA
#define GetDefaultCommConfig GetDefaultCommConfigA
#define SetDefaultCommConfig SetDefaultCommConfigA
#endif
/* Extended API */
/* FIXME: MAXULONG should be defined around winpr/limits.h */
#ifndef MAXULONG
#define MAXULONG (4294967295UL)
#endif
/**
* IOCTLs table according the server's serial driver:
* http://msdn.microsoft.com/en-us/library/windows/hardware/dn265347%28v=vs.85%29.aspx
*/
typedef enum
{
SerialDriverUnknown = 0,
SerialDriverSerialSys,
SerialDriverSerCxSys,
SerialDriverSerCx2Sys /* default fallback, see also CommDeviceIoControl() */
} SERIAL_DRIVER_ID;
/*
* About DefineCommDevice() / QueryDosDevice()
*
* Did something close to QueryDosDevice() and DefineDosDevice() but with
* following constraints:
* - mappings are stored in a static array.
* - QueryCommDevice returns only the mappings that have been defined through
* DefineCommDevice()
*/
WINPR_API BOOL DefineCommDevice(/* DWORD dwFlags,*/ LPCTSTR lpDeviceName, LPCTSTR lpTargetPath);
WINPR_API DWORD QueryCommDevice(LPCTSTR lpDeviceName, LPTSTR lpTargetPath, DWORD ucchMax);
WINPR_API BOOL IsCommDevice(LPCTSTR lpDeviceName);
/**
* A handle can only be created on defined devices with DefineCommDevice(). This
* also ensures that CommCreateFileA() has been registered through
* RegisterHandleCreator().
*/
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CommCreateFileA(LPCSTR lpDeviceName, DWORD dwDesiredAccess, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile);
#define IOCTL_SERIAL_SET_BAUD_RATE 0x001B0004
#define IOCTL_SERIAL_GET_BAUD_RATE 0x001B0050
#define IOCTL_SERIAL_SET_LINE_CONTROL 0x001B000C
#define IOCTL_SERIAL_GET_LINE_CONTROL 0x001B0054
#define IOCTL_SERIAL_SET_TIMEOUTS 0x001B001C
#define IOCTL_SERIAL_GET_TIMEOUTS 0x001B0020
/* GET_CHARS and SET_CHARS are swapped in the RDP docs [MS-RDPESP] */
#define IOCTL_SERIAL_GET_CHARS 0x001B0058
#define IOCTL_SERIAL_SET_CHARS 0x001B005C
#define IOCTL_SERIAL_SET_DTR 0x001B0024
#define IOCTL_SERIAL_CLR_DTR 0x001B0028
#define IOCTL_SERIAL_RESET_DEVICE 0x001B002C
#define IOCTL_SERIAL_SET_RTS 0x001B0030
#define IOCTL_SERIAL_CLR_RTS 0x001B0034
#define IOCTL_SERIAL_SET_XOFF 0x001B0038
#define IOCTL_SERIAL_SET_XON 0x001B003C
#define IOCTL_SERIAL_SET_BREAK_ON 0x001B0010
#define IOCTL_SERIAL_SET_BREAK_OFF 0x001B0014
#define IOCTL_SERIAL_SET_QUEUE_SIZE 0x001B0008
#define IOCTL_SERIAL_GET_WAIT_MASK 0x001B0040
#define IOCTL_SERIAL_SET_WAIT_MASK 0x001B0044
#define IOCTL_SERIAL_WAIT_ON_MASK 0x001B0048
#define IOCTL_SERIAL_IMMEDIATE_CHAR 0x001B0018
#define IOCTL_SERIAL_PURGE 0x001B004C
#define IOCTL_SERIAL_GET_HANDFLOW 0x001B0060
#define IOCTL_SERIAL_SET_HANDFLOW 0x001B0064
#define IOCTL_SERIAL_GET_MODEMSTATUS 0x001B0068
#define IOCTL_SERIAL_GET_DTRRTS 0x001B0078
/* according to [MS-RDPESP] it should be 0x001B0084, but servers send 0x001B006C */
#define IOCTL_SERIAL_GET_COMMSTATUS 0x001B006C
#define IOCTL_SERIAL_GET_PROPERTIES 0x001B0074
/* IOCTL_SERIAL_XOFF_COUNTER 0x001B0070 */
/* IOCTL_SERIAL_LSRMST_INSERT 0x001B007C */
#define IOCTL_SERIAL_CONFIG_SIZE 0x001B0080
/* IOCTL_SERIAL_GET_STATS 0x001B008C */
/* IOCTL_SERIAL_CLEAR_STATS 0x001B0090 */
/* IOCTL_SERIAL_GET_MODEM_CONTROL 0x001B0094 */
/* IOCTL_SERIAL_SET_MODEM_CONTROL 0x001B0098 */
/* IOCTL_SERIAL_SET_FIFO_CONTROL 0x001B009C */
/* IOCTL_PAR_QUERY_INFORMATION 0x00160004 */
/* IOCTL_PAR_SET_INFORMATION 0x00160008 */
/* IOCTL_PAR_QUERY_DEVICE_ID 0x0016000C */
/* IOCTL_PAR_QUERY_DEVICE_ID_SIZE 0x00160010 */
/* IOCTL_IEEE1284_GET_MODE 0x00160014 */
/* IOCTL_IEEE1284_NEGOTIATE 0x00160018 */
/* IOCTL_PAR_SET_WRITE_ADDRESS 0x0016001C */
/* IOCTL_PAR_SET_READ_ADDRESS 0x00160020 */
/* IOCTL_PAR_GET_DEVICE_CAPS 0x00160024 */
/* IOCTL_PAR_GET_DEFAULT_MODES 0x00160028 */
/* IOCTL_PAR_QUERY_RAW_DEVICE_ID 0x00160030 */
/* IOCTL_PAR_IS_PORT_FREE 0x00160054 */
/* http://msdn.microsoft.com/en-us/library/windows/hardware/ff551803(v=vs.85).aspx */
#define IOCTL_USBPRINT_GET_1284_ID 0x220034
typedef struct
{
ULONG number;
const char* name;
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
} _SERIAL_IOCTL_NAME;
/**
* FIXME: got a proper function name and place
*/
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
WINPR_API const char* _comm_serial_ioctl_name(ULONG number);
/**
* FIXME: got a proper function name and place
*/
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
WINPR_API void _comm_setServerSerialDriver(HANDLE hComm, SERIAL_DRIVER_ID);
/**
* FIXME: got a proper function name and place
*
* permissive mode is disabled by default.
*/
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
WINPR_API BOOL _comm_set_permissive(HANDLE hDevice, BOOL permissive);
/**
* FIXME: to be moved in comm_ioctl.h
*/
WINPR_API BOOL CommDeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode, LPVOID lpInBuffer,
DWORD nInBufferSize, LPVOID lpOutBuffer,
DWORD nOutBufferSize, LPDWORD lpBytesReturned,
LPOVERLAPPED lpOverlapped);
/**
* FIXME: to be moved in comm_io.h
*/
WINPR_API BOOL CommReadFile(HANDLE hDevice, LPVOID lpBuffer, DWORD nNumberOfBytesToRead,
LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped);
/**
* FIXME: to be moved in comm_io.h
*/
WINPR_API BOOL CommWriteFile(HANDLE hDevice, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_COMM_H */

View File

@@ -0,0 +1,172 @@
/**
* WinPR: Windows Portable Runtime
* Windows credentials
*
* Copyright 2022 David Fort <contact@hardening-consulting.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_CRED_H_
#define WINPR_CRED_H_
#include <winpr/winpr.h>
#ifdef _WIN32
#include <windows.h>
#include <wincred.h>
#else
#include <winpr/wtypes.h>
#define CERT_HASH_LENGTH 20
#ifdef __cplusplus
extern "C"
{
#endif
typedef enum
{
CertCredential = 1,
UsernameTargetCredential,
BinaryBlobCredential,
UsernameForPackedCredentials,
BinaryBlobForSystem
} CRED_MARSHAL_TYPE,
*PCRED_MARSHAL_TYPE;
typedef struct
{
ULONG cbSize;
UCHAR rgbHashOfCert[CERT_HASH_LENGTH];
} CERT_CREDENTIAL_INFO, *PCERT_CREDENTIAL_INFO;
typedef struct
{
LPSTR Keyword;
DWORD Flags;
DWORD ValueSize;
LPBYTE Value;
} CREDENTIAL_ATTRIBUTEA, *PCREDENTIAL_ATTRIBUTEA;
typedef struct
{
LPWSTR Keyword;
DWORD Flags;
DWORD ValueSize;
LPBYTE Value;
} CREDENTIAL_ATTRIBUTEW, *PCREDENTIAL_ATTRIBUTEW;
typedef struct
{
DWORD Flags;
DWORD Type;
LPSTR TargetName;
LPSTR Comment;
FILETIME LastWritten;
DWORD CredentialBlobSize;
LPBYTE CredentialBlob;
DWORD Persist;
DWORD AttributeCount;
PCREDENTIAL_ATTRIBUTEA Attributes;
LPSTR TargetAlias;
LPSTR UserName;
} CREDENTIALA, *PCREDENTIALA;
typedef struct
{
DWORD Flags;
DWORD Type;
LPWSTR TargetName;
LPWSTR Comment;
FILETIME LastWritten;
DWORD CredentialBlobSize;
LPBYTE CredentialBlob;
DWORD Persist;
DWORD AttributeCount;
PCREDENTIAL_ATTRIBUTEA Attributes;
LPWSTR TargetAlias;
LPWSTR UserName;
} CREDENTIALW, *PCREDENTIALW;
typedef struct
{
LPSTR TargetName;
LPSTR NetbiosServerName;
LPSTR DnsServerName;
LPSTR NetbiosDomainName;
LPSTR DnsDomainName;
LPSTR DnsTreeName;
LPSTR PackageName;
ULONG Flags;
DWORD CredTypeCount;
LPDWORD CredTypes;
} CREDENTIAL_TARGET_INFORMATIONA, *PCREDENTIAL_TARGET_INFORMATIONA;
typedef struct
{
LPWSTR TargetName;
LPWSTR NetbiosServerName;
LPWSTR DnsServerName;
LPWSTR NetbiosDomainName;
LPWSTR DnsDomainName;
LPWSTR DnsTreeName;
LPWSTR PackageName;
ULONG Flags;
DWORD CredTypeCount;
LPDWORD CredTypes;
} CREDENTIAL_TARGET_INFORMATIONW, *PCREDENTIAL_TARGET_INFORMATIONW;
typedef enum
{
CredUnprotected,
CredUserProtection,
CredTrustedProtection,
CredForSystemProtection
} CRED_PROTECTION_TYPE,
*PCRED_PROTECTION_TYPE;
WINPR_API BOOL CredMarshalCredentialA(CRED_MARSHAL_TYPE CredType, PVOID Credential,
LPSTR* MarshaledCredential);
WINPR_API BOOL CredMarshalCredentialW(CRED_MARSHAL_TYPE CredType, PVOID Credential,
LPWSTR* MarshaledCredential);
#ifdef UNICODE
#define CredMarshalCredential CredMarshalCredentialW
#else
#define CredMarshalCredential CredMarshalCredentialA
#endif
WINPR_API BOOL CredUnmarshalCredentialW(LPCWSTR cred, PCRED_MARSHAL_TYPE CredType,
PVOID* Credential);
WINPR_API BOOL CredUnmarshalCredentialA(LPCSTR cred, PCRED_MARSHAL_TYPE CredType,
PVOID* Credential);
#ifdef UNICODE
#define CredUnmarshalCredential CredUnmarshalCredentialW
#else
#define CredUnmarshalCredential CredUnmarshalCredentialA
#endif
WINPR_API BOOL CredIsMarshaledCredentialA(LPCSTR MarshaledCredential);
WINPR_API BOOL CredIsMarshaledCredentialW(LPCWSTR MarshaledCredential);
WINPR_API VOID CredFree(PVOID Buffer);
#ifdef __cplusplus
}
#endif
#endif /* _WIN32 */
#endif /* WINPR_CRED_H_ */

View File

@@ -0,0 +1,250 @@
/**
* WinPR: Windows Portable Runtime
* C Run-Time Library Routines
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_CRT_H
#define WINPR_CRT_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/cast.h>
#include <winpr/platform.h>
#include <winpr/winpr.h>
#include <winpr/spec.h>
#include <winpr/string.h>
WINPR_PRAGMA_DIAG_PUSH
WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER
// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#ifndef _WIN32
#include <unistd.h>
#ifndef _write
#define _write write
#endif
#ifndef _strtoui64
#define _strtoui64 strtoull
#endif /* _strtoui64 */
#ifndef _strtoi64
#define _strtoi64 strtoll
#endif /* _strtoi64 */
#ifndef _rotl
static inline UINT32 _rotl(UINT32 value, int shift)
{
return (value << shift) | (value >> (32 - shift));
}
#endif /* _rotl */
#ifndef _rotl64
static inline UINT64 _rotl64(UINT64 value, int shift)
{
return (value << shift) | (value >> (64 - shift));
}
#endif /* _rotl64 */
#ifndef _rotr
static inline UINT32 _rotr(UINT32 value, int shift)
{
return (value >> shift) | (value << (32 - shift));
}
#endif /* _rotr */
#ifndef _rotr64
static inline UINT64 _rotr64(UINT64 value, int shift)
{
return (value >> shift) | (value << (64 - shift));
}
#endif /* _rotr64 */
#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2))
#define _byteswap_ulong(_val) __builtin_bswap32(_val)
#define _byteswap_uint64(_val) __builtin_bswap64(_val)
#else
static inline UINT32 _byteswap_ulong(UINT32 _val)
{
return (((_val) >> 24) | (((_val)&0x00FF0000) >> 8) | (((_val)&0x0000FF00) << 8) |
((_val) << 24));
}
static inline UINT64 _byteswap_uint64(UINT64 _val)
{
return (((_val) << 56) | (((_val) << 40) & 0xFF000000000000) |
(((_val) << 24) & 0xFF0000000000) | (((_val) << 8) & 0xFF00000000) |
(((_val) >> 8) & 0xFF000000) | (((_val) >> 24) & 0xFF0000) | (((_val) >> 40) & 0xFF00) |
((_val) >> 56));
}
#endif /* (__GNUC__ > 4) || ... */
#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8))
#define _byteswap_ushort(_val) __builtin_bswap16(_val)
#else
static inline UINT16 _byteswap_ushort(UINT16 _val)
{
return WINPR_CXX_COMPAT_CAST(UINT16, ((_val) >> 8U) | ((_val) << 8U));
}
#endif /* (__GNUC__ > 4) || ... */
#define CopyMemory(Destination, Source, Length) memcpy((Destination), (Source), (Length))
#define MoveMemory(Destination, Source, Length) memmove((Destination), (Source), (Length))
#define FillMemory(Destination, Length, Fill) memset((Destination), (Fill), (Length))
#define ZeroMemory(Destination, Length) memset((Destination), 0, (Length))
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API PVOID SecureZeroMemory(PVOID ptr, size_t cnt);
#ifdef __cplusplus
}
#endif
#endif /* _WIN32 */
/* Data Alignment */
WINPR_PRAGMA_DIAG_PUSH
WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO
#ifndef _ERRNO_T_DEFINED
#define _ERRNO_T_DEFINED
typedef int errno_t;
#endif /* _ERRNO_T_DEFINED */
WINPR_PRAGMA_DIAG_POP
#ifndef _WIN32
#ifdef __cplusplus
extern "C"
{
#endif
/* Data Conversion */
WINPR_API errno_t _itoa_s(int value, char* buffer, size_t sizeInCharacters, int radix);
/* Buffer Manipulation */
WINPR_API errno_t memmove_s(void* dest, size_t numberOfElements, const void* src, size_t count);
WINPR_API errno_t wmemmove_s(WCHAR* dest, size_t numberOfElements, const WCHAR* src,
size_t count);
#ifdef __cplusplus
}
#endif
#endif /* _WIN32 */
#if !defined(_WIN32) || (defined(__MINGW32__) && !defined(_UCRT))
/* note: we use our own implementation of _aligned_XXX function when:
* - it's not win32
* - it's mingw with native libs (not ucrt64) because we didn't managed to have it working
* and not have C runtime deadly mixes
*/
#if defined(WINPR_MSVCR_ALIGNMENT_EMULATE)
#define _aligned_malloc winpr_aligned_malloc
#define _aligned_realloc winpr_aligned_realloc
#define _aligned_recalloc winpr_aligned_recalloc
#define _aligned_offset_malloc winpr_aligned_offset_malloc
#define _aligned_offset_realloc winpr_aligned_offset_realloc
#define _aligned_offset_recalloc winpr_aligned_offset_recalloc
#define _aligned_msize winpr_aligned_msize
#define _aligned_free winpr_aligned_free
#endif
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API void winpr_aligned_free(void* memblock);
WINPR_ATTR_MALLOC(winpr_aligned_free, 1)
WINPR_ATTR_NODISCARD
WINPR_API void* winpr_aligned_malloc(size_t size, size_t alignment);
WINPR_ATTR_MALLOC(winpr_aligned_free, 1)
WINPR_ATTR_NODISCARD
WINPR_API void* winpr_aligned_calloc(size_t count, size_t size, size_t alignment);
WINPR_ATTR_MALLOC(winpr_aligned_free, 1)
WINPR_ATTR_NODISCARD
WINPR_API void* winpr_aligned_realloc(void* memblock, size_t size, size_t alignment);
WINPR_ATTR_MALLOC(winpr_aligned_free, 1)
WINPR_ATTR_NODISCARD
WINPR_API void* winpr_aligned_recalloc(void* memblock, size_t num, size_t size,
size_t alignment);
WINPR_ATTR_MALLOC(winpr_aligned_free, 1)
WINPR_ATTR_NODISCARD
WINPR_API void* winpr_aligned_offset_malloc(size_t size, size_t alignment, size_t offset);
WINPR_ATTR_MALLOC(winpr_aligned_free, 1)
WINPR_ATTR_NODISCARD
WINPR_API void* winpr_aligned_offset_realloc(void* memblock, size_t size, size_t alignment,
size_t offset);
WINPR_ATTR_MALLOC(winpr_aligned_free, 1)
WINPR_ATTR_NODISCARD
WINPR_API void* winpr_aligned_offset_recalloc(void* memblock, size_t num, size_t size,
size_t alignment, size_t offset);
WINPR_API size_t winpr_aligned_msize(void* memblock, size_t alignment, size_t offset);
#ifdef __cplusplus
}
#endif
#else
#define winpr_aligned_malloc _aligned_malloc
#define winpr_aligned_realloc _aligned_realloc
#define winpr_aligned_recalloc _aligned_recalloc
#define winpr_aligned_offset_malloc _aligned_offset_malloc
#define winpr_aligned_offset_realloc _aligned_offset_realloc
#define winpr_aligned_offset_recalloc _aligned_offset_recalloc
#define winpr_aligned_msize _aligned_msize
#define winpr_aligned_free _aligned_free
#endif /* !defined(_WIN32) || (defined(__MINGW32__) ... */
#if defined(_WIN32) && (!defined(__MINGW32__) || defined(_UCRT))
#define winpr_aligned_calloc(count, size, alignment) \
_aligned_recalloc(nullptr, count, size, alignment)
#endif /* defined(_WIN32) && (!defined(__MINGW32__) || defined(_UCRT)) */
// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
WINPR_PRAGMA_DIAG_POP
#endif /* WINPR_CRT_H */

View File

@@ -0,0 +1,26 @@
/**
* WinPR: Windows Portable Runtime
* Cryptography API (CryptoAPI)
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_CRYPTO_H
#define WINPR_CRYPTO_H
#include <winpr/custom-crypto.h>
#include <winpr/wincrypt.h>
#endif /* WINPR_CRYPTO_H */

View File

@@ -0,0 +1,326 @@
/**
* WinPR: Windows Portable Runtime
* Cryptography API (CryptoAPI)
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_CUSTOM_CRYPTO_H
#define WINPR_CUSTOM_CRYPTO_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/error.h>
/**
* Custom Crypto API Abstraction Layer
*/
#define WINPR_MD4_DIGEST_LENGTH 16
#define WINPR_MD5_DIGEST_LENGTH 16
#define WINPR_SHA1_DIGEST_LENGTH 20
#define WINPR_SHA224_DIGEST_LENGTH 28
#define WINPR_SHA256_DIGEST_LENGTH 32
#define WINPR_SHA384_DIGEST_LENGTH 48
#define WINPR_SHA512_DIGEST_LENGTH 64
#define WINPR_RIPEMD160_DIGEST_LENGTH 20
#define WINPR_SHA3_224_DIGEST_LENGTH 28
#define WINPR_SHA3_256_DIGEST_LENGTH 32
#define WINPR_SHA3_384_DIGEST_LENGTH 48
#define WINPR_SHA3_512_DIGEST_LENGTH 64
#define WINPR_SHAKE128_DIGEST_LENGTH 16
#define WINPR_SHAKE256_DIGEST_LENGTH 32
/**
* HMAC
*/
typedef enum
{
WINPR_MD_NONE = 0,
WINPR_MD_MD2 = 1,
WINPR_MD_MD4 = 2,
WINPR_MD_MD5 = 3,
WINPR_MD_SHA1 = 4,
WINPR_MD_SHA224 = 5,
WINPR_MD_SHA256 = 6,
WINPR_MD_SHA384 = 7,
WINPR_MD_SHA512 = 8,
WINPR_MD_RIPEMD160 = 9,
WINPR_MD_SHA3_224 = 10,
WINPR_MD_SHA3_256 = 11,
WINPR_MD_SHA3_384 = 12,
WINPR_MD_SHA3_512 = 13,
WINPR_MD_SHAKE128 = 14,
WINPR_MD_SHAKE256 = 15
} WINPR_MD_TYPE;
typedef struct winpr_hmac_ctx_private_st WINPR_HMAC_CTX;
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API WINPR_MD_TYPE winpr_md_type_from_string(const char* name);
WINPR_API const char* winpr_md_type_to_string(WINPR_MD_TYPE md);
WINPR_API void winpr_HMAC_Free(WINPR_HMAC_CTX* ctx);
WINPR_ATTR_MALLOC(winpr_HMAC_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API WINPR_HMAC_CTX* winpr_HMAC_New(void);
WINPR_API BOOL winpr_HMAC_Init(WINPR_HMAC_CTX* ctx, WINPR_MD_TYPE md, const void* key,
size_t keylen);
WINPR_API BOOL winpr_HMAC_Update(WINPR_HMAC_CTX* ctx, const void* input, size_t ilen);
WINPR_API BOOL winpr_HMAC_Final(WINPR_HMAC_CTX* ctx, void* output, size_t olen);
WINPR_API BOOL winpr_HMAC(WINPR_MD_TYPE md, const void* key, size_t keylen, const void* input,
size_t ilen, void* output, size_t olen);
#ifdef __cplusplus
}
#endif
/**
* Generic Digest API
*/
typedef struct winpr_digest_ctx_private_st WINPR_DIGEST_CTX;
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API void winpr_Digest_Free(WINPR_DIGEST_CTX* ctx);
WINPR_ATTR_MALLOC(winpr_Digest_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API WINPR_DIGEST_CTX* winpr_Digest_New(void);
WINPR_API BOOL winpr_Digest_Init_Allow_FIPS(WINPR_DIGEST_CTX* ctx, WINPR_MD_TYPE md);
WINPR_API BOOL winpr_Digest_Init(WINPR_DIGEST_CTX* ctx, WINPR_MD_TYPE md);
WINPR_API BOOL winpr_Digest_Update(WINPR_DIGEST_CTX* ctx, const void* input, size_t ilen);
WINPR_API BOOL winpr_Digest_Final(WINPR_DIGEST_CTX* ctx, void* output, size_t olen);
WINPR_API BOOL winpr_Digest_Allow_FIPS(WINPR_MD_TYPE md, const void* input, size_t ilen,
void* output, size_t olen);
WINPR_API BOOL winpr_Digest(WINPR_MD_TYPE md, const void* input, size_t ilen, void* output,
size_t olen);
WINPR_API BOOL winpr_DigestSign_Init(WINPR_DIGEST_CTX* ctx, WINPR_MD_TYPE md, void* key);
WINPR_API BOOL winpr_DigestSign_Update(WINPR_DIGEST_CTX* ctx, const void* input, size_t ilen);
WINPR_API BOOL winpr_DigestSign_Final(WINPR_DIGEST_CTX* ctx, void* output, size_t* piolen);
#ifdef __cplusplus
}
#endif
/**
* Random Number Generation
*/
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API int winpr_RAND(void* output, size_t len);
WINPR_API int winpr_RAND_pseudo(void* output, size_t len);
#ifdef __cplusplus
}
#endif
/**
* RC4
*/
typedef struct winpr_rc4_ctx_private_st WINPR_RC4_CTX;
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API void winpr_RC4_Free(WINPR_RC4_CTX* ctx);
WINPR_ATTR_MALLOC(winpr_RC4_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API WINPR_RC4_CTX* winpr_RC4_New_Allow_FIPS(const void* key, size_t keylen);
WINPR_ATTR_MALLOC(winpr_RC4_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API WINPR_RC4_CTX* winpr_RC4_New(const void* key, size_t keylen);
WINPR_API BOOL winpr_RC4_Update(WINPR_RC4_CTX* ctx, size_t length, const void* input,
void* output);
#ifdef __cplusplus
}
#endif
/**
* Generic Cipher API
*/
#define WINPR_AES_BLOCK_SIZE 16
/* cipher operation types */
#define WINPR_CIPHER_MAX_IV_LENGTH 16u
#define WINPR_CIPHER_MAX_KEY_LENGTH 64u
typedef enum
{
WINPR_ENCRYPT = 0,
WINPR_DECRYPT = 1
} WINPR_CRYPTO_OPERATION;
/* cipher types */
typedef enum
{
WINPR_CIPHER_NONE = 0,
WINPR_CIPHER_NULL = 1,
WINPR_CIPHER_AES_128_ECB = 2,
WINPR_CIPHER_AES_192_ECB = 3,
WINPR_CIPHER_AES_256_ECB = 4,
WINPR_CIPHER_AES_128_CBC = 5,
WINPR_CIPHER_AES_192_CBC = 6,
WINPR_CIPHER_AES_256_CBC = 7,
WINPR_CIPHER_AES_128_CFB128 = 8,
WINPR_CIPHER_AES_192_CFB128 = 9,
WINPR_CIPHER_AES_256_CFB128 = 10,
WINPR_CIPHER_AES_128_CTR = 11,
WINPR_CIPHER_AES_192_CTR = 12,
WINPR_CIPHER_AES_256_CTR = 13,
WINPR_CIPHER_AES_128_GCM = 14,
WINPR_CIPHER_AES_192_GCM = 15,
WINPR_CIPHER_AES_256_GCM = 16,
WINPR_CIPHER_CAMELLIA_128_ECB = 17,
WINPR_CIPHER_CAMELLIA_192_ECB = 18,
WINPR_CIPHER_CAMELLIA_256_ECB = 19,
WINPR_CIPHER_CAMELLIA_128_CBC = 20,
WINPR_CIPHER_CAMELLIA_192_CBC = 21,
WINPR_CIPHER_CAMELLIA_256_CBC = 22,
WINPR_CIPHER_CAMELLIA_128_CFB128 = 23,
WINPR_CIPHER_CAMELLIA_192_CFB128 = 24,
WINPR_CIPHER_CAMELLIA_256_CFB128 = 25,
WINPR_CIPHER_CAMELLIA_128_CTR = 26,
WINPR_CIPHER_CAMELLIA_192_CTR = 27,
WINPR_CIPHER_CAMELLIA_256_CTR = 28,
WINPR_CIPHER_CAMELLIA_128_GCM = 29,
WINPR_CIPHER_CAMELLIA_192_GCM = 30,
WINPR_CIPHER_CAMELLIA_256_GCM = 31,
WINPR_CIPHER_DES_ECB = 32,
WINPR_CIPHER_DES_CBC = 33,
WINPR_CIPHER_DES_EDE_ECB = 34,
WINPR_CIPHER_DES_EDE_CBC = 35,
WINPR_CIPHER_DES_EDE3_ECB = 36,
WINPR_CIPHER_DES_EDE3_CBC = 37,
WINPR_CIPHER_BLOWFISH_ECB = 38,
WINPR_CIPHER_BLOWFISH_CBC = 39,
WINPR_CIPHER_BLOWFISH_CFB64 = 40,
WINPR_CIPHER_BLOWFISH_CTR = 41,
WINPR_CIPHER_ARC4_128 = 42,
WINPR_CIPHER_AES_128_CCM = 43,
WINPR_CIPHER_AES_192_CCM = 44,
WINPR_CIPHER_AES_256_CCM = 45,
WINPR_CIPHER_CAMELLIA_128_CCM = 46,
WINPR_CIPHER_CAMELLIA_192_CCM = 47,
WINPR_CIPHER_CAMELLIA_256_CCM = 48,
} WINPR_CIPHER_TYPE;
typedef struct winpr_cipher_ctx_private_st WINPR_CIPHER_CTX;
#ifdef __cplusplus
extern "C"
{
#endif
/** @brief convert a cipher string to an enum value
*
* @param name the name of the cipher
* @return the \b WINPR_CIPHER_* value matching or \b WINPR_CIPHER_NONE if not found.
*
* @since version 3.10.0
*/
WINPR_API WINPR_CIPHER_TYPE winpr_cipher_type_from_string(const char* name);
/** @brief convert a cipher enum value to string
*
* @param md the cipher enum value
* @return the string representation of the value
*
* @since version 3.10.0
*/
WINPR_API const char* winpr_cipher_type_to_string(WINPR_CIPHER_TYPE md);
WINPR_API void winpr_Cipher_Free(WINPR_CIPHER_CTX* ctx);
#if !defined(WITHOUT_FREERDP_3x_DEPRECATED)
WINPR_DEPRECATED_VAR("[since 3.10.0] use winpr_Cipher_NewEx",
WINPR_ATTR_MALLOC(winpr_Cipher_Free, 1)
WINPR_ATTR_NODISCARD WINPR_API WINPR_CIPHER_CTX* winpr_Cipher_New(
WINPR_CIPHER_TYPE cipher, WINPR_CRYPTO_OPERATION op,
const void* key, const void* iv));
#endif
/** @brief Create a new \b WINPR_CIPHER_CTX
*
* creates a new stream cipher. Only the ciphers supported by your SSL library are available,
* fallback to WITH_INTERNAL_RC4 is not possible.
*
* @param cipher The cipher to create the context for
* @param op Operation \b WINPR_ENCRYPT or \b WINPR_DECRYPT
* @param key A pointer to the key material (size must match expectations for the cipher used)
* @param keylen The length in bytes of key material
* @param iv A pointer to the IV material (size must match expectations for the cipher used)
* @param ivlen The length in bytes of the IV
*
* @return A newly allocated context or \b nullptr
*
* @since version 3.10.0
*/
WINPR_ATTR_MALLOC(winpr_Cipher_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API WINPR_CIPHER_CTX* winpr_Cipher_NewEx(WINPR_CIPHER_TYPE cipher,
WINPR_CRYPTO_OPERATION op, const void* key,
size_t keylen, const void* iv, size_t ivlen);
WINPR_API BOOL winpr_Cipher_SetPadding(WINPR_CIPHER_CTX* ctx, BOOL enabled);
WINPR_API BOOL winpr_Cipher_Update(WINPR_CIPHER_CTX* ctx, const void* input, size_t ilen,
void* output, size_t* olen);
WINPR_API BOOL winpr_Cipher_Final(WINPR_CIPHER_CTX* ctx, void* output, size_t* olen);
#ifdef __cplusplus
}
#endif
/**
* Key Generation
*/
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API int winpr_Cipher_BytesToKey(int cipher, WINPR_MD_TYPE md, const void* salt,
const void* data, size_t datal, size_t count, void* key,
void* iv);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_CUSTOM_CRYPTO_H */

View File

@@ -0,0 +1,53 @@
/**
* WinPR: Windows Portable Runtime
* WinPR Debugging helpers
*
* Copyright 2014 Armin Novak <armin.novak@thincast.com>
* Copyright 2014 Thincast Technologies GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_DEBUG_H
#define WINPR_DEBUG_H
#ifdef __cplusplus
extern "C"
{
#endif
#include <winpr/wtypes.h>
#include <winpr/winpr.h>
#include <winpr/wlog.h>
WINPR_API void winpr_log_backtrace(const char* tag, DWORD level, DWORD size);
WINPR_API void winpr_log_backtrace_ex(wLog* log, DWORD level, DWORD size);
WINPR_API void winpr_backtrace_free(void* buffer);
WINPR_ATTR_MALLOC(winpr_backtrace_free, 1)
WINPR_ATTR_NODISCARD
WINPR_API void* winpr_backtrace(DWORD size);
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char** winpr_backtrace_symbols(void* buffer, size_t* used);
WINPR_API void winpr_backtrace_symbols_fd(void* buffer, int fd);
WINPR_API char* winpr_strerror(INT32 dw, char* dmsg, size_t size);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_WLOG_H */

View File

@@ -0,0 +1,127 @@
/**
* WinPR: Windows Portable Runtime
* Active Directory Domain Services Parsing Functions
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_DSPARSE_H
#define WINPR_DSPARSE_H
#if defined(_WIN32) && !defined(_UWP)
#include <winpr/windows.h>
#include <winpr/rpc.h>
#include <ntdsapi.h>
#else
#include <winpr/crt.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/error.h>
typedef enum
{
DS_NAME_NO_FLAGS = 0x0,
DS_NAME_FLAG_SYNTACTICAL_ONLY = 0x1,
DS_NAME_FLAG_EVAL_AT_DC = 0x2,
DS_NAME_FLAG_GCVERIFY = 0x4,
DS_NAME_FLAG_TRUST_REFERRAL = 0x8
} DS_NAME_FLAGS;
typedef enum
{
DS_UNKNOWN_NAME = 0,
DS_FQDN_1779_NAME = 1,
DS_NT4_ACCOUNT_NAME = 2,
DS_DISPLAY_NAME = 3,
DS_UNIQUE_ID_NAME = 6,
DS_CANONICAL_NAME = 7,
DS_USER_PRINCIPAL_NAME = 8,
DS_CANONICAL_NAME_EX = 9,
DS_SERVICE_PRINCIPAL_NAME = 10,
DS_SID_OR_SID_HISTORY_NAME = 11,
DS_DNS_DOMAIN_NAME = 12
} DS_NAME_FORMAT;
typedef enum
{
DS_NAME_NO_ERROR = 0,
DS_NAME_ERROR_RESOLVING = 1,
DS_NAME_ERROR_NOT_FOUND = 2,
DS_NAME_ERROR_NOT_UNIQUE = 3,
DS_NAME_ERROR_NO_MAPPING = 4,
DS_NAME_ERROR_DOMAIN_ONLY = 5,
DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING = 6,
DS_NAME_ERROR_TRUST_REFERRAL = 7
} DS_NAME_ERROR;
typedef enum
{
DS_SPN_DNS_HOST = 0,
DS_SPN_DN_HOST = 1,
DS_SPN_NB_HOST = 2,
DS_SPN_DOMAIN = 3,
DS_SPN_NB_DOMAIN = 4,
DS_SPN_SERVICE = 5
} DS_SPN_NAME_TYPE;
typedef struct
{
DWORD status;
LPTSTR pDomain;
LPTSTR pName;
} DS_NAME_RESULT_ITEM, *PDS_NAME_RESULT_ITEM;
typedef struct
{
DWORD cItems;
PDS_NAME_RESULT_ITEM rItems;
} DS_NAME_RESULT, *PDS_NAME_RESULT;
#ifdef __cplusplus
extern "C"
{
#endif
#ifdef UNICODE
#define DsMakeSpn DsMakeSpnW
#else
#define DsMakeSpn DsMakeSpnA
#endif
WINPR_API DWORD DsMakeSpnW(LPCWSTR ServiceClass, LPCWSTR ServiceName, LPCWSTR InstanceName,
USHORT InstancePort, LPCWSTR Referrer, DWORD* pcSpnLength,
LPWSTR pszSpn);
WINPR_API DWORD DsMakeSpnA(LPCSTR ServiceClass, LPCSTR ServiceName, LPCSTR InstanceName,
USHORT InstancePort, LPCSTR Referrer, DWORD* pcSpnLength,
LPSTR pszSpn);
#ifdef __cplusplus
}
#endif
#ifdef UNICODE
#define DsMakeSpn DsMakeSpnW
#else
#define DsMakeSpn DsMakeSpnA
#endif
#endif
#endif /* WINPR_DSPARSE_H */

View File

@@ -0,0 +1,428 @@
/*
* WinPR: Windows Portable Runtime
* Endianness Macros
*
* Copyright 2013 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2024 Armin Novak <anovak@thincast.com>
* Copyright 2024 Thincast Technologies GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_ENDIAN_H
#define WINPR_ENDIAN_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/platform.h>
#include <winpr/assert.h>
#include <winpr/cast.h>
#define WINPR_ENDIAN_CAST(t, val) WINPR_CXX_COMPAT_CAST(t, val)
#ifdef __cplusplus
extern "C"
{
#endif
static inline UINT8 winpr_Data_Get_UINT8(const void* d)
{
WINPR_ASSERT(d);
const UINT8* ptr = WINPR_ENDIAN_CAST(const UINT8*, d);
return *ptr;
}
static inline INT8 winpr_Data_Get_INT8(const void* d)
{
WINPR_ASSERT(d);
const INT8* ptr = WINPR_ENDIAN_CAST(const INT8*, d);
return *ptr;
}
static inline UINT16 winpr_Data_Get_UINT16_NE(const void* d)
{
const UINT16* ptr = WINPR_ENDIAN_CAST(const UINT16*, d);
return *ptr;
}
static inline UINT16 winpr_Data_Get_UINT16(const void* d)
{
WINPR_ASSERT(d);
const UINT8* ptr = WINPR_ENDIAN_CAST(const UINT8*, d);
const size_t typesize = sizeof(UINT16);
UINT16 v = 0;
for (size_t x = 0; x < typesize; x++)
{
v <<= 8;
v |= ptr[typesize - x - 1];
}
return v;
}
static inline UINT16 winpr_Data_Get_UINT16_BE(const void* d)
{
WINPR_ASSERT(d);
const UINT8* ptr = WINPR_ENDIAN_CAST(const UINT8*, d);
const size_t typesize = sizeof(UINT16);
UINT16 v = 0;
for (size_t x = 0; x < typesize; x++)
{
v <<= 8;
v |= ptr[x];
}
return v;
}
static inline INT16 winpr_Data_Get_INT16_NE(const void* d)
{
WINPR_ASSERT(d);
const INT16* ptr = WINPR_ENDIAN_CAST(const INT16*, d);
return *ptr;
}
static inline INT16 winpr_Data_Get_INT16(const void* d)
{
const UINT16 u16 = winpr_Data_Get_UINT16(d);
return WINPR_ENDIAN_CAST(INT16, u16);
}
static inline INT16 winpr_Data_Get_INT16_BE(const void* d)
{
const UINT16 u16 = winpr_Data_Get_UINT16_BE(d);
return WINPR_ENDIAN_CAST(INT16, u16);
}
static inline UINT32 winpr_Data_Get_UINT32_NE(const void* d)
{
WINPR_ASSERT(d);
const UINT32* ptr = WINPR_ENDIAN_CAST(const UINT32*, d);
return *ptr;
}
static inline UINT32 winpr_Data_Get_UINT32(const void* d)
{
WINPR_ASSERT(d);
const UINT8* ptr = WINPR_ENDIAN_CAST(const UINT8*, d);
const size_t typesize = sizeof(UINT32);
UINT32 v = 0;
for (size_t x = 0; x < typesize; x++)
{
v <<= 8;
v |= ptr[typesize - x - 1];
}
return v;
}
static inline UINT32 winpr_Data_Get_UINT32_BE(const void* d)
{
WINPR_ASSERT(d);
const UINT8* ptr = WINPR_ENDIAN_CAST(const UINT8*, d);
const size_t typesize = sizeof(UINT32);
UINT32 v = 0;
for (size_t x = 0; x < typesize; x++)
{
v <<= 8;
v |= ptr[x];
}
return v;
}
static inline INT32 winpr_Data_Get_INT32_NE(const void* d)
{
WINPR_ASSERT(d);
const INT32* ptr = WINPR_ENDIAN_CAST(const INT32*, d);
return *ptr;
}
static inline INT32 winpr_Data_Get_INT32(const void* d)
{
const UINT32 u32 = winpr_Data_Get_UINT32(d);
return WINPR_ENDIAN_CAST(INT32, u32);
}
static inline INT32 winpr_Data_Get_INT32_BE(const void* d)
{
const UINT32 u32 = winpr_Data_Get_UINT32_BE(d);
return WINPR_ENDIAN_CAST(INT32, u32);
}
static inline UINT64 winpr_Data_Get_UINT64_NE(const void* d)
{
WINPR_ASSERT(d);
const UINT64* ptr = WINPR_ENDIAN_CAST(const UINT64*, d);
return *ptr;
}
static inline UINT64 winpr_Data_Get_UINT64(const void* d)
{
WINPR_ASSERT(d);
const UINT8* ptr = WINPR_ENDIAN_CAST(const UINT8*, d);
const size_t typesize = sizeof(UINT64);
UINT64 v = 0;
for (size_t x = 0; x < typesize; x++)
{
v <<= 8;
v |= ptr[typesize - x - 1];
}
return v;
}
static inline UINT64 winpr_Data_Get_UINT64_BE(const void* d)
{
WINPR_ASSERT(d);
const UINT8* ptr = WINPR_ENDIAN_CAST(const UINT8*, d);
const size_t typesize = sizeof(UINT64);
UINT64 v = 0;
for (size_t x = 0; x < typesize; x++)
{
v <<= 8;
v |= ptr[x];
}
return v;
}
static inline INT64 winpr_Data_Get_INT64_NE(const void* d)
{
WINPR_ASSERT(d);
const INT64* b = WINPR_ENDIAN_CAST(const INT64*, d);
return *b;
}
static inline INT64 winpr_Data_Get_INT64(const void* d)
{
const UINT64 u64 = winpr_Data_Get_UINT64(d);
return WINPR_ENDIAN_CAST(INT64, u64);
}
static inline INT64 winpr_Data_Get_INT64_BE(const void* d)
{
const UINT64 u64 = winpr_Data_Get_UINT64_BE(d);
return WINPR_ENDIAN_CAST(INT64, u64);
}
static inline void winpr_Data_Write_UINT8_NE(void* d, UINT8 v)
{
WINPR_ASSERT(d);
BYTE* b = WINPR_ENDIAN_CAST(BYTE*, d);
*b = v;
}
static inline void winpr_Data_Write_UINT8(void* d, UINT8 v)
{
WINPR_ASSERT(d);
BYTE* b = WINPR_ENDIAN_CAST(BYTE*, d);
*b = v;
}
static inline void winpr_Data_Write_UINT16_NE(void* d, UINT16 v)
{
WINPR_ASSERT(d);
UINT16* b = WINPR_ENDIAN_CAST(UINT16*, d);
*b = v;
}
static inline void winpr_Data_Write_UINT16(void* d, UINT16 v)
{
WINPR_ASSERT(d);
BYTE* b = WINPR_ENDIAN_CAST(BYTE*, d);
b[0] = v & 0xFF;
b[1] = (v >> 8) & 0xFF;
}
static inline void winpr_Data_Write_UINT16_BE(void* d, UINT16 v)
{
WINPR_ASSERT(d);
BYTE* b = WINPR_ENDIAN_CAST(BYTE*, d);
b[1] = v & 0xFF;
b[0] = (v >> 8) & 0xFF;
}
static inline void winpr_Data_Write_UINT32_NE(void* d, UINT32 v)
{
WINPR_ASSERT(d);
UINT32* b = WINPR_ENDIAN_CAST(UINT32*, d);
*b = v;
}
static inline void winpr_Data_Write_UINT32(void* d, UINT32 v)
{
WINPR_ASSERT(d);
BYTE* b = WINPR_ENDIAN_CAST(BYTE*, d);
winpr_Data_Write_UINT16(b, v & 0xFFFF);
winpr_Data_Write_UINT16(b + 2, (v >> 16) & 0xFFFF);
}
static inline void winpr_Data_Write_UINT32_BE(void* d, UINT32 v)
{
WINPR_ASSERT(d);
BYTE* b = WINPR_ENDIAN_CAST(BYTE*, d);
winpr_Data_Write_UINT16_BE(b, (v >> 16) & 0xFFFF);
winpr_Data_Write_UINT16_BE(b + 2, v & 0xFFFF);
}
static inline void winpr_Data_Write_UINT64_NE(void* d, UINT64 v)
{
WINPR_ASSERT(d);
UINT64* b = WINPR_ENDIAN_CAST(UINT64*, d);
*b = v;
}
static inline void winpr_Data_Write_UINT64(void* d, UINT64 v)
{
WINPR_ASSERT(d);
BYTE* b = WINPR_ENDIAN_CAST(BYTE*, d);
winpr_Data_Write_UINT32(b, v & 0xFFFFFFFF);
winpr_Data_Write_UINT32(b + 4, (v >> 32) & 0xFFFFFFFF);
}
static inline void winpr_Data_Write_UINT64_BE(void* d, UINT64 v)
{
WINPR_ASSERT(d);
BYTE* b = WINPR_ENDIAN_CAST(BYTE*, d);
winpr_Data_Write_UINT32_BE(b, (v >> 32) & 0xFFFFFFFF);
winpr_Data_Write_UINT32_BE(b + 4, v & 0xFFFFFFFF);
}
static inline void winpr_Data_Write_INT8_NE(void* d, INT8 v)
{
WINPR_ASSERT(d);
INT8* b = WINPR_ENDIAN_CAST(INT8*, d);
*b = v;
}
static inline void winpr_Data_Write_INT8(void* d, INT8 v)
{
WINPR_ASSERT(d);
INT8* b = WINPR_ENDIAN_CAST(INT8*, d);
*b = v;
}
static inline void winpr_Data_Write_INT16_NE(void* d, INT16 v)
{
WINPR_ASSERT(d);
INT16* b = WINPR_ENDIAN_CAST(INT16*, d);
*b = v;
}
static inline void winpr_Data_Write_INT16(void* d, INT16 v)
{
WINPR_ASSERT(d);
BYTE* b = WINPR_ENDIAN_CAST(BYTE*, d);
b[0] = v & 0xFF;
b[1] = (v >> 8) & 0xFF;
}
static inline void winpr_Data_Write_INT16_BE(void* d, INT16 v)
{
WINPR_ASSERT(d);
BYTE* b = WINPR_ENDIAN_CAST(BYTE*, d);
b[1] = v & 0xFF;
b[0] = (v >> 8) & 0xFF;
}
static inline void winpr_Data_Write_INT32_NE(void* d, INT32 v)
{
WINPR_ASSERT(d);
INT32* pu = WINPR_ENDIAN_CAST(INT32*, d);
*pu = v;
}
static inline void winpr_Data_Write_INT32(void* d, INT32 v)
{
WINPR_ASSERT(d);
BYTE* b = WINPR_ENDIAN_CAST(BYTE*, d);
winpr_Data_Write_UINT16(b, v & 0xFFFF);
winpr_Data_Write_UINT16(b + 2, (v >> 16) & 0xFFFF);
}
static inline void winpr_Data_Write_INT32_BE(void* d, INT32 v)
{
WINPR_ASSERT(d);
BYTE* b = WINPR_ENDIAN_CAST(BYTE*, d);
winpr_Data_Write_UINT16_BE(b, (v >> 16) & 0xFFFF);
winpr_Data_Write_UINT16_BE(b + 2, v & 0xFFFF);
}
static inline void winpr_Data_Write_INT64_NE(void* d, INT64 v)
{
WINPR_ASSERT(d);
INT64* pu = WINPR_ENDIAN_CAST(INT64*, d);
*pu = v;
}
static inline void winpr_Data_Write_INT64(void* d, INT64 v)
{
WINPR_ASSERT(d);
BYTE* b = WINPR_ENDIAN_CAST(BYTE*, d);
winpr_Data_Write_UINT32(b, v & 0xFFFFFFFF);
winpr_Data_Write_UINT32(b + 4, (v >> 32) & 0xFFFFFFFF);
}
static inline void winpr_Data_Write_INT64_BE(void* d, INT64 v)
{
WINPR_ASSERT(d);
BYTE* b = WINPR_ENDIAN_CAST(BYTE*, d);
winpr_Data_Write_UINT32_BE(b, (v >> 32) & 0xFFFFFFFF);
winpr_Data_Write_UINT32_BE(b + 4, v & 0xFFFFFFFF);
}
#if defined(WINPR_DEPRECATED)
#define Data_Read_UINT8_NE(_d, _v) _v = winpr_Data_Get_UINT8(_d)
#define Data_Read_UINT8(_d, _v) _v = winpr_Data_Get_UINT8(_d)
#define Data_Read_UINT16_NE(_d, _v) _v = winpr_Data_Get_UINT16_NE(_d)
#define Data_Read_UINT16(_d, _v) _v = winpr_Data_Get_UINT16(_d)
#define Data_Read_UINT16_BE(_d, _v) _v = winpr_Data_Get_UINT16_BE(_d)
#define Data_Read_UINT32_NE(_d, _v) _v = winpr_Data_Get_UINT32_NE(_d)
#define Data_Read_UINT32(_d, _v) _v = winpr_Data_Get_UINT32(_d)
#define Data_Read_UINT32_BE(_d, _v) _v = winpr_Data_Get_UINT32_BE(_d)
#define Data_Read_UINT64_NE(_d, _v) _v = winpr_Data_Get_UINT64_NE(_d)
#define Data_Read_UINT64(_d, _v) _v = winpr_Data_Get_UINT64(_d)
#define Data_Read_UINT64_BE(_d, _v) _v = winpr_Data_Get_UINT64_BE(_d)
#define Data_Write_UINT8_NE(_d, _v) winpr_Data_Write_UINT8_NE(_d, _v)
#define Data_Write_UINT8(_d, _v) winpr_Data_Write_UINT8(_d, _v)
#define Data_Write_UINT16_NE(_d, _v) winpr_Data_Write_UINT16_NE(_d, _v)
#define Data_Write_UINT16(_d, _v) winpr_Data_Write_UINT16(_d, _v)
#define Data_Write_UINT16_BE(_d, _v) winpr_Data_Write_UINT16_BE(_d, _v)
#define Data_Write_UINT32_NE(_d, _v) winpr_Data_Write_UINT32_NE(_d, _v)
#define Data_Write_UINT32(_d, _v) winpr_Data_Write_UINT32(_d, _v)
#define Data_Write_UINT32_BE(_d, _v) winpr_Data_Write_UINT32_BE(_d, _v)
#define Data_Write_UINT64_NE(_d, _v) winpr_Data_Write_UINT64_NE(_d, _v)
#define Data_Write_UINT64(_d, _v) winpr_Data_Write_UINT64(_d, _v)
#define Data_Write_UINT64_BE(_d, _v) winpr_Data_Write_UINT64_BE(_d, _v)
#endif
#ifdef __cplusplus
}
#endif
#endif /* WINPR_ENDIAN_H */

View File

@@ -0,0 +1,156 @@
/**
* WinPR: Windows Portable Runtime
* Process Environment Functions
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2013 Thincast Technologies GmbH
* Copyright 2013 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_ENVIRONMENT_H
#define WINPR_ENVIRONMENT_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#ifndef _WIN32
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API DWORD GetCurrentDirectoryA(DWORD nBufferLength, LPSTR lpBuffer);
WINPR_API DWORD GetCurrentDirectoryW(DWORD nBufferLength, LPWSTR lpBuffer);
WINPR_API BOOL SetCurrentDirectoryA(LPCSTR lpPathName);
WINPR_API BOOL SetCurrentDirectoryW(LPCWSTR lpPathName);
WINPR_API DWORD SearchPathA(LPCSTR lpPath, LPCSTR lpFileName, LPCSTR lpExtension,
DWORD nBufferLength, LPSTR lpBuffer, LPSTR* lpFilePart);
WINPR_API DWORD SearchPathW(LPCWSTR lpPath, LPCWSTR lpFileName, LPCWSTR lpExtension,
DWORD nBufferLength, LPWSTR lpBuffer, LPWSTR* lpFilePart);
WINPR_API LPSTR GetCommandLineA(VOID);
WINPR_API LPWSTR GetCommandLineW(VOID);
WINPR_API BOOL NeedCurrentDirectoryForExePathA(LPCSTR ExeName);
WINPR_API BOOL NeedCurrentDirectoryForExePathW(LPCWSTR ExeName);
#ifdef __cplusplus
}
#endif
#ifdef UNICODE
#define GetCurrentDirectory GetCurrentDirectoryW
#define SetCurrentDirectory SetCurrentDirectoryW
#define SearchPath SearchPathW
#define GetCommandLine GetCommandLineW
#define NeedCurrentDirectoryForExePath NeedCurrentDirectoryForExePathW
#else
#define GetCurrentDirectory GetCurrentDirectoryA
#define SetCurrentDirectory SetCurrentDirectoryA
#define SearchPath SearchPathA
#define GetCommandLine GetCommandLineA
#define NeedCurrentDirectoryForExePath NeedCurrentDirectoryForExePathA
#endif
#endif
#if !defined(_WIN32) || defined(_UWP)
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API DWORD GetEnvironmentVariableA(LPCSTR lpName, LPSTR lpBuffer, DWORD nSize);
WINPR_API DWORD GetEnvironmentVariableW(LPCWSTR lpName, LPWSTR lpBuffer, DWORD nSize);
WINPR_API BOOL SetEnvironmentVariableA(LPCSTR lpName, LPCSTR lpValue);
WINPR_API BOOL SetEnvironmentVariableW(LPCWSTR lpName, LPCWSTR lpValue);
/**
* A brief history of the GetEnvironmentStrings functions:
* http://blogs.msdn.com/b/oldnewthing/archive/2013/01/17/10385718.aspx
*/
WINPR_API BOOL FreeEnvironmentStringsA(LPCH lpszEnvironmentBlock);
WINPR_API BOOL FreeEnvironmentStringsW(LPWCH lpszEnvironmentBlock);
WINPR_ATTR_MALLOC(FreeEnvironmentStringsA, 1)
WINPR_ATTR_NODISCARD
WINPR_API LPCH GetEnvironmentStrings(VOID);
WINPR_ATTR_MALLOC(FreeEnvironmentStringsW, 1)
WINPR_ATTR_NODISCARD
WINPR_API LPWCH GetEnvironmentStringsW(VOID);
WINPR_API BOOL SetEnvironmentStringsA(LPCH NewEnvironment);
WINPR_API BOOL SetEnvironmentStringsW(LPWCH NewEnvironment);
WINPR_API DWORD ExpandEnvironmentStringsA(LPCSTR lpSrc, LPSTR lpDst, DWORD nSize);
WINPR_API DWORD ExpandEnvironmentStringsW(LPCWSTR lpSrc, LPWSTR lpDst, DWORD nSize);
#ifdef __cplusplus
}
#endif
#ifdef UNICODE
#define GetEnvironmentVariable GetEnvironmentVariableW
#define SetEnvironmentVariable SetEnvironmentVariableW
#define GetEnvironmentStrings GetEnvironmentStringsW
#define SetEnvironmentStrings SetEnvironmentStringsW
#define ExpandEnvironmentStrings ExpandEnvironmentStringsW
#define FreeEnvironmentStrings FreeEnvironmentStringsW
#else
#define GetEnvironmentVariable GetEnvironmentVariableA
#define SetEnvironmentVariable SetEnvironmentVariableA
#define GetEnvironmentStringsA GetEnvironmentStrings
#define SetEnvironmentStrings SetEnvironmentStringsA
#define ExpandEnvironmentStrings ExpandEnvironmentStringsA
#define FreeEnvironmentStrings FreeEnvironmentStringsA
#endif
#endif
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API LPCH MergeEnvironmentStrings(PCSTR original, PCSTR merge);
WINPR_API DWORD GetEnvironmentVariableEBA(LPCSTR envBlock, LPCSTR lpName, LPSTR lpBuffer,
DWORD nSize);
WINPR_API BOOL SetEnvironmentVariableEBA(LPSTR* envBlock, LPCSTR lpName, LPCSTR lpValue);
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char** EnvironmentBlockToEnvpA(LPCH lpszEnvironmentBlock);
WINPR_API DWORD GetEnvironmentVariableX(const char* lpName, char* lpBuffer, DWORD nSize);
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* GetEnvAlloc(LPCSTR lpName);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_ENVIRONMENT_H */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,592 @@
/**
* WinPR: Windows Portable Runtime
* File Functions
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2016 David PHAM-VAN <d.phamvan@inuvika.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_FILE_H
#define WINPR_FILE_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/nt.h>
#include <winpr/io.h>
#include <winpr/error.h>
#include <winpr/handle.h>
#ifndef _WIN32
#include <stdio.h>
#ifndef MAX_PATH
#define MAX_PATH 260
#endif
#define INVALID_HANDLE_VALUE ((HANDLE)(LONG_PTR)-1)
#define INVALID_FILE_SIZE ((DWORD)0xFFFFFFFF)
#define INVALID_SET_FILE_POINTER ((DWORD)-1)
#define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
#define FILE_ATTRIBUTE_READONLY 0x00000001u
#define FILE_ATTRIBUTE_HIDDEN 0x00000002u
#define FILE_ATTRIBUTE_SYSTEM 0x00000004u
#define FILE_ATTRIBUTE_DIRECTORY 0x00000010u
#define FILE_ATTRIBUTE_ARCHIVE 0x00000020u
#define FILE_ATTRIBUTE_DEVICE 0x00000040u
#define FILE_ATTRIBUTE_NORMAL 0x00000080u
#define FILE_ATTRIBUTE_TEMPORARY 0x00000100u
#define FILE_ATTRIBUTE_SPARSE_FILE 0x00000200u
#define FILE_ATTRIBUTE_REPARSE_POINT 0x00000400u
#define FILE_ATTRIBUTE_COMPRESSED 0x00000800u
#define FILE_ATTRIBUTE_OFFLINE 0x00001000u
#define FILE_ATTRIBUTE_NOT_CONTENT_INDEXED 0x00002000u
#define FILE_ATTRIBUTE_ENCRYPTED 0x00004000u
#define FILE_ATTRIBUTE_VIRTUAL 0x00010000u
#define FILE_NOTIFY_CHANGE_FILE_NAME 0x00000001
#define FILE_NOTIFY_CHANGE_DIR_NAME 0x00000002
#define FILE_NOTIFY_CHANGE_ATTRIBUTES 0x00000004
#define FILE_NOTIFY_CHANGE_SIZE 0x00000008
#define FILE_NOTIFY_CHANGE_LAST_WRITE 0x00000010
#define FILE_NOTIFY_CHANGE_LAST_ACCESS 0x00000020
#define FILE_NOTIFY_CHANGE_CREATION 0x00000040
#define FILE_NOTIFY_CHANGE_SECURITY 0x00000100
#define FILE_ACTION_ADDED 0x00000001
#define FILE_ACTION_REMOVED 0x00000002
#define FILE_ACTION_MODIFIED 0x00000003
#define FILE_ACTION_RENAMED_OLD_NAME 0x00000004
#define FILE_ACTION_RENAMED_NEW_NAME 0x00000005
#define FILE_CASE_SENSITIVE_SEARCH 0x00000001
#define FILE_CASE_PRESERVED_NAMES 0x00000002
#define FILE_UNICODE_ON_DISK 0x00000004
#define FILE_PERSISTENT_ACLS 0x00000008
#define FILE_FILE_COMPRESSION 0x00000010
#define FILE_VOLUME_QUOTAS 0x00000020
#define FILE_SUPPORTS_SPARSE_FILES 0x00000040
#define FILE_SUPPORTS_REPARSE_POINTS 0x00000080
#define FILE_SUPPORTS_REMOTE_STORAGE 0x00000100
#define FILE_VOLUME_IS_COMPRESSED 0x00008000
#define FILE_SUPPORTS_OBJECT_IDS 0x00010000
#define FILE_SUPPORTS_ENCRYPTION 0x00020000
#define FILE_NAMED_STREAMS 0x00040000
#define FILE_READ_ONLY_VOLUME 0x00080000
#define FILE_SEQUENTIAL_WRITE_ONCE 0x00100000
#define FILE_SUPPORTS_TRANSACTIONS 0x00200000
#define FILE_SUPPORTS_HARD_LINKS 0x00400000
#define FILE_SUPPORTS_EXTENDED_ATTRIBUTES 0x00800000
#define FILE_SUPPORTS_OPEN_BY_FILE_ID 0x01000000
#define FILE_SUPPORTS_USN_JOURNAL 0x02000000
#define FILE_FLAG_WRITE_THROUGH 0x80000000
#define FILE_FLAG_OVERLAPPED 0x40000000
#define FILE_FLAG_NO_BUFFERING 0x20000000
#define FILE_FLAG_RANDOM_ACCESS 0x10000000
#define FILE_FLAG_SEQUENTIAL_SCAN 0x08000000
#define FILE_FLAG_DELETE_ON_CLOSE 0x04000000
#define FILE_FLAG_BACKUP_SEMANTICS 0x02000000
#define FILE_FLAG_POSIX_SEMANTICS 0x01000000
#define FILE_FLAG_OPEN_REPARSE_POINT 0x00200000
#define FILE_FLAG_OPEN_NO_RECALL 0x00100000
#define FILE_FLAG_FIRST_PIPE_INSTANCE 0x00080000
#define PAGE_NOACCESS 0x00000001
#define PAGE_READONLY 0x00000002
#define PAGE_READWRITE 0x00000004
#define PAGE_WRITECOPY 0x00000008
#define PAGE_EXECUTE 0x00000010
#define PAGE_EXECUTE_READ 0x00000020
#define PAGE_EXECUTE_READWRITE 0x00000040
#define PAGE_EXECUTE_WRITECOPY 0x00000080
#define PAGE_GUARD 0x00000100
#define PAGE_NOCACHE 0x00000200
#define PAGE_WRITECOMBINE 0x00000400
#define MEM_COMMIT 0x00001000
#define MEM_RESERVE 0x00002000
#define MEM_DECOMMIT 0x00004000
#define MEM_RELEASE 0x00008000
#define MEM_FREE 0x00010000
#define MEM_PRIVATE 0x00020000
#define MEM_MAPPED 0x00040000
#define MEM_RESET 0x00080000
#define MEM_TOP_DOWN 0x00100000
#define MEM_WRITE_WATCH 0x00200000
#define MEM_PHYSICAL 0x00400000
#define MEM_4MB_PAGES 0x80000000
#define MEM_IMAGE SEC_IMAGE
#define SEC_NO_CHANGE 0x00400000
#define SEC_FILE 0x00800000
#define SEC_IMAGE 0x01000000
#define SEC_VLM 0x02000000
#define SEC_RESERVE 0x04000000
#define SEC_COMMIT 0x08000000
#define SEC_NOCACHE 0x10000000
#define SEC_WRITECOMBINE 0x40000000
#define SEC_LARGE_PAGES 0x80000000
#define SECTION_MAP_EXECUTE_EXPLICIT 0x00020
#define SECTION_EXTEND_SIZE 0x00010
#define SECTION_MAP_READ 0x00004
#define SECTION_MAP_WRITE 0x00002
#define SECTION_QUERY 0x00001
#define SECTION_MAP_EXECUTE 0x00008
#define SECTION_ALL_ACCESS 0xF001F
#define FILE_MAP_COPY SECTION_QUERY
#define FILE_MAP_WRITE SECTION_MAP_WRITE
#define FILE_MAP_READ SECTION_MAP_READ
#define FILE_MAP_ALL_ACCESS SECTION_ALL_ACCESS
#define FILE_MAP_EXECUTE SECTION_MAP_EXECUTE_EXPLICIT
#define CREATE_NEW 1
#define CREATE_ALWAYS 2
#define OPEN_EXISTING 3
#define OPEN_ALWAYS 4
#define TRUNCATE_EXISTING 5
#define FIND_FIRST_EX_CASE_SENSITIVE 0x1
#define FIND_FIRST_EX_LARGE_FETCH 0x2
#define STD_INPUT_HANDLE (DWORD) - 10
#define STD_OUTPUT_HANDLE (DWORD) - 11
#define STD_ERROR_HANDLE (DWORD) - 12
#define FILE_BEGIN 0
#define FILE_CURRENT 1
#define FILE_END 2
#define LOCKFILE_FAIL_IMMEDIATELY 1
#define LOCKFILE_EXCLUSIVE_LOCK 2
#define MOVEFILE_REPLACE_EXISTING 0x1
#define MOVEFILE_COPY_ALLOWED 0x2
#define MOVEFILE_DELAY_UNTIL_REBOOT 0x4
#define MOVEFILE_WRITE_THROUGH 0x8
#define MOVEFILE_CREATE_HARDLINK 0x10
#define MOVEFILE_FAIL_IF_NOT_TRACKABLE 0x20
typedef union
{
PVOID64 Buffer;
ULONGLONG Alignment;
} FILE_SEGMENT_ELEMENT, *PFILE_SEGMENT_ELEMENT;
typedef struct
{
DWORD dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
DWORD nFileSizeHigh;
DWORD nFileSizeLow;
DWORD dwReserved0;
DWORD dwReserved1;
CHAR cFileName[MAX_PATH];
CHAR cAlternateFileName[14];
} WIN32_FIND_DATAA, *PWIN32_FIND_DATAA, *LPWIN32_FIND_DATAA;
typedef struct
{
DWORD dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
DWORD nFileSizeHigh;
DWORD nFileSizeLow;
DWORD dwReserved0;
DWORD dwReserved1;
WCHAR cFileName[MAX_PATH];
WCHAR cAlternateFileName[14];
} WIN32_FIND_DATAW, *PWIN32_FIND_DATAW, *LPWIN32_FIND_DATAW;
typedef struct
{
DWORD dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
DWORD dwVolumeSerialNumber;
DWORD nFileSizeHigh;
DWORD nFileSizeLow;
DWORD nNumberOfLinks;
DWORD nFileIndexHigh;
DWORD nFileIndexLow;
} BY_HANDLE_FILE_INFORMATION, *PBY_HANDLE_FILE_INFORMATION, *LPBY_HANDLE_FILE_INFORMATION;
typedef enum
{
FindExInfoStandard,
FindExInfoMaxInfoLevel
} FINDEX_INFO_LEVELS;
typedef enum
{
FindExSearchNameMatch,
FindExSearchLimitToDirectories,
FindExSearchLimitToDevices,
FindExSearchMaxSearchOp
} FINDEX_SEARCH_OPS;
typedef VOID (*LPOVERLAPPED_COMPLETION_ROUTINE)(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered,
LPOVERLAPPED lpOverlapped);
#ifdef UNICODE
#define WIN32_FIND_DATA WIN32_FIND_DATAW
#define PWIN32_FIND_DATA PWIN32_FIND_DATAW
#define LPWIN32_FIND_DATA LPWIN32_FIND_DATAW
#else
#define WIN32_FIND_DATA WIN32_FIND_DATAA
#define PWIN32_FIND_DATA PWIN32_FIND_DATAA
#define LPWIN32_FIND_DATA LPWIN32_FIND_DATAA
#endif
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_DEPRECATED_VAR("since 3.16.0, Use winpr_CreateFile",
WINPR_ATTR_MALLOC(CloseHandle, 1) WINPR_API HANDLE CreateFileA(
LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile));
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_API HANDLE CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile);
WINPR_DEPRECATED_VAR("since 3.16.0, Use winpr_DeleteFile",
WINPR_API BOOL DeleteFileA(LPCSTR lpFileName));
WINPR_API BOOL DeleteFileW(LPCWSTR lpFileName);
WINPR_API BOOL ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead,
LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped);
WINPR_API BOOL ReadFileEx(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead,
LPOVERLAPPED lpOverlapped,
LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);
WINPR_API BOOL ReadFileScatter(HANDLE hFile, FILE_SEGMENT_ELEMENT aSegmentArray[],
DWORD nNumberOfBytesToRead, LPDWORD lpReserved,
LPOVERLAPPED lpOverlapped);
WINPR_API BOOL WriteFile(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped);
WINPR_API BOOL WriteFileEx(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite,
LPOVERLAPPED lpOverlapped,
LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);
WINPR_API BOOL WriteFileGather(HANDLE hFile, FILE_SEGMENT_ELEMENT aSegmentArray[],
DWORD nNumberOfBytesToWrite, LPDWORD lpReserved,
LPOVERLAPPED lpOverlapped);
WINPR_API BOOL FlushFileBuffers(HANDLE hFile);
typedef struct
{
DWORD dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
DWORD nFileSizeHigh;
DWORD nFileSizeLow;
} WIN32_FILE_ATTRIBUTE_DATA, *LPWIN32_FILE_ATTRIBUTE_DATA;
typedef enum
{
GetFileExInfoStandard,
GetFileExMaxInfoLevel
} GET_FILEEX_INFO_LEVELS;
WINPR_API BOOL GetFileAttributesExA(LPCSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
LPVOID lpFileInformation);
WINPR_API DWORD GetFileAttributesA(LPCSTR lpFileName);
WINPR_API BOOL GetFileAttributesExW(LPCWSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
LPVOID lpFileInformation);
WINPR_API DWORD GetFileAttributesW(LPCWSTR lpFileName);
WINPR_API BOOL GetFileInformationByHandle(HANDLE hFile,
LPBY_HANDLE_FILE_INFORMATION lpFileInformation);
WINPR_API BOOL SetFileAttributesA(LPCSTR lpFileName, DWORD dwFileAttributes);
WINPR_API BOOL SetFileAttributesW(LPCWSTR lpFileName, DWORD dwFileAttributes);
WINPR_API BOOL SetEndOfFile(HANDLE hFile);
WINPR_API DWORD WINAPI GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh);
WINPR_API DWORD SetFilePointer(HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHigh,
DWORD dwMoveMethod);
WINPR_API BOOL SetFilePointerEx(HANDLE hFile, LARGE_INTEGER liDistanceToMove,
PLARGE_INTEGER lpNewFilePointer, DWORD dwMoveMethod);
WINPR_API BOOL LockFile(HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh,
DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh);
WINPR_API BOOL LockFileEx(HANDLE hFile, DWORD dwFlags, DWORD dwReserved,
DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh,
LPOVERLAPPED lpOverlapped);
WINPR_API BOOL UnlockFile(HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh,
DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh);
WINPR_API BOOL UnlockFileEx(HANDLE hFile, DWORD dwReserved, DWORD nNumberOfBytesToUnlockLow,
DWORD nNumberOfBytesToUnlockHigh, LPOVERLAPPED lpOverlapped);
WINPR_API BOOL SetFileTime(HANDLE hFile, const FILETIME* lpCreationTime,
const FILETIME* lpLastAccessTime, const FILETIME* lpLastWriteTime);
WINPR_API BOOL FindClose(HANDLE hFindFile);
WINPR_ATTR_MALLOC(FindClose, 1)
WINPR_API HANDLE FindFirstFileA(LPCSTR lpFileName, LPWIN32_FIND_DATAA lpFindFileData);
WINPR_ATTR_MALLOC(FindClose, 1)
WINPR_API HANDLE FindFirstFileW(LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFindFileData);
WINPR_ATTR_MALLOC(FindClose, 1)
WINPR_API HANDLE FindFirstFileExA(LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
LPVOID lpSearchFilter, DWORD dwAdditionalFlags);
WINPR_ATTR_MALLOC(FindClose, 1)
WINPR_API HANDLE FindFirstFileExW(LPCWSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
LPVOID lpSearchFilter, DWORD dwAdditionalFlags);
WINPR_API BOOL FindNextFileA(HANDLE hFindFile, LPWIN32_FIND_DATAA lpFindFileData);
WINPR_API BOOL FindNextFileW(HANDLE hFindFile, LPWIN32_FIND_DATAW lpFindFileData);
WINPR_API BOOL CreateDirectoryA(LPCSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes);
WINPR_API BOOL CreateDirectoryW(LPCWSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes);
WINPR_DEPRECATED_VAR("since 3.16.0, Use winpr_RemoveDirectory",
WINPR_API BOOL RemoveDirectoryA(LPCSTR lpPathName));
WINPR_API BOOL RemoveDirectoryW(LPCWSTR lpPathName);
WINPR_API HANDLE GetStdHandle(DWORD nStdHandle);
WINPR_API BOOL SetStdHandle(DWORD nStdHandle, HANDLE hHandle);
WINPR_API BOOL SetStdHandleEx(DWORD dwStdHandle, HANDLE hNewHandle, HANDLE* phOldHandle);
WINPR_API BOOL GetDiskFreeSpaceA(LPCSTR lpRootPathName, LPDWORD lpSectorsPerCluster,
LPDWORD lpBytesPerSector, LPDWORD lpNumberOfFreeClusters,
LPDWORD lpTotalNumberOfClusters);
WINPR_API BOOL GetDiskFreeSpaceW(LPCWSTR lpRootPathName, LPDWORD lpSectorsPerCluster,
LPDWORD lpBytesPerSector, LPDWORD lpNumberOfFreeClusters,
LPDWORD lpTotalNumberOfClusters);
WINPR_DEPRECATED_VAR("since 3.16.0, Use winpr_MoveFileEx",
WINPR_API BOOL MoveFileExA(LPCSTR lpExistingFileName, LPCSTR lpNewFileName,
DWORD dwFlags));
WINPR_API BOOL MoveFileExW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName, DWORD dwFlags);
WINPR_DEPRECATED_VAR("since 3.16.0, Use winpr_MoveFile",
WINPR_API BOOL MoveFileA(LPCSTR lpExistingFileName, LPCSTR lpNewFileName));
WINPR_API BOOL MoveFileW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName);
#ifdef __cplusplus
}
#endif
#ifdef UNICODE
#define CreateFile CreateFileW
#define DeleteFile DeleteFileW
#define FindFirstFile FindFirstFileW
#define FindFirstFileEx FindFirstFileExW
#define FindNextFile FindNextFileW
#define CreateDirectory CreateDirectoryW
#define RemoveDirectory RemoveDirectoryW
#define GetFileAttributesEx GetFileAttributesExW
#define GetFileAttributes GetFileAttributesW
#define SetFileAttributes SetFileAttributesW
#define GetDiskFreeSpace GetDiskFreeSpaceW
#define MoveFileEx MoveFileExW
#define MoveFile MoveFileW
#else
#define CreateFile CreateFileA
#define DeleteFile DeleteFileA
#define FindFirstFile FindFirstFileA
#define FindFirstFileEx FindFirstFileExA
#define FindNextFile FindNextFileA
#define CreateDirectory CreateDirectoryA
#define RemoveDirectory RemoveDirectoryA
#define GetFileAttributesEx GetFileAttributesExA
#define GetFileAttributes GetFileAttributesA
#define SetFileAttributes SetFileAttributesA
#define GetDiskFreeSpace GetDiskFreeSpaceA
#define MoveFileEx MoveFileExA
#define MoveFile MoveFileA
#endif
/* Extra Functions */
typedef BOOL (*pcIsFileHandled)(LPCSTR lpFileName);
typedef HANDLE (*pcCreateFileA)(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile);
typedef struct
{
pcIsFileHandled IsHandled;
pcCreateFileA CreateFileA;
} HANDLE_CREATOR, *PHANDLE_CREATOR, *LPHANDLE_CREATOR;
#endif /* _WIN32 */
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API BOOL ValidFileNameComponent(LPCWSTR lpFileName);
#if defined(_UWP) || !defined(_WIN32)
WINPR_API DWORD GetLogicalDriveStringsA(DWORD nBufferLength, LPSTR lpBuffer);
WINPR_API DWORD GetLogicalDriveStringsW(DWORD nBufferLength, LPWSTR lpBuffer);
#endif
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_API HANDLE winpr_CreateFile(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile);
#ifdef __cplusplus
}
#endif
#ifdef _UWP
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile);
WINPR_API HANDLE CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile);
WINPR_API DWORD WINAPI GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh);
WINPR_API DWORD SetFilePointer(HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHigh,
DWORD dwMoveMethod);
WINPR_API HANDLE FindFirstFileA(LPCSTR lpFileName, LPWIN32_FIND_DATAA lpFindFileData);
WINPR_API HANDLE FindFirstFileW(LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFindFileData);
WINPR_API DWORD GetFullPathNameA(LPCSTR lpFileName, DWORD nBufferLength, LPSTR lpBuffer,
LPSTR* lpFilePart);
WINPR_API BOOL GetDiskFreeSpaceA(LPCSTR lpRootPathName, LPDWORD lpSectorsPerCluster,
LPDWORD lpBytesPerSector, LPDWORD lpNumberOfFreeClusters,
LPDWORD lpTotalNumberOfClusters);
WINPR_API BOOL GetDiskFreeSpaceW(LPCWSTR lpRootPathName, LPDWORD lpSectorsPerCluster,
LPDWORD lpBytesPerSector, LPDWORD lpNumberOfFreeClusters,
LPDWORD lpTotalNumberOfClusters);
WINPR_API BOOL PathIsDirectoryEmptyA(LPCSTR pszPath);
WINPR_API UINT GetACP(void);
#ifdef UNICODE
#define CreateFile CreateFileW
#define FindFirstFile FindFirstFileW
#else
#define CreateFile CreateFileA
#define FindFirstFile FindFirstFileA
#endif
#ifdef __cplusplus
}
#endif
#ifdef UNICODE
#define FindFirstFile FindFirstFileW
#else
#define FindFirstFile FindFirstFileA
#endif
#endif
#define WILDCARD_STAR 0x00000001
#define WILDCARD_QM 0x00000002
#define WILDCARD_DOS 0x00000100
#define WILDCARD_DOS_STAR 0x00000110
#define WILDCARD_DOS_QM 0x00000120
#define WILDCARD_DOS_DOT 0x00000140
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API BOOL FilePatternMatchA(LPCSTR lpFileName, LPCSTR lpPattern);
WINPR_API LPSTR FilePatternFindNextWildcardA(LPCSTR lpPattern, DWORD* pFlags);
WINPR_API int UnixChangeFileMode(const char* filename, int flags);
WINPR_API BOOL IsNamedPipeFileNameA(LPCSTR lpName);
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* GetNamedPipeNameWithoutPrefixA(LPCSTR lpName);
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* GetNamedPipeUnixDomainSocketBaseFilePathA(void);
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* GetNamedPipeUnixDomainSocketFilePathA(LPCSTR lpName);
WINPR_API int GetNamePipeFileDescriptor(HANDLE hNamedPipe);
WINPR_API HANDLE GetFileHandleForFileDescriptor(int fd);
WINPR_ATTR_MALLOC(fclose, 1)
WINPR_API FILE* winpr_fopen(const char* path, const char* mode);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_FILE_H */

View File

@@ -0,0 +1,64 @@
/**
* WinPR: Windows Portable Runtime
* Handle Management
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_HANDLE_H
#define WINPR_HANDLE_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/security.h>
#ifdef __cplusplus
extern "C"
{
#endif
#define WINPR_FD_READ_BIT 0
#define WINPR_FD_READ (1 << WINPR_FD_READ_BIT)
#define WINPR_FD_WRITE_BIT 1
#define WINPR_FD_WRITE (1 << WINPR_FD_WRITE_BIT)
#ifndef _WIN32
#define DUPLICATE_CLOSE_SOURCE 0x00000001
#define DUPLICATE_SAME_ACCESS 0x00000002
#define HANDLE_FLAG_INHERIT 0x00000001
#define HANDLE_FLAG_PROTECT_FROM_CLOSE 0x00000002
WINPR_API BOOL CloseHandle(HANDLE hObject);
WINPR_API BOOL DuplicateHandle(HANDLE hSourceProcessHandle, HANDLE hSourceHandle,
HANDLE hTargetProcessHandle, LPHANDLE lpTargetHandle,
DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwOptions);
WINPR_API BOOL GetHandleInformation(HANDLE hObject, LPDWORD lpdwFlags);
WINPR_API BOOL SetHandleInformation(HANDLE hObject, DWORD dwMask, DWORD dwFlags);
#endif
#ifdef __cplusplus
}
#endif
#endif /* WINPR_HANDLE_H */

View File

@@ -0,0 +1,196 @@
/**
* WinPR: Windows Portable Runtime
* Image Utils
*
* Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_IMAGE_H
#define WINPR_IMAGE_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#pragma pack(push, 1)
typedef struct
{
BYTE bfType[2];
UINT32 bfSize;
UINT16 bfReserved1;
UINT16 bfReserved2;
UINT32 bfOffBits;
} WINPR_BITMAP_FILE_HEADER;
typedef struct
{
UINT32 biSize;
INT32 biWidth;
INT32 biHeight;
UINT16 biPlanes;
UINT16 biBitCount;
UINT32 biCompression;
UINT32 biSizeImage;
INT32 biXPelsPerMeter;
INT32 biYPelsPerMeter;
UINT32 biClrUsed;
UINT32 biClrImportant;
} WINPR_BITMAP_INFO_HEADER;
typedef struct
{
UINT32 bcSize;
UINT16 bcWidth;
UINT16 bcHeight;
UINT16 bcPlanes;
UINT16 bcBitCount;
} WINPR_BITMAP_CORE_HEADER;
#pragma pack(pop)
/** @defgrop WINPR_IMAGE_FORMAT
* #{
*/
#define WINPR_IMAGE_BITMAP 0
#define WINPR_IMAGE_PNG 1
#define WINPR_IMAGE_JPEG 2 /** @since version 3.3.0 */
#define WINPR_IMAGE_WEBP 3 /** @since version 3.3.0 */
/** #} */
#define WINPR_IMAGE_BMP_HEADER_LEN 54
typedef struct
{
int type;
UINT32 width;
UINT32 height;
BYTE* data;
UINT32 scanline;
UINT32 bitsPerPixel;
UINT32 bytesPerPixel;
} wImage;
/** @defgroup WINPR_IMAGE_CMP_FLAGS WINPR_IMAGE_CMP_FLAGS
* @since version 3.3.0
* @{
*/
typedef enum
{
WINPR_IMAGE_CMP_NO_FLAGS = 0,
WINPR_IMAGE_CMP_IGNORE_DEPTH = 1,
WINPR_IMAGE_CMP_IGNORE_ALPHA = 2,
WINPR_IMAGE_CMP_FUZZY = 4
} wImageFlags;
/** @} */
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API int winpr_bitmap_write(const char* filename, const BYTE* data, size_t width,
size_t height, size_t bpp);
/** @brief write a bitmap to a file
*
* @param filename the name of the file to write to
* @param data the data of the bitmap without headers
* @param stride the byte size of a line in the image
* @param width the width in pixels of a line
* @param height the height of the bitmap
* @param bpp the color depth of the bitmap
*
* @since version 3.3.0
*
* @return \b >=0 for success, /b <0 for an error
*/
WINPR_API int winpr_bitmap_write_ex(const char* filename, const BYTE* data, size_t stride,
size_t width, size_t height, size_t bpp);
WINPR_API BYTE* winpr_bitmap_construct_header(size_t width, size_t height, size_t bpp);
WINPR_API int winpr_image_write(wImage* image, const char* filename);
WINPR_API int winpr_image_write_ex(wImage* image, UINT32 format, const char* filename);
WINPR_API int winpr_image_read(wImage* image, const char* filename);
/** @brief write a bitmap to a buffer and return it
*
* @param image the image to write
* @param format the format of type @ref WINPR_IMAGE_FORMAT
* @param size a pointer to hold the size in bytes of the allocated bitmap
*
* @since version 3.3.0
*
* @return \b nullptr in case of failure, a pointer to an allocated buffer otherwise. Use \b
* free as deallocator
*/
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API void* winpr_image_write_buffer(wImage* image, UINT32 format, size_t* size);
WINPR_API int winpr_image_read_buffer(wImage* image, const BYTE* buffer, size_t size);
WINPR_API void winpr_image_free(wImage* image, BOOL bFreeBuffer);
WINPR_ATTR_MALLOC(winpr_image_free, 1)
WINPR_ATTR_NODISCARD
WINPR_API wImage* winpr_image_new(void);
/** @brief Check if a image format is supported
*
* @param format the format of type @ref WINPR_IMAGE_FORMAT
*
* @since version 3.3.0
*
* @return \b TRUE if the format is supported, \b FALSE otherwise
*/
WINPR_API BOOL winpr_image_format_is_supported(UINT32 format);
/** @brief Return the file extension of a format
*
* @param format the format of type @ref WINPR_IMAGE_FORMAT
*
* @since version 3.3.0
*
* @return a extension string if format has one or \b nullptr
*/
WINPR_API const char* winpr_image_format_extension(UINT32 format);
/** @brief Return the mime type of a format
*
* @param format the format of type @ref WINPR_IMAGE_FORMAT
*
* @since version 3.3.0
*
* @return a mime type string if format has one or \b nullptr
*/
WINPR_API const char* winpr_image_format_mime(UINT32 format);
/** @brief Check if two images are content equal
*
* @param imageA the first image for the comparison
* @param imageB the second image for the comparison
* @param flags Comparison flags @ref WINPR_IMAGE_CMP_FLAGS
*
* @since version 3.3.0
*
* @return \b TRUE if they are equal, \b FALSE otherwise
*/
WINPR_API BOOL winpr_image_equal(const wImage* imageA, const wImage* imageB, UINT32 flags);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_IMAGE_H */

View File

@@ -0,0 +1,158 @@
/**
* WinPR: Windows Portable Runtime
* .ini config file
*
* Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_UTILS_INI_H
#define WINPR_UTILS_INI_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
typedef struct s_wIniFile wIniFile;
#ifdef __cplusplus
extern "C"
{
#endif
/** @brief read an ini file from a buffer
*
* @param ini The instance to use, must not be \b nullptr
* @param buffer The buffer to read from, must be a '\0' terminated string.
*
* @return > 0 for success, < 0 for failure
*/
WINPR_API int IniFile_ReadBuffer(wIniFile* ini, const char* buffer);
/** @brief read an ini file from a file
*
* @param ini The instance to use, must not be \b nullptr
* @param filename The name of the file to read from, must be a '\0' terminated string.
*
* @return > 0 for success, < 0 for failure
*/
WINPR_API int IniFile_ReadFile(wIniFile* ini, const char* filename);
/** @brief write an ini instance to a buffer
*
* @param ini The instance to use, must not be \b nullptr
*
* @return A newly allocated string, use \b free after use. \b nullptr in case of failure
*/
WINPR_API char* IniFile_WriteBuffer(wIniFile* ini);
/** @brief write an ini instance to a file
*
* @param ini The instance to use, must not be \b nullptr
* @param filename The name of the file as '\0' terminated string.
*
* @return > 0 for success, < 0 for failure
*/
WINPR_API int IniFile_WriteFile(wIniFile* ini, const char* filename);
/** @brief Get the number and names of sections in the ini instance
*
* @param ini The instance to use, must not be \b nullptr
* @param count A buffer that will contain the number of sections
*
* @return A newly allocated array of strings (size \b count). Use \b free after use
*/
WINPR_API char** IniFile_GetSectionNames(wIniFile* ini, size_t* count);
/** @brief Get the number and names of keys of a section in the ini instance
*
* @param ini The instance to use, must not be \b nullptr
* @param section The name of the section as '\0' terminated string.
* @param count A buffer that will contain the number of sections
*
* @return A newly allocated array of strings (size \b count). Use \b free after use
*/
WINPR_API char** IniFile_GetSectionKeyNames(wIniFile* ini, const char* section, size_t* count);
/** @brief Get an ini [section/key] value of type string
*
* @param ini The instance to use, must not be \b nullptr
* @param section The name of the section as '\0' terminated string.
* @param key The name of the key as '\0' terminated string.
*
* @return The value of the [section/key] as '\0' terminated string or \b nullptr
*/
WINPR_API const char* IniFile_GetKeyValueString(wIniFile* ini, const char* section,
const char* key);
/** @brief Get an ini [section/key] value of type int
*
* @param ini The instance to use, must not be \b nullptr
* @param section The name of the section as '\0' terminated string.
* @param key The name of the key as '\0' terminated string.
*
* @return The value of the [section/key]
*/
WINPR_API int IniFile_GetKeyValueInt(wIniFile* ini, const char* section, const char* key);
/** @brief Set an ini [section/key] value of type string
*
* @param ini The instance to use, must not be \b nullptr
* @param section The name of the section as '\0' terminated string.
* @param key The name of the key as '\0' terminated string.
* @param value The value of the [section/key] as '\0' terminated string.
*
* @return > 0 for success, < 0 for failure
*/
WINPR_API int IniFile_SetKeyValueString(wIniFile* ini, const char* section, const char* key,
const char* value);
/** @brief Set an ini [section/key] value of type int
*
* @param ini The instance to use, must not be \b nullptr
* @param section The name of the section as '\0' terminated string.
* @param key The name of the key as '\0' terminated string.
* @param value The value of the [section/key]
*
* @return > 0 for success, < 0 for failure
*/
WINPR_API int IniFile_SetKeyValueInt(wIniFile* ini, const char* section, const char* key,
int value);
/** @brief Free a ini instance
*
* @param ini The instance to free, may be \b nullptr
*/
WINPR_API void IniFile_Free(wIniFile* ini);
/** @brief Create a new ini instance
*
* @return The newly allocated instance or \b nullptr if failed.
*/
WINPR_ATTR_MALLOC(IniFile_Free, 1)
WINPR_ATTR_NODISCARD
WINPR_API wIniFile* IniFile_New(void);
/** @brief Clone a ini instance
*
* @param ini The instance to free, may be \b nullptr
*
* @return the cloned instance or \b nullptr in case of \b ini was \b nullptr or failure
*/
WINPR_API wIniFile* IniFile_Clone(const wIniFile* ini);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_UTILS_INI_H */

View File

@@ -0,0 +1,910 @@
/**
* WinPR: Windows Portable Runtime
* Input Functions
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_INPUT_H
#define WINPR_INPUT_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
/**
* Key Flags
*/
#define KBDEXT 0x0100u
#define KBDMULTIVK 0x0200u
#define KBDSPECIAL 0x0400u
#define KBDNUMPAD 0x0800u
#define KBDUNICODE 0x1000u
#define KBDINJECTEDVK 0x2000u
#define KBDMAPPEDVK 0x4000u
#define KBDBREAK 0x8000u
/*
* Virtual Key Codes (Windows):
* http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731/
* http://msdn.microsoft.com/en-us/library/ms927178.aspx
* https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
*/
/* Mouse buttons */
#define VK_LBUTTON 0x01 /* Left mouse button */
#define VK_RBUTTON 0x02 /* Right mouse button */
#define VK_CANCEL 0x03 /* Control-break processing */
#define VK_MBUTTON 0x04 /* Middle mouse button (three-button mouse) */
#define VK_XBUTTON1 0x05 /* Windows 2000/XP: X1 mouse button */
#define VK_XBUTTON2 0x06 /* Windows 2000/XP: X2 mouse button */
/* 0x07 is undefined */
#define VK_BACK 0x08 /* BACKSPACE key */
#define VK_TAB 0x09 /* TAB key */
/* 0x0A to 0x0B are reserved */
#define VK_CLEAR 0x0C /* CLEAR key */
#define VK_RETURN 0x0D /* ENTER key */
/* 0x0E to 0x0F are undefined */
#define VK_SHIFT 0x10 /* SHIFT key */
#define VK_CONTROL 0x11 /* CTRL key */
#define VK_MENU 0x12 /* ALT key */
#define VK_PAUSE 0x13 /* PAUSE key */
#define VK_CAPITAL 0x14 /* CAPS LOCK key */
#define VK_KANA 0x15 /* Input Method Editor (IME) Kana mode */
#define VK_HANGUEL \
0x15 /* IME Hanguel mode (maintained for compatibility; use #define VK_HANGUL) \
*/
#define VK_HANGUL 0x15 /* IME Hangul mode */
#define VK_IME_ON 0x16
#define VK_JUNJA 0x17 /* IME Junja mode */
#define VK_FINAL 0x18 /* IME final mode */
#define VK_HANJA 0x19 /* IME Hanja mode */
#define VK_KANJI 0x19 /* IME Kanji mode */
#define VK_HKTG 0x1A /* Hiragana/Katakana toggle */
#define VK_IME_OFF 0x1A
#define VK_ESCAPE 0x1B /* ESC key */
#define VK_CONVERT 0x1C /* IME convert */
#define VK_NONCONVERT 0x1D /* IME nonconvert */
#define VK_ACCEPT 0x1E /* IME accept */
#define VK_MODECHANGE 0x1F /* IME mode change request */
#define VK_SPACE 0x20 /* SPACEBAR */
#define VK_PRIOR 0x21 /* PAGE UP key */
#define VK_NEXT 0x22 /* PAGE DOWN key */
#define VK_END 0x23 /* END key */
#define VK_HOME 0x24 /* HOME key */
#define VK_LEFT 0x25 /* LEFT ARROW key */
#define VK_UP 0x26 /* UP ARROW key */
#define VK_RIGHT 0x27 /* RIGHT ARROW key */
#define VK_DOWN 0x28 /* DOWN ARROW key */
#define VK_SELECT 0x29 /* SELECT key */
#define VK_PRINT 0x2A /* PRINT key */
#define VK_EXECUTE 0x2B /* EXECUTE key */
#define VK_SNAPSHOT 0x2C /* PRINT SCREEN key */
#define VK_INSERT 0x2D /* INS key */
#define VK_DELETE 0x2E /* DEL key */
#define VK_HELP 0x2F /* HELP key */
/* Digits, the last 4 bits of the code represent the corresponding digit */
#define VK_KEY_0 0x30 /* '0' key */
#define VK_KEY_1 0x31 /* '1' key */
#define VK_KEY_2 0x32 /* '2' key */
#define VK_KEY_3 0x33 /* '3' key */
#define VK_KEY_4 0x34 /* '4' key */
#define VK_KEY_5 0x35 /* '5' key */
#define VK_KEY_6 0x36 /* '6' key */
#define VK_KEY_7 0x37 /* '7' key */
#define VK_KEY_8 0x38 /* '8' key */
#define VK_KEY_9 0x39 /* '9' key */
/* 0x3A to 0x40 are undefined */
/* The alphabet, the code corresponds to the capitalized letter in the ASCII code */
#define VK_KEY_A 0x41 /* 'A' key */
#define VK_KEY_B 0x42 /* 'B' key */
#define VK_KEY_C 0x43 /* 'C' key */
#define VK_KEY_D 0x44 /* 'D' key */
#define VK_KEY_E 0x45 /* 'E' key */
#define VK_KEY_F 0x46 /* 'F' key */
#define VK_KEY_G 0x47 /* 'G' key */
#define VK_KEY_H 0x48 /* 'H' key */
#define VK_KEY_I 0x49 /* 'I' key */
#define VK_KEY_J 0x4A /* 'J' key */
#define VK_KEY_K 0x4B /* 'K' key */
#define VK_KEY_L 0x4C /* 'L' key */
#define VK_KEY_M 0x4D /* 'M' key */
#define VK_KEY_N 0x4E /* 'N' key */
#define VK_KEY_O 0x4F /* 'O' key */
#define VK_KEY_P 0x50 /* 'P' key */
#define VK_KEY_Q 0x51 /* 'Q' key */
#define VK_KEY_R 0x52 /* 'R' key */
#define VK_KEY_S 0x53 /* 'S' key */
#define VK_KEY_T 0x54 /* 'T' key */
#define VK_KEY_U 0x55 /* 'U' key */
#define VK_KEY_V 0x56 /* 'V' key */
#define VK_KEY_W 0x57 /* 'W' key */
#define VK_KEY_X 0x58 /* 'X' key */
#define VK_KEY_Y 0x59 /* 'Y' key */
#define VK_KEY_Z 0x5A /* 'Z' key */
#define VK_LWIN 0x5B /* Left Windows key (Microsoft Natural keyboard) */
#define VK_RWIN 0x5C /* Right Windows key (Natural keyboard) */
#define VK_APPS 0x5D /* Applications key (Natural keyboard) */
/* 0x5E is reserved */
#define VK_POWER 0x5E /* Power key */
#define VK_SLEEP 0x5F /* Computer Sleep key */
/* Numeric keypad digits, the last four bits of the code represent the corresponding digit */
#define VK_NUMPAD0 0x60 /* Numeric keypad '0' key */
#define VK_NUMPAD1 0x61 /* Numeric keypad '1' key */
#define VK_NUMPAD2 0x62 /* Numeric keypad '2' key */
#define VK_NUMPAD3 0x63 /* Numeric keypad '3' key */
#define VK_NUMPAD4 0x64 /* Numeric keypad '4' key */
#define VK_NUMPAD5 0x65 /* Numeric keypad '5' key */
#define VK_NUMPAD6 0x66 /* Numeric keypad '6' key */
#define VK_NUMPAD7 0x67 /* Numeric keypad '7' key */
#define VK_NUMPAD8 0x68 /* Numeric keypad '8' key */
#define VK_NUMPAD9 0x69 /* Numeric keypad '9' key */
/* Numeric keypad operators and special keys */
#define VK_MULTIPLY 0x6A /* Multiply key */
#define VK_ADD 0x6B /* Add key */
#define VK_SEPARATOR 0x6C /* Separator key */
#define VK_SUBTRACT 0x6D /* Subtract key */
#define VK_DECIMAL 0x6E /* Decimal key */
#define VK_DIVIDE 0x6F /* Divide key */
/* Function keys, from F1 to F24 */
#define VK_F1 0x70 /* F1 key */
#define VK_F2 0x71 /* F2 key */
#define VK_F3 0x72 /* F3 key */
#define VK_F4 0x73 /* F4 key */
#define VK_F5 0x74 /* F5 key */
#define VK_F6 0x75 /* F6 key */
#define VK_F7 0x76 /* F7 key */
#define VK_F8 0x77 /* F8 key */
#define VK_F9 0x78 /* F9 key */
#define VK_F10 0x79 /* F10 key */
#define VK_F11 0x7A /* F11 key */
#define VK_F12 0x7B /* F12 key */
#define VK_F13 0x7C /* F13 key */
#define VK_F14 0x7D /* F14 key */
#define VK_F15 0x7E /* F15 key */
#define VK_F16 0x7F /* F16 key */
#define VK_F17 0x80 /* F17 key */
#define VK_F18 0x81 /* F18 key */
#define VK_F19 0x82 /* F19 key */
#define VK_F20 0x83 /* F20 key */
#define VK_F21 0x84 /* F21 key */
#define VK_F22 0x85 /* F22 key */
#define VK_F23 0x86 /* F23 key */
#define VK_F24 0x87 /* F24 key */
/* 0x88 to 0x8F are unassigned */
#define VK_NUMLOCK 0x90 /* NUM LOCK key */
#define VK_SCROLL 0x91 /* SCROLL LOCK key */
/* 0x92 to 0x96 are OEM specific */
/* 0x97 to 0x9F are unassigned */
/* Modifier keys */
#define VK_LSHIFT 0xA0 /* Left SHIFT key */
#define VK_RSHIFT 0xA1 /* Right SHIFT key */
#define VK_LCONTROL 0xA2 /* Left CONTROL key */
#define VK_RCONTROL 0xA3 /* Right CONTROL key */
#define VK_LMENU 0xA4 /* Left MENU key */
#define VK_RMENU 0xA5 /* Right MENU key */
/* Browser related keys */
#define VK_BROWSER_BACK 0xA6 /* Windows 2000/XP: Browser Back key */
#define VK_BROWSER_FORWARD 0xA7 /* Windows 2000/XP: Browser Forward key */
#define VK_BROWSER_REFRESH 0xA8 /* Windows 2000/XP: Browser Refresh key */
#define VK_BROWSER_STOP 0xA9 /* Windows 2000/XP: Browser Stop key */
#define VK_BROWSER_SEARCH 0xAA /* Windows 2000/XP: Browser Search key */
#define VK_BROWSER_FAVORITES 0xAB /* Windows 2000/XP: Browser Favorites key */
#define VK_BROWSER_HOME 0xAC /* Windows 2000/XP: Browser Start and Home key */
/* Volume related keys */
#define VK_VOLUME_MUTE 0xAD /* Windows 2000/XP: Volume Mute key */
#define VK_VOLUME_DOWN 0xAE /* Windows 2000/XP: Volume Down key */
#define VK_VOLUME_UP 0xAF /* Windows 2000/XP: Volume Up key */
/* Media player related keys */
#define VK_MEDIA_NEXT_TRACK 0xB0 /* Windows 2000/XP: Next Track key */
#define VK_MEDIA_PREV_TRACK 0xB1 /* Windows 2000/XP: Previous Track key */
#define VK_MEDIA_STOP 0xB2 /* Windows 2000/XP: Stop Media key */
#define VK_MEDIA_PLAY_PAUSE 0xB3 /* Windows 2000/XP: Play/Pause Media key */
/* Application launcher keys */
#define VK_LAUNCH_MAIL 0xB4 /* Windows 2000/XP: Start Mail key */
#define VK_MEDIA_SELECT 0xB5 /* Windows 2000/XP: Select Media key */
#define VK_LAUNCH_MEDIA_SELECT 0xB5 /* Windows 2000/XP: Select Media key */
#define VK_LAUNCH_APP1 0xB6 /* Windows 2000/XP: Start Application 1 key */
#define VK_LAUNCH_APP2 0xB7 /* Windows 2000/XP: Start Application 2 key */
/* 0xB8 and 0xB9 are reserved */
/* OEM keys */
#define VK_OEM_1 0xBA /* Used for miscellaneous characters; it can vary by keyboard. */
/* Windows 2000/XP: For the US standard keyboard, the ';:' key */
#define VK_OEM_PLUS 0xBB /* Windows 2000/XP: For any country/region, the '+' key */
#define VK_OEM_COMMA 0xBC /* Windows 2000/XP: For any country/region, the ',' key */
#define VK_OEM_MINUS 0xBD /* Windows 2000/XP: For any country/region, the '-' key */
#define VK_OEM_PERIOD 0xBE /* Windows 2000/XP: For any country/region, the '.' key */
#define VK_OEM_2 0xBF /* Used for miscellaneous characters; it can vary by keyboard. */
/* Windows 2000/XP: For the US standard keyboard, the '/?' key */
#define VK_OEM_3 0xC0 /* Used for miscellaneous characters; it can vary by keyboard. */
/* Windows 2000/XP: For the US standard keyboard, the '`~' key */
/* 0xC1 to 0xD7 are reserved */
#define VK_ABNT_C1 0xC1 /* Brazilian (ABNT) Keyboard */
#define VK_ABNT_C2 0xC2 /* Brazilian (ABNT) Keyboard */
/* 0xD8 to 0xDA are unassigned */
#define VK_OEM_4 0xDB /* Used for miscellaneous characters; it can vary by keyboard. */
/* Windows 2000/XP: For the US standard keyboard, the '[{' key */
#define VK_OEM_5 0xDC /* Used for miscellaneous characters; it can vary by keyboard. */
/* Windows 2000/XP: For the US standard keyboard, the '\|' key */
#define VK_OEM_6 0xDD /* Used for miscellaneous characters; it can vary by keyboard. */
/* Windows 2000/XP: For the US standard keyboard, the ']}' key */
#define VK_OEM_7 0xDE /* Used for miscellaneous characters; it can vary by keyboard. */
/* Windows 2000/XP: For the US standard keyboard, the 'single-quote/double-quote' key */
#define VK_OEM_8 0xDF /* Used for miscellaneous characters; it can vary by keyboard. */
/* 0xE0 is reserved */
#define VK_OEM_AX 0xE1 /* AX key on Japanese AX keyboard */
#define VK_OEM_102 0xE2 /* Windows 2000/XP: Either the angle bracket key or */
/* the backslash key on the RT 102-key keyboard */
/* 0xE3 and 0xE4 are OEM specific */
#define VK_PROCESSKEY \
0xE5 /* Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key \
*/
/* 0xE6 is OEM specific */
#define VK_PACKET \
0xE7 /* Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. */
/* The #define VK_PACKET key is the low word of a 32-bit Virtual Key value used */
/* for non-keyboard input methods. For more information, */
/* see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KEYUP */
/* 0xE8 is unassigned */
/* 0xE9 to 0xF5 are OEM specific */
#define VK_OEM_RESET 0xE9
#define VK_OEM_JUMP 0xEA
#define VK_OEM_PA1 0xEB
#define VK_OEM_PA2 0xEC
#define VK_OEM_PA3 0xED
#define VK_OEM_WSCTRL 0xEE
#define VK_OEM_CUSEL 0xEF
#define VK_OEM_ATTN 0xF0
#define VK_OEM_FINISH 0xF1
#define VK_OEM_COPY 0xF2
#define VK_OEM_AUTO 0xF3
#define VK_OEM_ENLW 0xF4
#define VK_OEM_BACKTAB 0xF5
#define VK_ATTN 0xF6 /* Attn key */
#define VK_CRSEL 0xF7 /* CrSel key */
#define VK_EXSEL 0xF8 /* ExSel key */
#define VK_EREOF 0xF9 /* Erase EOF key */
#define VK_PLAY 0xFA /* Play key */
#define VK_ZOOM 0xFB /* Zoom key */
#define VK_NONAME 0xFC /* Reserved */
#define VK_PA1 0xFD /* PA1 key */
#define VK_OEM_CLEAR 0xFE /* Clear key */
#define VK_NONE 0xFF /* no key */
/**
* For East Asian Input Method Editors (IMEs)
* the following additional virtual keyboard definitions must be observed.
*/
#define VK_DBE_ALPHANUMERIC 0xF0 /* Changes the mode to alphanumeric. */
#define VK_DBE_KATAKANA 0xF1 /* Changes the mode to Katakana. */
#define VK_DBE_HIRAGANA 0xF2 /* Changes the mode to Hiragana. */
#define VK_DBE_SBCSCHAR 0xF3 /* Changes the mode to single-byte characters. */
#define VK_DBE_DBCSCHAR 0xF4 /* Changes the mode to double-byte characters. */
#define VK_DBE_ROMAN 0xF5 /* Changes the mode to Roman characters. */
#define VK_DBE_NOROMAN 0xF6 /* Changes the mode to non-Roman characters. */
#define VK_DBE_ENTERWORDREGISTERMODE 0xF7 /* Activates the word registration dialog box. */
#define VK_DBE_ENTERIMECONFIGMODE \
0xF8 /* Activates a dialog box for setting up an IME environment. */
#define VK_DBE_FLUSHSTRING 0xF9 /* Deletes the undetermined string without determining it. */
#define VK_DBE_CODEINPUT 0xFA /* Changes the mode to code input. */
#define VK_DBE_NOCODEINPUT 0xFB /* Changes the mode to no-code input. */
/*
* Virtual Scan Codes
*/
/**
* Keyboard Type 4
*/
#define KBD4_T00 VK_NONE
#define KBD4_T01 VK_ESCAPE
#define KBD4_T02 VK_KEY_1
#define KBD4_T03 VK_KEY_2
#define KBD4_T04 VK_KEY_3
#define KBD4_T05 VK_KEY_4
#define KBD4_T06 VK_KEY_5
#define KBD4_T07 VK_KEY_6
#define KBD4_T08 VK_KEY_7
#define KBD4_T09 VK_KEY_8
#define KBD4_T0A VK_KEY_9
#define KBD4_T0B VK_KEY_0
#define KBD4_T0C VK_OEM_MINUS
#define KBD4_T0D VK_OEM_PLUS /* NE */
#define KBD4_T0E VK_BACK
#define KBD4_T0F VK_TAB
#define KBD4_T10 VK_KEY_Q
#define KBD4_T11 VK_KEY_W
#define KBD4_T12 VK_KEY_E
#define KBD4_T13 VK_KEY_R
#define KBD4_T14 VK_KEY_T
#define KBD4_T15 VK_KEY_Y
#define KBD4_T16 VK_KEY_U
#define KBD4_T17 VK_KEY_I
#define KBD4_T18 VK_KEY_O
#define KBD4_T19 VK_KEY_P
#define KBD4_T1A VK_OEM_4 /* NE */
#define KBD4_T1B VK_OEM_6 /* NE */
#define KBD4_T1C VK_RETURN
#define KBD4_T1D VK_LCONTROL
#define KBD4_T1E VK_KEY_A
#define KBD4_T1F VK_KEY_S
#define KBD4_T20 VK_KEY_D
#define KBD4_T21 VK_KEY_F
#define KBD4_T22 VK_KEY_G
#define KBD4_T23 VK_KEY_H
#define KBD4_T24 VK_KEY_J
#define KBD4_T25 VK_KEY_K
#define KBD4_T26 VK_KEY_L
#define KBD4_T27 VK_OEM_1 /* NE */
#define KBD4_T28 VK_OEM_7 /* NE */
#define KBD4_T29 VK_OEM_3 /* NE */
#define KBD4_T2A VK_LSHIFT
#define KBD4_T2B VK_OEM_5
#define KBD4_T2C VK_KEY_Z
#define KBD4_T2D VK_KEY_X
#define KBD4_T2E VK_KEY_C
#define KBD4_T2F VK_KEY_V
#define KBD4_T30 VK_KEY_B
#define KBD4_T31 VK_KEY_N
#define KBD4_T32 VK_KEY_M
#define KBD4_T33 VK_OEM_COMMA
#define KBD4_T34 VK_OEM_PERIOD
#define KBD4_T35 VK_OEM_2
#define KBD4_T36 VK_RSHIFT
#define KBD4_T37 VK_MULTIPLY
#define KBD4_T38 VK_LMENU
#define KBD4_T39 VK_SPACE
#define KBD4_T3A VK_CAPITAL
#define KBD4_T3B VK_F1
#define KBD4_T3C VK_F2
#define KBD4_T3D VK_F3
#define KBD4_T3E VK_F4
#define KBD4_T3F VK_F5
#define KBD4_T40 VK_F6
#define KBD4_T41 VK_F7
#define KBD4_T42 VK_F8
#define KBD4_T43 VK_F9
#define KBD4_T44 VK_F10
#define KBD4_T45 VK_NUMLOCK
#define KBD4_T46 VK_SCROLL
#define KBD4_T47 VK_NUMPAD7 /* VK_HOME */
#define KBD4_T48 VK_NUMPAD8 /* VK_UP */
#define KBD4_T49 VK_NUMPAD9 /* VK_PRIOR */
#define KBD4_T4A VK_SUBTRACT
#define KBD4_T4B VK_NUMPAD4 /* VK_LEFT */
#define KBD4_T4C VK_NUMPAD5 /* VK_CLEAR */
#define KBD4_T4D VK_NUMPAD6 /* VK_RIGHT */
#define KBD4_T4E VK_ADD
#define KBD4_T4F VK_NUMPAD1 /* VK_END */
#define KBD4_T50 VK_NUMPAD2 /* VK_DOWN */
#define KBD4_T51 VK_NUMPAD3 /* VK_NEXT */
#define KBD4_T52 VK_NUMPAD0 /* VK_INSERT */
#define KBD4_T53 VK_DECIMAL /* VK_DELETE */
#define KBD4_T54 VK_SNAPSHOT
#define KBD4_T55 VK_NONE
#define KBD4_T56 VK_OEM_102 /* NE */
#define KBD4_T57 VK_F11 /* NE */
#define KBD4_T58 VK_F12 /* NE */
#define KBD4_T59 VK_CLEAR
#define KBD4_T5A VK_OEM_WSCTRL
#define KBD4_T5B VK_OEM_FINISH
#define KBD4_T5C VK_OEM_JUMP
#define KBD4_T5D VK_EREOF
#define KBD4_T5E VK_OEM_BACKTAB
#define KBD4_T5F VK_OEM_AUTO
#define KBD4_T60 VK_NONE
#define KBD4_T61 VK_NONE
#define KBD4_T62 VK_ZOOM
#define KBD4_T63 VK_HELP
#define KBD4_T64 VK_F13
#define KBD4_T65 VK_F14
#define KBD4_T66 VK_F15
#define KBD4_T67 VK_F16
#define KBD4_T68 VK_F17
#define KBD4_T69 VK_F18
#define KBD4_T6A VK_F19
#define KBD4_T6B VK_F20
#define KBD4_T6C VK_F21
#define KBD4_T6D VK_F22
#define KBD4_T6E VK_F23
#define KBD4_T6F VK_OEM_PA3
#define KBD4_T70 VK_NONE
#define KBD4_T71 VK_OEM_RESET
#define KBD4_T72 VK_NONE
#define KBD4_T73 VK_ABNT_C1
#define KBD4_T74 VK_NONE
#define KBD4_T75 VK_NONE
#define KBD4_T76 VK_F24
#define KBD4_T77 VK_NONE
#define KBD4_T78 VK_NONE
#define KBD4_T79 VK_NONE
#define KBD4_T7A VK_NONE
#define KBD4_T7B VK_OEM_PA1
#define KBD4_T7C VK_TAB
#define KBD4_T7D VK_NONE
#define KBD4_T7E VK_ABNT_C2
#define KBD4_T7F VK_OEM_PA2
#define KBD4_X10 VK_MEDIA_PREV_TRACK
#define KBD4_X19 VK_MEDIA_NEXT_TRACK
#define KBD4_X1C VK_RETURN
#define KBD4_X1D VK_RCONTROL
#define KBD4_X20 VK_VOLUME_MUTE
#define KBD4_X21 VK_LAUNCH_APP2
#define KBD4_X22 VK_MEDIA_PLAY_PAUSE
#define KBD4_X24 VK_MEDIA_STOP
#define KBD4_X2E VK_VOLUME_DOWN
#define KBD4_X30 VK_VOLUME_UP
#define KBD4_X32 VK_BROWSER_HOME
#define KBD4_X35 VK_DIVIDE
#define KBD4_X37 VK_SNAPSHOT
#define KBD4_X38 VK_RMENU
#define KBD4_X46 VK_PAUSE /* VK_CANCEL */
#define KBD4_X47 VK_HOME
#define KBD4_X48 VK_UP
#define KBD4_X49 VK_PRIOR
#define KBD4_X4B VK_LEFT
#define KBD4_X4D VK_RIGHT
#define KBD4_X4F VK_END
#define KBD4_X50 VK_DOWN
#define KBD4_X51 VK_NEXT /* NE */
#define KBD4_X52 VK_INSERT
#define KBD4_X53 VK_DELETE
#define KBD4_X5B VK_LWIN
#define KBD4_X5C VK_RWIN
#define KBD4_X5D VK_APPS
#define KBD4_X5E VK_POWER
#define KBD4_X5F VK_SLEEP
#define KBD4_X65 VK_BROWSER_SEARCH
#define KBD4_X66 VK_BROWSER_FAVORITES
#define KBD4_X67 VK_BROWSER_REFRESH
#define KBD4_X68 VK_BROWSER_STOP
#define KBD4_X69 VK_BROWSER_FORWARD
#define KBD4_X6A VK_BROWSER_BACK
#define KBD4_X6B VK_LAUNCH_APP1
#define KBD4_X6C VK_LAUNCH_MAIL
#define KBD4_X6D VK_LAUNCH_MEDIA_SELECT
#define KBD4_Y1D VK_PAUSE
/**
* Keyboard Type 7
*
* https://kbdlayout.info/kbdjpn/virtualkeys
*/
#define KBD7_T00 VK_NONE
#define KBD7_T01 VK_ESCAPE
#define KBD7_T02 VK_KEY_1
#define KBD7_T03 VK_KEY_2
#define KBD7_T04 VK_KEY_3
#define KBD7_T05 VK_KEY_4
#define KBD7_T06 VK_KEY_5
#define KBD7_T07 VK_KEY_6
#define KBD7_T08 VK_KEY_7
#define KBD7_T09 VK_KEY_8
#define KBD7_T0A VK_KEY_9
#define KBD7_T0B VK_KEY_0
#define KBD7_T0C VK_OEM_MINUS
#define KBD7_T0D VK_OEM_PLUS
#define KBD7_T0E VK_BACK
#define KBD7_T0F VK_TAB
#define KBD7_T10 VK_KEY_Q
#define KBD7_T11 VK_KEY_W
#define KBD7_T12 VK_KEY_E
#define KBD7_T13 VK_KEY_R
#define KBD7_T14 VK_KEY_T
#define KBD7_T15 VK_KEY_Y
#define KBD7_T16 VK_KEY_U
#define KBD7_T17 VK_KEY_I
#define KBD7_T18 VK_KEY_O
#define KBD7_T19 VK_KEY_P
#define KBD7_T1A VK_OEM_4
#define KBD7_T1B VK_OEM_6
#define KBD7_T1C VK_RETURN
#define KBD7_T1D VK_LCONTROL
#define KBD7_T1E VK_KEY_A
#define KBD7_T1F VK_KEY_S
#define KBD7_T20 VK_KEY_D
#define KBD7_T21 VK_KEY_F
#define KBD7_T22 VK_KEY_G
#define KBD7_T23 VK_KEY_H
#define KBD7_T24 VK_KEY_J
#define KBD7_T25 VK_KEY_K
#define KBD7_T26 VK_KEY_L
#define KBD7_T27 VK_OEM_1
#define KBD7_T28 VK_OEM_7
#define KBD7_T29 VK_OEM_3
#define KBD7_T2A VK_LSHIFT
#define KBD7_T2B VK_OEM_5
#define KBD7_T2C VK_KEY_Z
#define KBD7_T2D VK_KEY_X
#define KBD7_T2E VK_KEY_C
#define KBD7_T2F VK_KEY_V
#define KBD7_T30 VK_KEY_B
#define KBD7_T31 VK_KEY_N
#define KBD7_T32 VK_KEY_M
#define KBD7_T33 VK_OEM_COMMA
#define KBD7_T34 VK_OEM_PERIOD
#define KBD7_T35 VK_OEM_2
#define KBD7_T36 VK_RSHIFT
#define KBD7_T37 VK_MULTIPLY
#define KBD7_T38 VK_LMENU
#define KBD7_T39 VK_SPACE
#define KBD7_T3A VK_CAPITAL
#define KBD7_T3B VK_F1
#define KBD7_T3C VK_F2
#define KBD7_T3D VK_F3
#define KBD7_T3E VK_F4
#define KBD7_T3F VK_F5
#define KBD7_T40 VK_F6
#define KBD7_T41 VK_F7
#define KBD7_T42 VK_F8
#define KBD7_T43 VK_F9
#define KBD7_T44 VK_F10
#define KBD7_T45 VK_NUMLOCK
#define KBD7_T46 VK_SCROLL
#define KBD7_T47 VK_HOME
#define KBD7_T48 VK_UP
#define KBD7_T49 VK_PRIOR
#define KBD7_T4A VK_SUBTRACT
#define KBD7_T4B VK_LEFT
#define KBD7_T4C VK_CLEAR
#define KBD7_T4D VK_RIGHT
#define KBD7_T4E VK_ADD
#define KBD7_T4F VK_END
#define KBD7_T50 VK_DOWN
#define KBD7_T51 VK_NEXT
#define KBD7_T52 VK_INSERT
#define KBD7_T53 VK_DELETE
#define KBD7_T54 VK_SNAPSHOT
#define KBD7_T55 VK_NONE
#define KBD7_T56 VK_OEM_102
#define KBD7_T57 VK_F11
#define KBD7_T58 VK_F12
#define KBD7_T59 VK_CLEAR
#define KBD7_T5A VK_OEM_WSCTRL
#define KBD7_T5B VK_DBE_KATAKANA
#define KBD7_T5C VK_OEM_JUMP
#define KBD7_T5D VK_DBE_FLUSHSTRING
#define KBD7_T5E VK_OEM_BACKTAB
#define KBD7_T5F VK_OEM_AUTO
#define KBD7_T60 VK_NONE
#define KBD7_T61 VK_NONE
#define KBD7_T62 VK_DBE_NOCODEINPUT
#define KBD7_T63 VK_HELP
#define KBD7_T64 VK_F13
#define KBD7_T65 VK_F14
#define KBD7_T66 VK_F15
#define KBD7_T67 VK_F16
#define KBD7_T68 VK_F17
#define KBD7_T69 VK_F18
#define KBD7_T6A VK_F19
#define KBD7_T6B VK_F20
#define KBD7_T6C VK_F21
#define KBD7_T6D VK_F22
#define KBD7_T6E VK_F23
#define KBD7_T6F VK_OEM_PA3
#define KBD7_T70 VK_NONE
#define KBD7_T71 VK_OEM_RESET
#define KBD7_T72 VK_NONE
#define KBD7_T73 VK_ABNT_C1
#define KBD7_T74 VK_NONE
#define KBD7_T75 VK_NONE
#define KBD7_T76 VK_F24
#define KBD7_T77 VK_NONE
#define KBD7_T78 VK_NONE
#define KBD7_T79 VK_NONE
#define KBD7_T7A VK_NONE
#define KBD7_T7B VK_OEM_PA1
#define KBD7_T7C VK_TAB
#define KBD7_T7D VK_NONE
#define KBD7_T7E VK_ABNT_C2
#define KBD7_T7F VK_OEM_PA2
#define KBD7_X10 VK_MEDIA_PREV_TRACK
#define KBD7_X19 VK_MEDIA_NEXT_TRACK
#define KBD7_X1C VK_RETURN
#define KBD7_X1D VK_RCONTROL
#define KBD7_X20 VK_VOLUME_MUTE
#define KBD7_X21 VK_LAUNCH_APP2
#define KBD7_X22 VK_MEDIA_PLAY_PAUSE
#define KBD7_X24 VK_MEDIA_STOP
#define KBD7_X2E VK_VOLUME_DOWN
#define KBD7_X30 VK_VOLUME_UP
#define KBD7_X32 VK_BROWSER_HOME
#define KBD7_X33 VK_NONE
#define KBD7_X35 VK_DIVIDE
#define KBD7_X37 VK_SNAPSHOT
#define KBD7_X38 VK_RMENU
#define KBD7_X42 VK_NONE
#define KBD7_X43 VK_NONE
#define KBD7_X44 VK_NONE
#define KBD7_X46 VK_CANCEL
#define KBD7_X47 VK_HOME
#define KBD7_X48 VK_UP
#define KBD7_X49 VK_PRIOR
#define KBD7_X4B VK_LEFT
#define KBD7_X4D VK_RIGHT
#define KBD7_X4F VK_END
#define KBD7_X50 VK_DOWN
#define KBD7_X51 VK_NEXT
#define KBD7_X52 VK_INSERT
#define KBD7_X53 VK_DELETE
#define KBD7_X5B VK_LWIN
#define KBD7_X5C VK_RWIN
#define KBD7_X5D VK_APPS
#define KBD7_X5E VK_NONE
#define KBD7_X5F VK_SLEEP
#define KBD7_X65 VK_BROWSER_SEARCH
#define KBD7_X66 VK_BROWSER_FAVORITES
#define KBD7_X67 VK_BROWSER_REFRESH
#define KBD7_X68 VK_BROWSER_STOP
#define KBD7_X69 VK_BROWSER_FORWARD
#define KBD7_X6A VK_BROWSER_BACK
#define KBD7_X6B VK_LAUNCH_APP1
#define KBD7_X6C VK_LAUNCH_MAIL
#define KBD7_X6D VK_LAUNCH_MEDIA_SELECT
#define KBD7_XF1 VK_IME_OFF
#define KBD7_XF2 VK_IME_ON
/**
* X11 Keycodes
*/
/**
* Mac OS X
*/
#define APPLE_VK_ANSI_A 0x00
#define APPLE_VK_ANSI_S 0x01
#define APPLE_VK_ANSI_D 0x02
#define APPLE_VK_ANSI_F 0x03
#define APPLE_VK_ANSI_H 0x04
#define APPLE_VK_ANSI_G 0x05
#define APPLE_VK_ANSI_Z 0x06
#define APPLE_VK_ANSI_X 0x07
#define APPLE_VK_ANSI_C 0x08
#define APPLE_VK_ANSI_V 0x09
#define APPLE_VK_ISO_Section 0x0A
#define APPLE_VK_ANSI_B 0x0B
#define APPLE_VK_ANSI_Q 0x0C
#define APPLE_VK_ANSI_W 0x0D
#define APPLE_VK_ANSI_E 0x0E
#define APPLE_VK_ANSI_R 0x0F
#define APPLE_VK_ANSI_Y 0x10
#define APPLE_VK_ANSI_T 0x11
#define APPLE_VK_ANSI_1 0x12
#define APPLE_VK_ANSI_2 0x13
#define APPLE_VK_ANSI_3 0x14
#define APPLE_VK_ANSI_4 0x15
#define APPLE_VK_ANSI_6 0x16
#define APPLE_VK_ANSI_5 0x17
#define APPLE_VK_ANSI_Equal 0x18
#define APPLE_VK_ANSI_9 0x19
#define APPLE_VK_ANSI_7 0x1A
#define APPLE_VK_ANSI_Minus 0x1B
#define APPLE_VK_ANSI_8 0x1C
#define APPLE_VK_ANSI_0 0x1D
#define APPLE_VK_ANSI_RightBracket 0x1E
#define APPLE_VK_ANSI_O 0x1F
#define APPLE_VK_ANSI_U 0x20
#define APPLE_VK_ANSI_LeftBracket 0x21
#define APPLE_VK_ANSI_I 0x22
#define APPLE_VK_ANSI_P 0x23
#define APPLE_VK_Return 0x24
#define APPLE_VK_ANSI_L 0x25
#define APPLE_VK_ANSI_J 0x26
#define APPLE_VK_ANSI_Quote 0x27
#define APPLE_VK_ANSI_K 0x28
#define APPLE_VK_ANSI_Semicolon 0x29
#define APPLE_VK_ANSI_Backslash 0x2A
#define APPLE_VK_ANSI_Comma 0x2B
#define APPLE_VK_ANSI_Slash 0x2C
#define APPLE_VK_ANSI_N 0x2D
#define APPLE_VK_ANSI_M 0x2E
#define APPLE_VK_ANSI_Period 0x2F
#define APPLE_VK_Tab 0x30
#define APPLE_VK_Space 0x31
#define APPLE_VK_ANSI_Grave 0x32
#define APPLE_VK_Delete 0x33
#define APPLE_VK_0x34 0x34
#define APPLE_VK_Escape 0x35
#define APPLE_VK_0x36 0x36
#define APPLE_VK_Command 0x37
#define APPLE_VK_Shift 0x38
#define APPLE_VK_CapsLock 0x39
#define APPLE_VK_Option 0x3A
#define APPLE_VK_Control 0x3B
#define APPLE_VK_RightShift 0x3C
#define APPLE_VK_RightOption 0x3D
#define APPLE_VK_RightControl 0x3E
#define APPLE_VK_Function 0x3F
#define APPLE_VK_F17 0x40
#define APPLE_VK_ANSI_KeypadDecimal 0x41
#define APPLE_VK_0x42 0x42
#define APPLE_VK_ANSI_KeypadMultiply 0x43
#define APPLE_VK_0x44 0x44
#define APPLE_VK_ANSI_KeypadPlus 0x45
#define APPLE_VK_0x46 0x46
#define APPLE_VK_ANSI_KeypadClear 0x47
#define APPLE_VK_VolumeUp 0x48
#define APPLE_VK_VolumeDown 0x49
#define APPLE_VK_Mute 0x4A
#define APPLE_VK_ANSI_KeypadDivide 0x4B
#define APPLE_VK_ANSI_KeypadEnter 0x4C
#define APPLE_VK_0x4D 0x4D
#define APPLE_VK_ANSI_KeypadMinus 0x4E
#define APPLE_VK_F18 0x4F
#define APPLE_VK_F19 0x50
#define APPLE_VK_ANSI_KeypadEquals 0x51
#define APPLE_VK_ANSI_Keypad0 0x52
#define APPLE_VK_ANSI_Keypad1 0x53
#define APPLE_VK_ANSI_Keypad2 0x54
#define APPLE_VK_ANSI_Keypad3 0x55
#define APPLE_VK_ANSI_Keypad4 0x56
#define APPLE_VK_ANSI_Keypad5 0x57
#define APPLE_VK_ANSI_Keypad6 0x58
#define APPLE_VK_ANSI_Keypad7 0x59
#define APPLE_VK_F20 0x5A
#define APPLE_VK_ANSI_Keypad8 0x5B
#define APPLE_VK_ANSI_Keypad9 0x5C
#define APPLE_VK_JIS_Yen 0x5D
#define APPLE_VK_JIS_Underscore 0x5E
#define APPLE_VK_JIS_KeypadComma 0x5F
#define APPLE_VK_F5 0x60
#define APPLE_VK_F6 0x61
#define APPLE_VK_F7 0x62
#define APPLE_VK_F3 0x63
#define APPLE_VK_F8 0x64
#define APPLE_VK_F9 0x65
#define APPLE_VK_JIS_Eisu 0x66
#define APPLE_VK_F11 0x67
#define APPLE_VK_JIS_Kana 0x68
#define APPLE_VK_F13 0x69
#define APPLE_VK_F16 0x6A
#define APPLE_VK_F14 0x6B
#define APPLE_VK_F10 0x6D
#define APPLE_VK_0x6C 0x6C
#define APPLE_VK_0x6E 0x6E
#define APPLE_VK_F12 0x6F
#define APPLE_VK_0x70 0x70
#define APPLE_VK_F15 0x71
#define APPLE_VK_Help 0x72
#define APPLE_VK_Home 0x73
#define APPLE_VK_PageUp 0x74
#define APPLE_VK_ForwardDelete 0x75
#define APPLE_VK_F4 0x76
#define APPLE_VK_End 0x77
#define APPLE_VK_F2 0x78
#define APPLE_VK_PageDown 0x79
#define APPLE_VK_F1 0x7A
#define APPLE_VK_LeftArrow 0x7B
#define APPLE_VK_RightArrow 0x7C
#define APPLE_VK_DownArrow 0x7D
#define APPLE_VK_UpArrow 0x7E
#ifdef __cplusplus
extern "C"
{
#endif
/* [MS-RDPBCGR] 2.2.1.3.2 Client Core Data (TS_UD_CS_CORE) KeyboardType */
enum WINPR_KBD_TYPE
{
WINPR_KBD_TYPE_IBM_PC_XT = 0x00000001, /* IBM PC/XT or compatible (83-key) keyboard */
WINPR_KBD_TYPE_OLIVETTI_ICO = 0x00000002, /* Olivetti "ICO" (102-key) keyboard */
WINPR_KBD_TYPE_IBM_PC_AT = 0x00000003, /* IBM PC/AT (84-key) and similar keyboards */
WINPR_KBD_TYPE_IBM_ENHANCED = 0x00000004, /* IBM enhanced (101-key or 102-key) keyboard */
WINPR_KBD_TYPE_NOKIA_1050 = 0x00000005, /* Nokia 1050 and similar keyboards */
WINPR_KBD_TYPE_NOKIA_9140 = 0x00000006, /* Nokia 9140 and similar keyboards */
WINPR_KBD_TYPE_JAPANESE = 0x00000007, /* Japanese keyboard */
WINPR_KBD_TYPE_KOREAN = 0x00000008 /* Korean keyboard */
};
/**
* Functions
*/
WINPR_API const char* GetVirtualKeyName(DWORD vkcode);
WINPR_API DWORD GetVirtualKeyCodeFromName(const char* vkname);
WINPR_API DWORD GetVirtualKeyCodeFromXkbKeyName(const char* xkbname);
WINPR_API DWORD GetVirtualKeyCodeFromVirtualScanCode(DWORD scancode,
DWORD /* WINPR_KBD_TYPE */ dwKeyboardType);
WINPR_API DWORD GetVirtualScanCodeFromVirtualKeyCode(DWORD vkcode,
DWORD /* WINPR_KBD_TYPE */ dwKeyboardType);
typedef enum
{
WINPR_KEYCODE_TYPE_NONE = 0x00000000,
WINPR_KEYCODE_TYPE_APPLE = 0x00000001,
WINPR_KEYCODE_TYPE_EVDEV = 0x00000002,
WINPR_KEYCODE_TYPE_XKB = 0x00000003
} WINPR_KEYCODE_TYPE;
WINPR_API DWORD GetVirtualKeyCodeFromKeycode(DWORD keycode, WINPR_KEYCODE_TYPE type);
WINPR_API DWORD GetKeycodeFromVirtualKeyCode(DWORD keycode, WINPR_KEYCODE_TYPE type);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_INPUT_H */

View File

@@ -0,0 +1,216 @@
/**
* WinPR: Windows Portable Runtime
* Interlocked Singly-Linked Lists
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_INTERLOCKED_H
#define WINPR_INTERLOCKED_H
#include <winpr/spec.h>
#include <winpr/platform.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#ifdef __cplusplus
extern "C"
{
#endif
#ifndef _WIN32
#ifndef CONTAINING_RECORD
#define CONTAINING_RECORD(address, type, field) \
((type*)(((ULONG_PTR)address) - (ULONG_PTR)(&(((type*)0)->field))))
#endif
typedef struct S_WINPR_LIST_ENTRY WINPR_LIST_ENTRY;
typedef struct S_WINPR_LIST_ENTRY* WINPR_PLIST_ENTRY;
struct S_WINPR_LIST_ENTRY
{
WINPR_PLIST_ENTRY Flink;
WINPR_PLIST_ENTRY Blink;
};
typedef struct S_WINPR_SINGLE_LIST_ENTRY WINPR_SINGLE_LIST_ENTRY;
typedef struct S_WINPR_SINGLE_LIST_ENTRY* WINPR_PSINGLE_LIST_ENTRY;
struct S_WINPR_SINGLE_LIST_ENTRY
{
WINPR_PSINGLE_LIST_ENTRY Next;
};
typedef struct WINPR_LIST_ENTRY32
{
DWORD Flink;
DWORD Blink;
} WINPR_LIST_ENTRY32;
typedef WINPR_LIST_ENTRY32* WINPR_PLIST_ENTRY32;
typedef struct WINPR_LIST_ENTRY64
{
ULONGLONG Flink;
ULONGLONG Blink;
} WINPR_LIST_ENTRY64;
typedef WINPR_LIST_ENTRY64* WINPR_PLIST_ENTRY64;
#ifdef _WIN64
typedef struct S_WINPR_SLIST_ENTRY* WINPR_PSLIST_ENTRY;
typedef struct DECLSPEC_ALIGN(16) S_WINPR_SLIST_ENTRY
{
WINPR_PSLIST_ENTRY Next;
} WINPR_SLIST_ENTRY;
#else /* _WIN64 */
WINPR_PRAGMA_DIAG_PUSH
WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO
#define WINPR_SLIST_ENTRY WINPR_SINGLE_LIST_ENTRY
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _WINPR_SLIST_ENTRY _WINPR_SINGLE_LIST_ENTRY
#define WINPR_PSLIST_ENTRY WINPR_PSINGLE_LIST_ENTRY
WINPR_PRAGMA_DIAG_POP
#endif /* _WIN64 */
#ifdef _WIN64
typedef union DECLSPEC_ALIGN(16)
{
struct
{
ULONGLONG Alignment;
ULONGLONG Region;
} DUMMYSTRUCTNAME;
struct
{
ULONGLONG Depth : 16;
ULONGLONG Sequence : 9;
ULONGLONG NextEntry : 39;
ULONGLONG HeaderType : 1;
ULONGLONG Init : 1;
ULONGLONG Reserved : 59;
ULONGLONG Region : 3;
} Header8;
struct
{
ULONGLONG Depth : 16;
ULONGLONG Sequence : 48;
ULONGLONG HeaderType : 1;
ULONGLONG Reserved : 3;
ULONGLONG NextEntry : 60;
} HeaderX64;
} WINPR_SLIST_HEADER, *WINPR_PSLIST_HEADER;
#else /* _WIN64 */
typedef union
{
ULONGLONG Alignment;
struct
{
WINPR_SLIST_ENTRY Next;
WORD Depth;
WORD Sequence;
} DUMMYSTRUCTNAME;
} WINPR_SLIST_HEADER, *WINPR_PSLIST_HEADER;
#endif /* _WIN64 */
/* Singly-Linked List */
WINPR_API VOID InitializeSListHead(WINPR_PSLIST_HEADER ListHead);
WINPR_API WINPR_PSLIST_ENTRY InterlockedPushEntrySList(WINPR_PSLIST_HEADER ListHead,
WINPR_PSLIST_ENTRY ListEntry);
WINPR_API WINPR_PSLIST_ENTRY InterlockedPushListSListEx(WINPR_PSLIST_HEADER ListHead,
WINPR_PSLIST_ENTRY List,
WINPR_PSLIST_ENTRY ListEnd,
ULONG Count);
WINPR_API WINPR_PSLIST_ENTRY InterlockedPopEntrySList(WINPR_PSLIST_HEADER ListHead);
WINPR_API WINPR_PSLIST_ENTRY InterlockedFlushSList(WINPR_PSLIST_HEADER ListHead);
WINPR_API USHORT QueryDepthSList(WINPR_PSLIST_HEADER ListHead);
WINPR_API LONG InterlockedIncrement(LONG volatile* Addend);
WINPR_API LONG InterlockedDecrement(LONG volatile* Addend);
WINPR_API LONG InterlockedExchange(LONG volatile* Target, LONG Value);
WINPR_API LONG InterlockedExchangeAdd(LONG volatile* Addend, LONG Value);
WINPR_API LONG InterlockedCompareExchange(LONG volatile* Destination, LONG Exchange,
LONG Comperand);
WINPR_API PVOID InterlockedCompareExchangePointer(PVOID volatile* Destination, PVOID Exchange,
PVOID Comperand);
#else /* _WIN32 */
#define WINPR_LIST_ENTRY LIST_ENTRY
#define WINPR_PLIST_ENTRY PLIST_ENTRY
#define WINPR_SINGLE_LIST_ENTRY SINGLE_LIST_ENTRY
#define WINPR_PSINGLE_LIST_ENTRY PSINGLE_LIST_ENTRY
#define WINPR_SLIST_ENTRY SLIST_ENTRY
#define WINPR_PSLIST_ENTRY PSLIST_ENTRY
#define WINPR_SLIST_HEADER SLIST_HEADER
#define WINPR_PSLIST_HEADER PSLIST_HEADER
#endif /* _WIN32 */
#if (!defined(_WIN32) || \
(defined(_WIN32) && (_WIN32_WINNT < 0x0502) && !defined(InterlockedCompareExchange64)))
#define WINPR_INTERLOCKED_COMPARE_EXCHANGE64 1
#endif
#ifdef WINPR_INTERLOCKED_COMPARE_EXCHANGE64
WINPR_API LONGLONG InterlockedCompareExchange64(LONGLONG volatile* Destination,
LONGLONG Exchange, LONGLONG Comperand);
#endif
/* Doubly-Linked List */
WINPR_API VOID InitializeListHead(WINPR_PLIST_ENTRY ListHead);
WINPR_API BOOL IsListEmpty(const WINPR_LIST_ENTRY* ListHead);
WINPR_API BOOL RemoveEntryList(WINPR_PLIST_ENTRY Entry);
WINPR_API VOID InsertHeadList(WINPR_PLIST_ENTRY ListHead, WINPR_PLIST_ENTRY Entry);
WINPR_API WINPR_PLIST_ENTRY RemoveHeadList(WINPR_PLIST_ENTRY ListHead);
WINPR_API VOID InsertTailList(WINPR_PLIST_ENTRY ListHead, WINPR_PLIST_ENTRY Entry);
WINPR_API WINPR_PLIST_ENTRY RemoveTailList(WINPR_PLIST_ENTRY ListHead);
WINPR_API VOID AppendTailList(WINPR_PLIST_ENTRY ListHead, WINPR_PLIST_ENTRY ListToAppend);
WINPR_API VOID PushEntryList(WINPR_PSINGLE_LIST_ENTRY ListHead, WINPR_PSINGLE_LIST_ENTRY Entry);
WINPR_API WINPR_PSINGLE_LIST_ENTRY PopEntryList(WINPR_PSINGLE_LIST_ENTRY ListHead);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_INTERLOCKED_H */

View File

@@ -0,0 +1,93 @@
/**
* WinPR: Windows Portable Runtime
* C Run-Time Library Routines
*
* Copyright 2015 Thincast Technologies GmbH
* Copyright 2015 Bernhard Miklautz <bernhard.miklautz@thincast.com>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_INTRIN_H
#define WINPR_INTRIN_H
#if !defined(_WIN32) || defined(__MINGW32__) || defined(_M_ARM64)
/**
* __lzcnt16, __lzcnt, __lzcnt64:
* http://msdn.microsoft.com/en-us/library/bb384809/
*
* Beware: the result of __builtin_clz(0) is undefined
*/
#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2))
static inline UINT32 __lzcnt(UINT32 _val32)
{
return ((UINT32)__builtin_clz(_val32));
}
#if !(defined(__MINGW32__) && defined(__clang__))
static inline UINT16 __lzcnt16(UINT16 _val16)
{
return ((UINT16)(__builtin_clz((UINT32)_val16) - 16));
}
#endif /* !(defined(__MINGW32__) && defined(__clang__)) */
#else /* (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2) */
static inline UINT32 __lzcnt(UINT32 x)
{
unsigned y;
int n = 32;
y = x >> 16;
if (y != 0)
{
n = n - 16;
x = y;
}
y = x >> 8;
if (y != 0)
{
n = n - 8;
x = y;
}
y = x >> 4;
if (y != 0)
{
n = n - 4;
x = y;
}
y = x >> 2;
if (y != 0)
{
n = n - 2;
x = y;
}
y = x >> 1;
if (y != 0)
return n - 2;
return n - x;
}
static inline UINT16 __lzcnt16(UINT16 x)
{
return ((UINT16)__lzcnt((UINT32)x));
}
#endif /* (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2) */
#endif /* !defined(_WIN32) || defined(__MINGW32__) */
#endif /* WINPR_INTRIN_H */

View File

@@ -0,0 +1,264 @@
/**
* WinPR: Windows Portable Runtime
* Asynchronous I/O Functions
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_IO_H
#define WINPR_IO_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/handle.h>
WINPR_PRAGMA_DIAG_PUSH
WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER
#ifdef _WIN32
#include <winioctl.h>
#else
#include <winpr/nt.h>
typedef struct
{
ULONG_PTR Internal;
ULONG_PTR InternalHigh;
union
{
struct
{
DWORD Offset;
DWORD OffsetHigh;
} DUMMYSTRUCTNAME;
PVOID Pointer;
} DUMMYUNIONNAME;
HANDLE hEvent;
} OVERLAPPED, *LPOVERLAPPED;
typedef struct
{
ULONG_PTR lpCompletionKey;
LPOVERLAPPED lpOverlapped;
ULONG_PTR Internal;
DWORD dwNumberOfBytesTransferred;
} OVERLAPPED_ENTRY, *LPOVERLAPPED_ENTRY;
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API BOOL GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
LPDWORD lpNumberOfBytesTransferred, BOOL bWait);
WINPR_API BOOL GetOverlappedResultEx(HANDLE hFile, LPOVERLAPPED lpOverlapped,
LPDWORD lpNumberOfBytesTransferred, DWORD dwMilliseconds,
BOOL bAlertable);
WINPR_API BOOL DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode, LPVOID lpInBuffer,
DWORD nInBufferSize, LPVOID lpOutBuffer, DWORD nOutBufferSize,
LPDWORD lpBytesReturned, LPOVERLAPPED lpOverlapped);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateIoCompletionPort(HANDLE FileHandle, HANDLE ExistingCompletionPort,
ULONG_PTR CompletionKey,
DWORD NumberOfConcurrentThreads);
WINPR_API BOOL GetQueuedCompletionStatus(HANDLE CompletionPort,
LPDWORD lpNumberOfBytesTransferred,
PULONG_PTR lpCompletionKey, LPOVERLAPPED* lpOverlapped,
DWORD dwMilliseconds);
WINPR_API BOOL GetQueuedCompletionStatusEx(HANDLE CompletionPort,
LPOVERLAPPED_ENTRY lpCompletionPortEntries,
ULONG ulCount, PULONG ulNumEntriesRemoved,
DWORD dwMilliseconds, BOOL fAlertable);
WINPR_API BOOL PostQueuedCompletionStatus(HANDLE CompletionPort,
DWORD dwNumberOfBytesTransferred,
ULONG_PTR dwCompletionKey, LPOVERLAPPED lpOverlapped);
WINPR_API BOOL CancelIo(HANDLE hFile);
WINPR_API BOOL CancelIoEx(HANDLE hFile, LPOVERLAPPED lpOverlapped);
WINPR_API BOOL CancelSynchronousIo(HANDLE hThread);
#ifdef __cplusplus
}
#endif
#define DEVICE_TYPE ULONG
#define FILE_DEVICE_BEEP 0x00000001
#define FILE_DEVICE_CD_ROM 0x00000002
#define FILE_DEVICE_CD_ROM_FILE_SYSTEM 0x00000003
#define FILE_DEVICE_CONTROLLER 0x00000004
#define FILE_DEVICE_DATALINK 0x00000005
#define FILE_DEVICE_DFS 0x00000006
#define FILE_DEVICE_DISK 0x00000007
#define FILE_DEVICE_DISK_FILE_SYSTEM 0x00000008
#define FILE_DEVICE_FILE_SYSTEM 0x00000009
#define FILE_DEVICE_INPORT_PORT 0x0000000a
#define FILE_DEVICE_KEYBOARD 0x0000000b
#define FILE_DEVICE_MAILSLOT 0x0000000c
#define FILE_DEVICE_MIDI_IN 0x0000000d
#define FILE_DEVICE_MIDI_OUT 0x0000000e
#define FILE_DEVICE_MOUSE 0x0000000f
#define FILE_DEVICE_MULTI_UNC_PROVIDER 0x00000010
#define FILE_DEVICE_NAMED_PIPE 0x00000011
#define FILE_DEVICE_NETWORK 0x00000012
#define FILE_DEVICE_NETWORK_BROWSER 0x00000013
#define FILE_DEVICE_NETWORK_FILE_SYSTEM 0x00000014
#define FILE_DEVICE_NULL 0x00000015
#define FILE_DEVICE_PARALLEL_PORT 0x00000016
#define FILE_DEVICE_PHYSICAL_NETCARD 0x00000017
#define FILE_DEVICE_PRINTER 0x00000018
#define FILE_DEVICE_SCANNER 0x00000019
#define FILE_DEVICE_SERIAL_MOUSE_PORT 0x0000001a
#define FILE_DEVICE_SERIAL_PORT 0x0000001b
#define FILE_DEVICE_SCREEN 0x0000001c
#define FILE_DEVICE_SOUND 0x0000001d
#define FILE_DEVICE_STREAMS 0x0000001e
#define FILE_DEVICE_TAPE 0x0000001f
#define FILE_DEVICE_TAPE_FILE_SYSTEM 0x00000020
#define FILE_DEVICE_TRANSPORT 0x00000021
#define FILE_DEVICE_UNKNOWN 0x00000022
#define FILE_DEVICE_VIDEO 0x00000023
#define FILE_DEVICE_VIRTUAL_DISK 0x00000024
#define FILE_DEVICE_WAVE_IN 0x00000025
#define FILE_DEVICE_WAVE_OUT 0x00000026
#define FILE_DEVICE_8042_PORT 0x00000027
#define FILE_DEVICE_NETWORK_REDIRECTOR 0x00000028
#define FILE_DEVICE_BATTERY 0x00000029
#define FILE_DEVICE_BUS_EXTENDER 0x0000002a
#define FILE_DEVICE_MODEM 0x0000002b
#define FILE_DEVICE_VDM 0x0000002c
#define FILE_DEVICE_MASS_STORAGE 0x0000002d
#define FILE_DEVICE_SMB 0x0000002e
#define FILE_DEVICE_KS 0x0000002f
#define FILE_DEVICE_CHANGER 0x00000030
#define FILE_DEVICE_SMARTCARD 0x00000031
#define FILE_DEVICE_ACPI 0x00000032
#define FILE_DEVICE_DVD 0x00000033
#define FILE_DEVICE_FULLSCREEN_VIDEO 0x00000034
#define FILE_DEVICE_DFS_FILE_SYSTEM 0x00000035
#define FILE_DEVICE_DFS_VOLUME 0x00000036
#define FILE_DEVICE_SERENUM 0x00000037
#define FILE_DEVICE_TERMSRV 0x00000038
#define FILE_DEVICE_KSEC 0x00000039
#define FILE_DEVICE_FIPS 0x0000003A
#define FILE_DEVICE_INFINIBAND 0x0000003B
#define FILE_DEVICE_VMBUS 0x0000003E
#define FILE_DEVICE_CRYPT_PROVIDER 0x0000003F
#define FILE_DEVICE_WPD 0x00000040
#define FILE_DEVICE_BLUETOOTH 0x00000041
#define FILE_DEVICE_MT_COMPOSITE 0x00000042
#define FILE_DEVICE_MT_TRANSPORT 0x00000043
#define FILE_DEVICE_BIOMETRIC 0x00000044
#define FILE_DEVICE_PMI 0x00000045
#define CTL_CODE(DeviceType, Function, Method, Access) \
(((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
#define DEVICE_TYPE_FROM_CTL_CODE(ctrlCode) (((DWORD)(ctrlCode & 0xFFFF0000)) >> 16)
#define METHOD_FROM_CTL_CODE(ctrlCode) ((DWORD)(ctrlCode & 3))
#define METHOD_BUFFERED 0
#define METHOD_IN_DIRECT 1
#define METHOD_OUT_DIRECT 2
#define METHOD_NEITHER 3
#define FILE_ANY_ACCESS 0
#define FILE_SPECIAL_ACCESS (FILE_ANY_ACCESS)
#define FILE_READ_ACCESS (0x0001)
#define FILE_WRITE_ACCESS (0x0002)
/*
* WinPR I/O Manager Custom API
*/
typedef HANDLE PDRIVER_OBJECT_EX;
typedef HANDLE PDEVICE_OBJECT_EX;
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
WINPR_API NTSTATUS _IoCreateDeviceEx(PDRIVER_OBJECT_EX DriverObject, ULONG DeviceExtensionSize,
PUNICODE_STRING DeviceName, DEVICE_TYPE DeviceType,
ULONG DeviceCharacteristics, BOOLEAN Exclusive,
PDEVICE_OBJECT_EX* DeviceObject);
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
WINPR_API VOID _IoDeleteDeviceEx(PDEVICE_OBJECT_EX DeviceObject);
#endif
#ifdef _UWP
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API BOOL GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
LPDWORD lpNumberOfBytesTransferred, BOOL bWait);
WINPR_API BOOL DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode, LPVOID lpInBuffer,
DWORD nInBufferSize, LPVOID lpOutBuffer, DWORD nOutBufferSize,
LPDWORD lpBytesReturned, LPOVERLAPPED lpOverlapped);
WINPR_API HANDLE CreateIoCompletionPort(HANDLE FileHandle, HANDLE ExistingCompletionPort,
ULONG_PTR CompletionKey,
DWORD NumberOfConcurrentThreads);
WINPR_API BOOL GetQueuedCompletionStatus(HANDLE CompletionPort,
LPDWORD lpNumberOfBytesTransferred,
PULONG_PTR lpCompletionKey, LPOVERLAPPED* lpOverlapped,
DWORD dwMilliseconds);
WINPR_API BOOL GetQueuedCompletionStatusEx(HANDLE CompletionPort,
LPOVERLAPPED_ENTRY lpCompletionPortEntries,
ULONG ulCount, PULONG ulNumEntriesRemoved,
DWORD dwMilliseconds, BOOL fAlertable);
WINPR_API BOOL PostQueuedCompletionStatus(HANDLE CompletionPort,
DWORD dwNumberOfBytesTransferred,
ULONG_PTR dwCompletionKey, LPOVERLAPPED lpOverlapped);
WINPR_API BOOL CancelIo(HANDLE hFile);
WINPR_API BOOL CancelSynchronousIo(HANDLE hThread);
#ifdef __cplusplus
}
#endif
#endif
/**
* Extended API
*/
#define ACCESS_FROM_CTL_CODE(ctrlCode) ((DWORD)((ctrlCode >> 14) & 0x3))
#define FUNCTION_FROM_CTL_CODE(ctrlCode) ((DWORD)((ctrlCode >> 2) & 0xFFF))
WINPR_PRAGMA_DIAG_POP
#endif /* WINPR_IO_H */

View File

@@ -0,0 +1,431 @@
/**
* FreeRDP: A Remote Desktop Protocol Implementation
* JSON parser wrapper
*
* Copyright 2024 Armin Novak <anovak@thincast.com>
* Copyright 2024 Thincast Technologies GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_UTILS_JSON
#define WINPR_UTILS_JSON
#include <winpr/winpr.h>
#include <winpr/string.h>
#include <winpr/wtypes.h>
/** @defgroup WINPR_JSON WinPR JSON wrapper
* @since version 3.6.0
* @brief Wrapper around cJSON, JSONC or jansson libraries
* @{
*/
#ifdef __cplusplus
extern "C"
{
#endif
typedef void WINPR_JSON;
/**
* @brief Get the library version string
*
* @param buffer a string buffer to hold the version string
* @param len the length of the buffer
* @return length of the version string in bytes or negative for error
* @since version 3.6.0
*/
WINPR_API int WINPR_JSON_version(char* buffer, size_t len);
/**
* @brief Delete a @ref WINPR_JSON object
*
* @param item The instance to delete
* @since version 3.6.0
*/
WINPR_API void WINPR_JSON_Delete(WINPR_JSON* item);
/**
* @brief Parse a '\0' terminated JSON string
*
* @param value A '\0' terminated JSON string
* @return A @ref WINPR_JSON object holding the parsed string or \b nullptr if failed
* @since version 3.6.0
*/
WINPR_ATTR_MALLOC(WINPR_JSON_Delete, 1)
WINPR_ATTR_NODISCARD
WINPR_API WINPR_JSON* WINPR_JSON_Parse(const char* value);
/**
* @brief Parse a JSON string
*
* @param value A JSON string
* @param buffer_length The length in bytes of the JSON string
* @return A @ref WINPR_JSON object holding the parsed string or \b nullptr if failed
* @since version 3.6.0
*/
WINPR_ATTR_MALLOC(WINPR_JSON_Delete, 1)
WINPR_ATTR_NODISCARD
WINPR_API WINPR_JSON* WINPR_JSON_ParseWithLength(const char* value, size_t buffer_length);
/**
* @brief Parse a JSON string read from a file \b filename
*
* @param filename the name of the file to read from
* @return A @ref WINPR_JSON object holding the parsed string or \b nullptr if failed
* @since version 3.16.0
*/
WINPR_ATTR_MALLOC(WINPR_JSON_Delete, 1)
WINPR_ATTR_NODISCARD
WINPR_API WINPR_JSON* WINPR_JSON_ParseFromFile(const char* filename);
/**
* @brief Parse a JSON string read from a \b FILE
*
* @param fp a \b FILE pointer to read from.
* @return A @ref WINPR_JSON object holding the parsed string or \b nullptr if failed
* @since version 3.16.0
*/
WINPR_ATTR_MALLOC(WINPR_JSON_Delete, 1)
WINPR_ATTR_NODISCARD
WINPR_API WINPR_JSON* WINPR_JSON_ParseFromFileFP(FILE* fp);
/**
* @brief Get the number of arrayitems from an array
*
* @param array the JSON instance to query
* @return number of array items
* @since version 3.6.0
*/
WINPR_API size_t WINPR_JSON_GetArraySize(const WINPR_JSON* array);
/**
* @brief Return a pointer to an item in the array
*
* @param array the JSON instance to query
* @param index The index of the array item
* @return A pointer to the array item or \b nullptr if failed
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_GetArrayItem(const WINPR_JSON* array, size_t index);
/**
* @brief Return a pointer to an JSON object item
* @param object the JSON object
* @param string the name of the object (case is ignored)
*
* @return A pointer to the object identified by \b string or \b nullptr
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_GetObjectItem(const WINPR_JSON* object, const char* string);
/**
* @brief Same as @ref WINPR_JSON_GetObjectItem but with case sensitive matching
*
* @param object the JSON instance to query
* @param string the name of the object
* @return A pointer to the object identified by \b string or \b nullptr
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_GetObjectItemCaseSensitive(const WINPR_JSON* object,
const char* string);
/**
* @brief Check if JSON has an object matching the name
* @param object the JSON instance
* @param string the name of the object
* @return \b TRUE if found, \b FALSE otherwise
* @since version 3.6.0
*/
WINPR_API BOOL WINPR_JSON_HasObjectItem(const WINPR_JSON* object, const char* string);
/**
* @brief Return an error string
* @return A string describing the last error that occurred or \b nullptr
* @since version 3.6.0
*/
WINPR_API const char* WINPR_JSON_GetErrorPtr(void);
/**
* @brief Return the String value of a JSON item
* @param item the JSON item to query
* @return The string value or \b nullptr if failed
* @since version 3.6.0
*/
WINPR_API const char* WINPR_JSON_GetStringValue(WINPR_JSON* item);
/**
* @brief Return the Number value of a JSON item
* @param item the JSON item to query
* @return The Number value or \b NaN if failed
* @since version 3.6.0
*/
WINPR_API double WINPR_JSON_GetNumberValue(const WINPR_JSON* item);
/**
* @brief Check if JSON item is valid
* @param item the JSON item to query
* @return \b TRUE if valid, \b FALSE otherwise
* @since version 3.6.0
*/
WINPR_API BOOL WINPR_JSON_IsInvalid(const WINPR_JSON* item);
/**
* @brief Check if JSON item is BOOL value False
* @param item the JSON item to query
* @return \b TRUE if False, \b FALSE otherwise
* @since version 3.6.0
*/
WINPR_API BOOL WINPR_JSON_IsFalse(const WINPR_JSON* item);
/**
* @brief Check if JSON item is BOOL value True
* @param item the JSON item to query
* @return \b TRUE if True, \b FALSE otherwise
* @since version 3.6.0
*/
WINPR_API BOOL WINPR_JSON_IsTrue(const WINPR_JSON* item);
/**
* @brief Check if JSON item is of type BOOL
* @param item the JSON item to query
* @return \b TRUE if the type is BOOL, \b FALSE otherwise
* @since version 3.6.0
*/
WINPR_API BOOL WINPR_JSON_IsBool(const WINPR_JSON* item);
/**
* @brief Check if JSON item is Null
* @param item the JSON item to query
* @return \b TRUE if it is Null, \b FALSE otherwise
* @since version 3.6.0
*/
WINPR_API BOOL WINPR_JSON_IsNull(const WINPR_JSON* item);
/**
* @brief Check if JSON item is of type Number
* @param item the JSON item to query
* @return \b TRUE if the type is Number, \b FALSE otherwise
* @since version 3.6.0
*/
WINPR_API BOOL WINPR_JSON_IsNumber(const WINPR_JSON* item);
/**
* @brief Check if JSON item is of type String
* @param item the JSON item to query
* @return \b TRUE if the type is String, \b FALSE otherwise
* @since version 3.6.0
*/
WINPR_API BOOL WINPR_JSON_IsString(const WINPR_JSON* item);
/**
* @brief Check if JSON item is of type Array
* @param item the JSON item to query
* @return \b TRUE if the type is Array, \b FALSE otherwise
* @since version 3.6.0
*/
WINPR_API BOOL WINPR_JSON_IsArray(const WINPR_JSON* item);
/**
* @brief Check if JSON item is of type Object
* @param item the JSON item to query
* @return \b TRUE if the type is Object, \b FALSE otherwise
* @since version 3.6.0
*/
WINPR_API BOOL WINPR_JSON_IsObject(const WINPR_JSON* item);
/**
* @brief WINPR_JSON_CreateNull
* @return a new JSON item of type and value Null
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_CreateNull(void);
/**
* @brief WINPR_JSON_CreateTrue
* @return a new JSON item of type Bool and value True
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_CreateTrue(void);
/**
* @brief WINPR_JSON_CreateFalse
* @return a new JSON item of type Bool and value False
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_CreateFalse(void);
/**
* @brief WINPR_JSON_CreateBool
* @param boolean the value the JSON item should have
* @return a new JSON item of type Bool
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_CreateBool(BOOL boolean);
/**
* @brief WINPR_JSON_CreateNumber
* @param num the number value of the new item
* @return a new JSON item of type Number
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_CreateNumber(double num);
/**
* @brief WINPR_JSON_CreateString
* @param string The string value of the new item
* @return a new JSON item of type String
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_CreateString(const char* string);
/**
* @brief WINPR_JSON_CreateArray
* @return a new JSON item of type array, empty
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_CreateArray(void);
/**
* @brief WINPR_JSON_CreateObject
* @return a new JSON item of type Object
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_CreateObject(void);
/**
* @brief WINPR_JSON_AddNullToObject
* @param object The JSON object the new item is added to
* @param name The name of the object
* @return the new JSON item added
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_AddNullToObject(WINPR_JSON* object, const char* name);
/**
* @brief WINPR_JSON_AddTrueToObject
* @param object The JSON object the new item is added to
* @param name The name of the object
* @return the new JSON item added
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_AddTrueToObject(WINPR_JSON* object, const char* name);
/**
* @brief WINPR_JSON_AddFalseToObject
* @param object The JSON object the new item is added to
* @param name The name of the object
* @return the new JSON item added
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_AddFalseToObject(WINPR_JSON* object, const char* name);
/**
* @brief WINPR_JSON_AddBoolToObject
* @param object The JSON object the new item is added to
* @param name The name of the object
* @return the new JSON item added
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_AddBoolToObject(WINPR_JSON* object, const char* name,
BOOL boolean);
/**
* @brief WINPR_JSON_AddNumberToObject
* @param object The JSON object the new item is added to
* @param name The name of the object
* @return the new JSON item added
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_AddNumberToObject(WINPR_JSON* object, const char* name,
double number);
/**
* @brief WINPR_JSON_AddIntegerToObject
* @param object The JSON object the new item is added to
* @param name The name of the object
* @return the new JSON item added
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_AddIntegerToObject(WINPR_JSON* object, const char* name,
int64_t number);
/**
* @brief WINPR_JSON_AddStringToObject
* @param object The JSON object the new item is added to
* @param name The name of the object
* @return the new JSON item added
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_AddStringToObject(WINPR_JSON* object, const char* name,
const char* string);
/**
* @brief WINPR_JSON_AddObjectToObject
* @param object The JSON object the new item is added to
* @param name The name of the object
* @return the new JSON item added
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_AddObjectToObject(WINPR_JSON* object, const char* name);
/**
* @brief WINPR_JSON_AddArrayToObject
* @param object The JSON object the new item is added to
* @param name The name of the object
* @return the new JSON item added
* @since version 3.6.0
*/
WINPR_API WINPR_JSON* WINPR_JSON_AddArrayToObject(WINPR_JSON* object, const char* name);
/**
* @brief Add an item to an existing array
* @param array An array to add to, must not be \b nullptr
* @param item An item to add, must not be \b nullptr
* @return \b TRUE for success, \b FALSE for failure
* @since version 3.7.0
*/
WINPR_API BOOL WINPR_JSON_AddItemToArray(WINPR_JSON* array, WINPR_JSON* item);
/**
* @brief Serialize a JSON instance to string
* for minimal size without formatting see @ref WINPR_JSON_PrintUnformatted
*
* @param item The JSON instance to serialize
* @return A string representation of the JSON instance or \b nullptr
* @since version 3.6.0
*/
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* WINPR_JSON_Print(WINPR_JSON* item);
/**
* @brief Serialize a JSON instance to string without formatting
* for human readable formatted output see @ref WINPR_JSON_Print
*
* @param item The JSON instance to serialize
* @return A string representation of the JSON instance or \b nullptr
* @since version 3.6.0
*/
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* WINPR_JSON_PrintUnformatted(WINPR_JSON* item);
#ifdef __cplusplus
}
#endif
/** @} */
#endif

View File

@@ -0,0 +1,129 @@
/**
* WinPR: Windows Portable Runtime
* Library Loader
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_LIBRARY_H
#define WINPR_LIBRARY_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#if !defined(_WIN32) || defined(_UWP)
typedef HANDLE DLL_DIRECTORY_COOKIE;
#define LOAD_LIBRARY_SEARCH_APPLICATION_DIR 0x00000200
#define LOAD_LIBRARY_SEARCH_DEFAULT_DIRS 0x00001000
#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
#define LOAD_LIBRARY_SEARCH_USER_DIRS 0x00000400
#define DONT_RESOLVE_DLL_REFERENCES 0x00000001
#define LOAD_LIBRARY_AS_DATAFILE 0x00000002
#define LOAD_WITH_ALTERED_SEARCH_PATH 0x00000008
#define LOAD_IGNORE_CODE_AUTHZ_LEVEL 0x00000010
#define LOAD_LIBRARY_AS_IMAGE_RESOURCE 0x00000020
#define LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE 0x00000040
#define LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR 0x00000100
#define LOAD_LIBRARY_SEARCH_APPLICATION_DIR 0x00000200
#define LOAD_LIBRARY_SEARCH_USER_DIRS 0x00000400
#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
#define LOAD_LIBRARY_SEARCH_DEFAULT_DIRS 0x00001000
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API DLL_DIRECTORY_COOKIE AddDllDirectory(PCWSTR NewDirectory);
WINPR_API BOOL RemoveDllDirectory(DLL_DIRECTORY_COOKIE Cookie);
WINPR_API BOOL SetDefaultDllDirectories(DWORD DirectoryFlags);
WINPR_API HMODULE LoadLibraryA(LPCSTR lpLibFileName);
WINPR_API HMODULE LoadLibraryW(LPCWSTR lpLibFileName);
WINPR_API HMODULE LoadLibraryExA(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags);
WINPR_API HMODULE LoadLibraryExW(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags);
#ifdef __cplusplus
}
#endif
#ifdef UNICODE
#define LoadLibrary LoadLibraryW
#define LoadLibraryEx LoadLibraryExW
#else
#define LoadLibrary LoadLibraryA
#define LoadLibraryEx LoadLibraryExA
#endif
#endif
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API HMODULE LoadLibraryX(LPCSTR lpLibFileName);
WINPR_API HMODULE LoadLibraryExX(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags);
#ifdef __cplusplus
}
#endif
/**
* @brief A macro to get a function pointer from a library handle
* @param module The library handle
* @param name The name of the function
* @param type The type of the function pointer
* @since version 3.9.0
* @return A new function pointer or \b nullptr
*/
#define GetProcAddressAs(module, name, type) WINPR_FUNC_PTR_CAST(GetProcAddress(module, name), type)
#if !defined(_WIN32) && !defined(__CYGWIN__)
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API HMODULE GetModuleHandleA(LPCSTR lpModuleName);
WINPR_API HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
WINPR_API DWORD GetModuleFileNameA(HMODULE hModule, LPSTR lpFilename, DWORD nSize);
WINPR_API DWORD GetModuleFileNameW(HMODULE hModule, LPWSTR lpFilename, DWORD nSize);
WINPR_API FARPROC GetProcAddress(HMODULE hModule, LPCSTR lpProcName);
WINPR_API BOOL FreeLibrary(HMODULE hLibModule);
#ifdef __cplusplus
}
#endif
#ifdef UNICODE
#define GetModuleHandle GetModuleHandleW
#define GetModuleFileName GetModuleFileNameW
#else
#define GetModuleHandle GetModuleHandleA
#define GetModuleFileName GetModuleFileNameA
#endif
#endif
#endif /* WINPR_LIBRARY_H */

View File

@@ -0,0 +1,86 @@
/**
* WinPR: Windows Portable Runtime
* Memory Allocation
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_MEMORY_H
#define WINPR_MEMORY_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/crt.h>
#include <winpr/file.h>
#ifndef _WIN32
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateFileMappingA(HANDLE hFile, LPSECURITY_ATTRIBUTES lpAttributes,
DWORD flProtect, DWORD dwMaximumSizeHigh,
DWORD dwMaximumSizeLow, LPCSTR lpName);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateFileMappingW(HANDLE hFile, LPSECURITY_ATTRIBUTES lpAttributes,
DWORD flProtect, DWORD dwMaximumSizeHigh,
DWORD dwMaximumSizeLow, LPCWSTR lpName);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE OpenFileMappingA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE OpenFileMappingW(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCWSTR lpName);
WINPR_API LPVOID MapViewOfFile(HANDLE hFileMappingObject, DWORD dwDesiredAccess,
DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow,
size_t dwNumberOfBytesToMap);
WINPR_API LPVOID MapViewOfFileEx(HANDLE hFileMappingObject, DWORD dwDesiredAccess,
DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow,
size_t dwNumberOfBytesToMap, LPVOID lpBaseAddress);
WINPR_API BOOL FlushViewOfFile(LPCVOID lpBaseAddress, size_t dwNumberOfBytesToFlush);
WINPR_API BOOL UnmapViewOfFile(LPCVOID lpBaseAddress);
#ifdef __cplusplus
}
#endif
#ifdef UNICODE
#define CreateFileMapping CreateFileMappingW
#define OpenFileMapping OpenFileMappingW
#else
#define CreateFileMapping CreateFileMappingA
#define OpenFileMapping OpenFileMappingA
#endif
#endif
#endif /* WINPR_MEMORY_H */

View File

@@ -0,0 +1,234 @@
/**
* WinPR: Windows Portable Runtime
* NCrypt library
*
* Copyright 2021 David Fort <contact@hardening-consulting.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_INCLUDE_WINPR_NCRYPT_H_
#define WINPR_INCLUDE_WINPR_NCRYPT_H_
#ifdef _WIN32
#include <wincrypt.h>
#include <ncrypt.h>
#else
#include <winpr/wtypes.h>
#include <winpr/winpr.h>
WINPR_PRAGMA_DIAG_PUSH
WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO
#ifndef __SECSTATUS_DEFINED__
typedef LONG SECURITY_STATUS;
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define __SECSTATUS_DEFINED__
#endif
WINPR_PRAGMA_DIAG_POP
typedef ULONG_PTR NCRYPT_HANDLE;
typedef ULONG_PTR NCRYPT_PROV_HANDLE;
typedef ULONG_PTR NCRYPT_KEY_HANDLE;
#define MS_KEY_STORAGE_PROVIDER \
(const WCHAR*)"M\x00i\x00" \
"c\x00r\x00o\x00s\x00o\x00" \
"f\x00t\x00 " \
"\x00S\x00o\x00" \
"f\x00t\x00w\x00" \
"a\x00r\x00" \
"e\x00 \x00K\x00" \
"e\x00y\x00 " \
"\x00S\x00t\x00o\x00r\x00" \
"a\x00g\x00" \
"e\x00 " \
"\x00P\x00r\x00o\x00v\x00i\x00" \
"d\x00" \
"e\x00r\x00\x00"
#define MS_SMART_CARD_KEY_STORAGE_PROVIDER \
(const WCHAR*)"M\x00i\x00" \
"c\x00r\x00o\x00s\x00o\x00" \
"f\x00t\x00 \x00S\x00m\x00" \
"a\x00r\x00t\x00 " \
"\x00" \
"C\x00" \
"a\x00r\x00" \
"d\x00 \x00K\x00" \
"e\x00y\x00 " \
"\x00S\x00t\x00o\x00r\x00" \
"a\x00g\x00" \
"e\x00 " \
"\x00P\x00r\x00o\x00v\x00i\x00" \
"d\x00" \
"e\x00r\x00\x00"
#define MS_SCARD_PROV_A "Microsoft Base Smart Card Crypto Provider"
#define MS_SCARD_PROV \
(const WCHAR*)("M\x00i\x00" \
"c\x00r\x00o\x00s\x00o\x00" \
"f\x00t\x00 \x00" \
"B\x00" \
"a\x00s\x00" \
"e\x00 " \
"\x00S\x00m\x00" \
"a\x00r\x00t\x00 \x00" \
"C\x00" \
"a\x00r\x00" \
"d\x00 " \
"\x00" \
"C\x00r\x00y\x00p\x00t\x00o\x00 " \
"\x00P\x00r\x00o\x00v\x00i\x00" \
"d\x00" \
"e\x00r\x00\x00")
#define MS_PLATFORM_KEY_STORAGE_PROVIDER \
(const WCHAR*)"M\x00i\x00" \
"c\x00r\x00o\x00s\x00o\x00" \
"f\x00t\x00 " \
"\x00P\x00l\x00" \
"a\x00t\x00" \
"f\x00o\x00r\x00m\x00 " \
"\x00" \
"C\x00r\x00y\x00p\x00t\x00o\x00 " \
"\x00P\x00r\x00o\x00v\x00i\x00" \
"d\x00" \
"e\x00r\x00\x00"
#define NCRYPT_CERTIFICATE_PROPERTY \
(const WCHAR*)"S\x00m\x00" \
"a\x00r\x00t\x00" \
"C\x00" \
"a\x00r\x00" \
"d\x00K\x00" \
"e\x00y\x00" \
"C\x00" \
"e\x00r\x00t" \
"\x00i\x00" \
"f\x00i\x00" \
"c\x00" \
"a\x00t\x00" \
"e\x00\x00"
#define NCRYPT_NAME_PROPERTY (const WCHAR*)"N\x00a\x00m\x00e\x00\x00"
#define NCRYPT_UNIQUE_NAME_PROPERTY \
(const WCHAR*)"U\x00n\x00i\x00q\x00u\x00" \
"e\x00 \x00N\x00" \
"a\x00m\x00" \
"e\x00\x00"
#define NCRYPT_READER_PROPERTY \
(const WCHAR*)"S\x00m\x00" \
"a\x00r\x00t\x00" \
"C\x00" \
"a\x00r\x00" \
"d\x00R\x00" \
"e\x00" \
"a\x00" \
"d\x00" \
"e\x00r\x00\x00"
/* winpr specific properties */
#define NCRYPT_WINPR_SLOTID (const WCHAR*)"S\x00l\x00o\x00t\x00\x00"
#define NCRYPT_MACHINE_KEY_FLAG 0x20
#define NCRYPT_SILENT_FLAG 0x40
/** @brief a key name descriptor */
typedef struct NCryptKeyName
{
LPWSTR pszName;
LPWSTR pszAlgid;
DWORD dwLegacyKeySpec;
DWORD dwFlags;
} NCryptKeyName;
/** @brief a provider name descriptor */
typedef struct NCryptProviderName
{
LPWSTR pszName;
LPWSTR pszComment;
} NCryptProviderName;
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API SECURITY_STATUS NCryptEnumStorageProviders(DWORD* wProviderCount,
NCryptProviderName** ppProviderList,
DWORD dwFlags);
WINPR_API SECURITY_STATUS NCryptOpenStorageProvider(NCRYPT_PROV_HANDLE* phProvider,
LPCWSTR pszProviderName, DWORD dwFlags);
WINPR_API SECURITY_STATUS NCryptEnumKeys(NCRYPT_PROV_HANDLE hProvider, LPCWSTR pszScope,
NCryptKeyName** ppKeyName, PVOID* ppEnumState,
DWORD dwFlags);
WINPR_API SECURITY_STATUS NCryptOpenKey(NCRYPT_PROV_HANDLE hProvider, NCRYPT_KEY_HANDLE* phKey,
LPCWSTR pszKeyName, DWORD dwLegacyKeySpec,
DWORD dwFlags);
WINPR_API SECURITY_STATUS NCryptGetProperty(NCRYPT_HANDLE hObject, LPCWSTR pszProperty,
PBYTE pbOutput, DWORD cbOutput, DWORD* pcbResult,
DWORD dwFlags);
WINPR_API SECURITY_STATUS NCryptFreeObject(NCRYPT_HANDLE hObject);
WINPR_API SECURITY_STATUS NCryptFreeBuffer(PVOID pvInput);
#ifdef __cplusplus
}
#endif
#endif /* _WIN32 */
#ifdef __cplusplus
extern "C"
{
#endif
/**
* custom NCryptOpenStorageProvider that allows to provide a list of modules to load
*
* @param phProvider [out] resulting provider handle
* @param dwFlags [in] the flags to use
* @param modulePaths [in] an array of library path to try to load ended with a nullptr string
* @return ERROR_SUCCESS or an NTE error code something failed
*/
WINPR_API SECURITY_STATUS winpr_NCryptOpenStorageProviderEx(NCRYPT_PROV_HANDLE* phProvider,
LPCWSTR pszProviderName,
DWORD dwFlags, LPCSTR* modulePaths);
/**
* Gives a string representation of a SECURITY_STATUS
*
* @param status [in] SECURITY_STATUS that we want as string
* @return the string representation of status
*/
WINPR_API const char* winpr_NCryptSecurityStatusError(SECURITY_STATUS status);
/**
* Gives a module path of provider handle
*
* @param phProvider [in] provider handle
* @return module path
* @since version 3.6.0
*/
WINPR_API const char* winpr_NCryptGetModulePath(NCRYPT_PROV_HANDLE phProvider);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_INCLUDE_WINPR_NCRYPT_H_ */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,68 @@
/**
* WinPR: Windows Portable Runtime
* NTLM Utils
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_UTILS_NTLM_H
#define WINPR_UTILS_NTLM_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/sspi.h>
#ifdef __cplusplus
extern "C"
{
#endif
typedef SECURITY_STATUS (*psPeerComputeNtlmHash)(void* client,
const SEC_WINNT_AUTH_IDENTITY* authIdentity,
const SecBuffer* ntproofvalue,
const BYTE* randkey, const BYTE* mic,
const SecBuffer* micvalue, BYTE* ntlmhash);
WINPR_API BOOL NTOWFv1W(LPWSTR Password, UINT32 PasswordLength, BYTE* NtHash);
WINPR_API BOOL NTOWFv1A(LPSTR Password, UINT32 PasswordLength, BYTE* NtHash);
WINPR_API BOOL NTOWFv2W(LPWSTR Password, UINT32 PasswordLength, LPWSTR User, UINT32 UserLength,
LPWSTR Domain, UINT32 DomainLength, BYTE* NtHash);
WINPR_API BOOL NTOWFv2A(LPSTR Password, UINT32 PasswordLength, LPSTR User, UINT32 UserLength,
LPSTR Domain, UINT32 DomainLength, BYTE* NtHash);
WINPR_API BOOL NTOWFv2FromHashW(BYTE* NtHashV1, LPWSTR User, UINT32 UserLength, LPWSTR Domain,
UINT32 DomainLength, BYTE* NtHash);
WINPR_API BOOL NTOWFv2FromHashA(BYTE* NtHashV1, LPSTR User, UINT32 UserLength, LPSTR Domain,
UINT32 DomainLength, BYTE* NtHash);
#ifdef __cplusplus
}
#endif
#ifdef UNICODE
#define NTOWFv1 NTOWFv1W
#define NTOWFv2 NTOWFv2W
#define NTOWFv2FromHash NTOWFv2FromHashW
#else
#define NTOWFv1 NTOWFv1A
#define NTOWFv2 NTOWFv2A
#define NTOWFv2FromHash NTOWFv2FromHashA
#endif
#endif /* WINPR_UTILS_NTLM_H */

View File

@@ -0,0 +1,100 @@
/**
* WinPR: Windows Portable Runtime
* Pragma Pack
*
* Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This header is meant to be repeatedly included
* after defining the operation to be done:
*
* #define WINPR_PACK_PUSH
* #include <winpr/pack.h> // enables packing
*
* #define WINPR_PACK_POP
* #include <winpr/pack.h> // disables packing
*
* On each include, WINPR_PACK_* macros are undefined.
*/
#if !defined(__APPLE__)
#ifndef WINPR_PRAGMA_PACK_EXT
#define WINPR_PRAGMA_PACK_EXT
#endif
#endif
#ifdef PRAGMA_PACK_PUSH
#ifndef PRAGMA_PACK_PUSH1
#define PRAGMA_PACK_PUSH1
#endif
#undef PRAGMA_PACK_PUSH
#endif
#ifdef PRAGMA_PACK_PUSH1
#ifdef WINPR_PRAGMA_PACK_EXT
#pragma pack(push, 1)
#else
#pragma pack(1)
#endif
#undef PRAGMA_PACK_PUSH1
#endif
#ifdef PRAGMA_PACK_PUSH2
#ifdef WINPR_PRAGMA_PACK_EXT
#pragma pack(push, 2)
#else
#pragma pack(2)
#endif
#undef PRAGMA_PACK_PUSH2
#endif
#ifdef PRAGMA_PACK_PUSH4
#ifdef WINPR_PRAGMA_PACK_EXT
#pragma pack(push, 4)
#else
#pragma pack(4)
#endif
#undef PRAGMA_PACK_PUSH4
#endif
#ifdef PRAGMA_PACK_PUSH8
#ifdef WINPR_PRAGMA_PACK_EXT
#pragma pack(push, 8)
#else
#pragma pack(8)
#endif
#undef PRAGMA_PACK_PUSH8
#endif
#ifdef PRAGMA_PACK_PUSH16
#ifdef WINPR_PRAGMA_PACK_EXT
#pragma pack(push, 16)
#else
#pragma pack(16)
#endif
#undef PRAGMA_PACK_PUSH16
#endif
#ifdef PRAGMA_PACK_POP
#ifdef WINPR_PRAGMA_PACK_EXT
#pragma pack(pop)
#else
#pragma pack()
#endif
#undef PRAGMA_PACK_POP
#endif
#undef WINPR_PRAGMA_PACK_EXT

View File

@@ -0,0 +1,515 @@
/**
* WinPR: Windows Portable Runtime
* Path Functions
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_PATH_H
#define WINPR_PATH_H
#include <winpr/winpr.h>
#include <winpr/tchar.h>
#include <winpr/error.h>
#include <winpr/wtypes.h>
//#define WINPR_HAVE_PATHCCH_H 1
#ifdef WINPR_HAVE_PATHCCH_H
#include <Pathcch.h>
#else
#ifdef __cplusplus
extern "C"
{
#endif
#define PATHCCH_ALLOW_LONG_PATHS \
0x00000001 /* Allow building of \\?\ paths if longer than MAX_PATH */
#define VOLUME_PREFIX _T("\\\\?\\Volume")
#define VOLUME_PREFIX_LEN ((sizeof(VOLUME_PREFIX) / sizeof(TCHAR)) - 1)
/*
* Maximum number of characters we support using the "\\?\" syntax
* (0x7FFF + 1 for nullptr terminator)
*/
#define PATHCCH_MAX_CCH 0x8000
WINPR_API HRESULT PathCchAddBackslashA(PSTR pszPath, size_t cchPath);
WINPR_API HRESULT PathCchAddBackslashW(PWSTR pszPath, size_t cchPath);
WINPR_API HRESULT PathCchRemoveBackslashA(PSTR pszPath, size_t cchPath);
WINPR_API HRESULT PathCchRemoveBackslashW(PWSTR pszPath, size_t cchPath);
WINPR_API HRESULT PathCchAddBackslashExA(PSTR pszPath, size_t cchPath, PSTR* ppszEnd,
size_t* pcchRemaining);
WINPR_API HRESULT PathCchAddBackslashExW(PWSTR pszPath, size_t cchPath, PWSTR* ppszEnd,
size_t* pcchRemaining);
WINPR_API HRESULT PathCchRemoveBackslashExA(PSTR pszPath, size_t cchPath, PSTR* ppszEnd,
size_t* pcchRemaining);
WINPR_API HRESULT PathCchRemoveBackslashExW(PWSTR pszPath, size_t cchPath, PWSTR* ppszEnd,
size_t* pcchRemaining);
WINPR_API HRESULT PathCchAddExtensionA(PSTR pszPath, size_t cchPath, PCSTR pszExt);
WINPR_API HRESULT PathCchAddExtensionW(PWSTR pszPath, size_t cchPath, PCWSTR pszExt);
WINPR_API HRESULT PathCchAppendA(PSTR pszPath, size_t cchPath, PCSTR pszMore);
WINPR_API HRESULT PathCchAppendW(PWSTR pszPath, size_t cchPath, PCWSTR pszMore);
WINPR_API HRESULT PathCchAppendExA(PSTR pszPath, size_t cchPath, PCSTR pszMore,
unsigned long dwFlags);
WINPR_API HRESULT PathCchAppendExW(PWSTR pszPath, size_t cchPath, PCWSTR pszMore,
unsigned long dwFlags);
WINPR_API HRESULT PathCchCanonicalizeA(PSTR pszPathOut, size_t cchPathOut, PCSTR pszPathIn);
WINPR_API HRESULT PathCchCanonicalizeW(PWSTR pszPathOut, size_t cchPathOut, PCWSTR pszPathIn);
WINPR_API HRESULT PathCchCanonicalizeExA(PSTR pszPathOut, size_t cchPathOut, PCSTR pszPathIn,
unsigned long dwFlags);
WINPR_API HRESULT PathCchCanonicalizeExW(PWSTR pszPathOut, size_t cchPathOut, PCWSTR pszPathIn,
unsigned long dwFlags);
WINPR_API HRESULT PathAllocCanonicalizeA(PCSTR pszPathIn, unsigned long dwFlags,
PSTR* ppszPathOut);
WINPR_API HRESULT PathAllocCanonicalizeW(PCWSTR pszPathIn, unsigned long dwFlags,
PWSTR* ppszPathOut);
WINPR_API HRESULT PathCchCombineA(PSTR pszPathOut, size_t cchPathOut, PCSTR pszPathIn,
PCSTR pszMore);
WINPR_API HRESULT PathCchCombineW(PWSTR pszPathOut, size_t cchPathOut, PCWSTR pszPathIn,
PCWSTR pszMore);
WINPR_API HRESULT PathCchCombineExA(PSTR pszPathOut, size_t cchPathOut, PCSTR pszPathIn,
PCSTR pszMore, unsigned long dwFlags);
WINPR_API HRESULT PathCchCombineExW(PWSTR pszPathOut, size_t cchPathOut, PCWSTR pszPathIn,
PCWSTR pszMore, unsigned long dwFlags);
WINPR_API HRESULT PathAllocCombineA(PCSTR pszPathIn, PCSTR pszMore, unsigned long dwFlags,
PSTR* ppszPathOut);
WINPR_API HRESULT PathAllocCombineW(PCWSTR pszPathIn, PCWSTR pszMore, unsigned long dwFlags,
PWSTR* ppszPathOut);
WINPR_API HRESULT PathCchFindExtensionA(PCSTR pszPath, size_t cchPath, PCSTR* ppszExt);
WINPR_API HRESULT PathCchFindExtensionW(PCWSTR pszPath, size_t cchPath, PCWSTR* ppszExt);
WINPR_API HRESULT PathCchRenameExtensionA(PSTR pszPath, size_t cchPath, PCSTR pszExt);
WINPR_API HRESULT PathCchRenameExtensionW(PWSTR pszPath, size_t cchPath, PCWSTR pszExt);
WINPR_API HRESULT PathCchRemoveExtensionA(PSTR pszPath, size_t cchPath);
WINPR_API HRESULT PathCchRemoveExtensionW(PWSTR pszPath, size_t cchPath);
WINPR_API BOOL PathCchIsRootA(PCSTR pszPath);
WINPR_API BOOL PathCchIsRootW(PCWSTR pszPath);
WINPR_API BOOL PathIsUNCExA(PCSTR pszPath, PCSTR* ppszServer);
WINPR_API BOOL PathIsUNCExW(PCWSTR pszPath, PCWSTR* ppszServer);
WINPR_API HRESULT PathCchSkipRootA(PCSTR pszPath, PCSTR* ppszRootEnd);
WINPR_API HRESULT PathCchSkipRootW(PCWSTR pszPath, PCWSTR* ppszRootEnd);
WINPR_API HRESULT PathCchStripToRootA(PSTR pszPath, size_t cchPath);
WINPR_API HRESULT PathCchStripToRootW(PWSTR pszPath, size_t cchPath);
WINPR_API HRESULT PathCchStripPrefixA(PSTR pszPath, size_t cchPath);
WINPR_API HRESULT PathCchStripPrefixW(PWSTR pszPath, size_t cchPath);
WINPR_API HRESULT PathCchRemoveFileSpecA(PSTR pszPath, size_t cchPath);
WINPR_API HRESULT PathCchRemoveFileSpecW(PWSTR pszPath, size_t cchPath);
#ifdef UNICODE
#define PathCchAddBackslash PathCchAddBackslashW
#define PathCchRemoveBackslash PathCchRemoveBackslashW
#define PathCchAddBackslashEx PathCchAddBackslashExW
#define PathCchRemoveBackslashEx PathCchRemoveBackslashExW
#define PathCchAddExtension PathCchAddExtensionW
#define PathCchAppend PathCchAppendW
#define PathCchAppendEx PathCchAppendExW
#define PathCchCanonicalize PathCchCanonicalizeW
#define PathCchCanonicalizeEx PathCchCanonicalizeExW
#define PathAllocCanonicalize PathAllocCanonicalizeW
#define PathCchCombine PathCchCombineW
#define PathCchCombineEx PathCchCombineExW
#define PathAllocCombine PathAllocCombineW
#define PathCchFindExtension PathCchFindExtensionW
#define PathCchRenameExtension PathCchRenameExtensionW
#define PathCchRemoveExtension PathCchRemoveExtensionW
#define PathCchIsRoot PathCchIsRootW
#define PathIsUNCEx PathIsUNCExW
#define PathCchSkipRoot PathCchSkipRootW
#define PathCchStripToRoot PathCchStripToRootW
#define PathCchStripPrefix PathCchStripPrefixW
#define PathCchRemoveFileSpec PathCchRemoveFileSpecW
#else
#define PathCchAddBackslash PathCchAddBackslashA
#define PathCchRemoveBackslash PathCchRemoveBackslashA
#define PathCchAddBackslashEx PathCchAddBackslashExA
#define PathCchRemoveBackslashEx PathCchRemoveBackslashExA
#define PathCchAddExtension PathCchAddExtensionA
#define PathCchAppend PathCchAppendA
#define PathCchAppendEx PathCchAppendExA
#define PathCchCanonicalize PathCchCanonicalizeA
#define PathCchCanonicalizeEx PathCchCanonicalizeExA
#define PathAllocCanonicalize PathAllocCanonicalizeA
#define PathCchCombine PathCchCombineA
#define PathCchCombineEx PathCchCombineExA
#define PathAllocCombine PathAllocCombineA
#define PathCchFindExtension PathCchFindExtensionA
#define PathCchRenameExtension PathCchRenameExtensionA
#define PathCchRemoveExtension PathCchRemoveExtensionA
#define PathCchIsRoot PathCchIsRootA
#define PathIsUNCEx PathIsUNCExA
#define PathCchSkipRoot PathCchSkipRootA
#define PathCchStripToRoot PathCchStripToRootA
#define PathCchStripPrefix PathCchStripPrefixA
#define PathCchRemoveFileSpec PathCchRemoveFileSpecA
#endif
/* Unix-style Paths */
WINPR_API HRESULT PathCchAddSlashA(PSTR pszPath, size_t cchPath);
WINPR_API HRESULT PathCchAddSlashW(PWSTR pszPath, size_t cchPath);
WINPR_API HRESULT PathCchAddSlashExA(PSTR pszPath, size_t cchPath, PSTR* ppszEnd,
size_t* pcchRemaining);
WINPR_API HRESULT PathCchAddSlashExW(PWSTR pszPath, size_t cchPath, PWSTR* ppszEnd,
size_t* pcchRemaining);
WINPR_API HRESULT UnixPathCchAddExtensionA(PSTR pszPath, size_t cchPath, PCSTR pszExt);
WINPR_API HRESULT UnixPathCchAddExtensionW(PWSTR pszPath, size_t cchPath, PCWSTR pszExt);
WINPR_API HRESULT UnixPathCchAppendA(PSTR pszPath, size_t cchPath, PCSTR pszMore);
WINPR_API HRESULT UnixPathCchAppendW(PWSTR pszPath, size_t cchPath, PCWSTR pszMore);
WINPR_API HRESULT UnixPathAllocCombineA(PCSTR pszPathIn, PCSTR pszMore, unsigned long dwFlags,
PSTR* ppszPathOut);
WINPR_API HRESULT UnixPathAllocCombineW(PCWSTR pszPathIn, PCWSTR pszMore, unsigned long dwFlags,
PWSTR* ppszPathOut);
#ifdef UNICODE
#define PathCchAddSlash PathCchAddSlashW
#define PathCchAddSlashEx PathCchAddSlashExW
#define UnixPathCchAddExtension UnixPathCchAddExtensionW
#define UnixPathCchAppend UnixPathCchAppendW
#define UnixPathAllocCombine UnixPathAllocCombineW
#else
#define PathCchAddSlash PathCchAddSlashA
#define PathCchAddSlashEx PathCchAddSlashExA
#define UnixPathCchAddExtension UnixPathCchAddExtensionA
#define UnixPathCchAppend UnixPathCchAppendA
#define UnixPathAllocCombine UnixPathAllocCombineA
#endif
/* Native-style Paths */
WINPR_API HRESULT PathCchAddSeparatorA(PSTR pszPath, size_t cchPath);
WINPR_API HRESULT PathCchAddSeparatorW(PWSTR pszPath, size_t cchPath);
WINPR_API HRESULT PathCchAddSeparatorExA(PSTR pszPath, size_t cchPath, PSTR* ppszEnd,
size_t* pcchRemaining);
WINPR_API HRESULT PathCchAddSeparatorExW(PWSTR pszPath, size_t cchPath, PWSTR* ppszEnd,
size_t* pcchRemaining);
WINPR_API HRESULT NativePathCchAddExtensionA(PSTR pszPath, size_t cchPath, PCSTR pszExt);
WINPR_API HRESULT NativePathCchAddExtensionW(PWSTR pszPath, size_t cchPath, PCWSTR pszExt);
WINPR_API HRESULT NativePathCchAppendA(PSTR pszPath, size_t cchPath, PCSTR pszMore);
WINPR_API HRESULT NativePathCchAppendW(PWSTR pszPath, size_t cchPath, PCWSTR pszMore);
WINPR_API HRESULT NativePathAllocCombineA(PCSTR pszPathIn, PCSTR pszMore, unsigned long dwFlags,
PSTR* ppszPathOut);
WINPR_API HRESULT NativePathAllocCombineW(PCWSTR pszPathIn, PCWSTR pszMore,
unsigned long dwFlags, PWSTR* ppszPathOut);
#ifdef UNICODE
#define PathCchAddSeparator PathCchAddSeparatorW
#define PathCchAddSeparatorEx PathCchAddSeparatorExW
#define NativePathCchAddExtension NativePathCchAddExtensionW
#define NativePathCchAppend NativePathCchAppendW
#define NativePathAllocCombine NativePathAllocCombineW
#else
#define PathCchAddSeparator PathCchAddSeparatorA
#define PathCchAddSeparatorEx PathCchAddSeparatorExA
#define NativePathCchAddExtension NativePathCchAddExtensionA
#define NativePathCchAppend NativePathCchAppendA
#define NativePathAllocCombine NativePathAllocCombineA
#endif
/* Path Portability Functions */
#define PATH_STYLE_WINDOWS 0x00000001
#define PATH_STYLE_UNIX 0x00000002
#define PATH_STYLE_NATIVE 0x00000003
#define PATH_SHARED_LIB_EXT_WITH_DOT 0x00000001
#define PATH_SHARED_LIB_EXT_APPLE_SO 0x00000002
#define PATH_SHARED_LIB_EXT_EXPLICIT 0x80000000
#define PATH_SHARED_LIB_EXT_EXPLICIT_DLL 0x80000001
#define PATH_SHARED_LIB_EXT_EXPLICIT_SO 0x80000002
#define PATH_SHARED_LIB_EXT_EXPLICIT_DYLIB 0x80000003
WINPR_API HRESULT PathCchConvertStyleA(PSTR pszPath, size_t cchPath, unsigned long dwFlags);
WINPR_API HRESULT PathCchConvertStyleW(PWSTR pszPath, size_t cchPath, unsigned long dwFlags);
WINPR_API char PathGetSeparatorA(unsigned long dwFlags);
WINPR_API WCHAR PathGetSeparatorW(unsigned long dwFlags);
WINPR_API PCSTR PathGetSharedLibraryExtensionA(unsigned long dwFlags);
WINPR_API PCWSTR PathGetSharedLibraryExtensionW(unsigned long dwFlags);
#ifdef UNICODE
#define PathCchConvertStyle PathCchConvertStyleW
#define PathGetSeparator PathGetSeparatorW
#define PathGetSharedLibraryExtension PathGetSharedLibraryExtensionW
#else
#define PathCchConvertStyle PathCchConvertStyleA
#define PathGetSeparator PathGetSeparatorW
#define PathGetSharedLibraryExtension PathGetSharedLibraryExtensionA
#endif
#ifdef __cplusplus
}
#endif
#endif
/**
* Shell Path Functions
*/
typedef enum
{
KNOWN_PATH_HOME = 1,
KNOWN_PATH_TEMP = 2,
KNOWN_PATH_XDG_DATA_HOME = 3,
KNOWN_PATH_XDG_CONFIG_HOME = 4,
KNOWN_PATH_XDG_CACHE_HOME = 5,
KNOWN_PATH_XDG_RUNTIME_DIR = 6,
KNOWN_PATH_SYSTEM_CONFIG_HOME = 7
} eKnownPathTypes;
#ifdef __cplusplus
extern "C"
{
#endif
/** @brief Return the absolute path of a configuration file (the path of the configuration
* directory if \b filename is \b nullptr)
*
* @param system a boolean indicating the configuration base, \b TRUE for system configuration,
* \b FALSE for user configuration
* @param filename an optional configuration file name to append.
*
* @return The absolute path of the desired configuration or \b nullptr in case of failure. Use
* \b free to clean up the allocated string.
*
*
* @since version 3.9.0
*/
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* winpr_GetConfigFilePath(BOOL system, const char* filename);
/** @brief Get a config file sub path with a formatting argument constructing the filename
*
* @param system \b TRUE to return a system config path
* @param filename The format string to generate the filename. Must not be \b nullptr. Must not
* contain any forbidden characters.
*
* @return A (absolute) configuration file path or \b nullptr in case of failure.
* @since version 3.23.0
*/
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_ATTR_FORMAT_ARG(2, 3)
WINPR_API char* winpr_GetConfigFilePathV(BOOL system, WINPR_FORMAT_ARG const char* filename,
...);
/** @brief Get a config file sub path with a formatting argument constructing the filename
*
* @param system \b TRUE to return a system config path
* @param filename The format string to generate the filename. Must not be \b nullptr. Must not
* contain any forbidden characters.
* @param ap The argument list
*
* @return A (absolute) configuration file path or \b nullptr in case of failure.
* @since version 3.23.0
*/
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_ATTR_FORMAT_ARG(2, 0)
WINPR_API char* winpr_GetConfigFilePathVA(BOOL system, WINPR_FORMAT_ARG const char* filename,
va_list ap);
WINPR_API const char* GetKnownPathIdString(int id);
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* GetKnownPath(eKnownPathTypes id);
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* GetKnownSubPath(eKnownPathTypes id, const char* path);
/** @brief Append a path to some existing known path type.
*
* @param id a \ref eKnownPathTypes known path id
* @param path the format string generating the subpath. Must not be \b nullptr
*
* @return A string of combined \b id path and \b path or \b nullptr in case of an error.
* @since version 3.23.0
*/
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_ATTR_FORMAT_ARG(2, 3)
WINPR_API char* GetKnownSubPathV(eKnownPathTypes id, const char* path, ...);
/** @brief Append a path to some existing known path type.
*
* @param id a \ref eKnownPathTypes known path id
* @param path the format string generating the subpath. Must not be \b nullptr
* @param ap a va_list containing the format string arguments
* * @return A string of combined \b basePath and \b path or \b nullptr in case of
* an error.
* * @version since 3.23.0
*/
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_ATTR_FORMAT_ARG(2, 0)
WINPR_API char* GetKnownSubPathVA(eKnownPathTypes id, const char* path, va_list ap);
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* GetEnvironmentPath(char* name);
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* GetEnvironmentSubPath(char* name, const char* path);
/** @brief Append a path to some existing environment name.
*
* @param name The prefix path to use, must not be \b nullptr
* @param path A format string used to generate the path to append. Must not be \b nullptr
*
* @return A string of combined \b basePath and \b path or \b nullptr in case of an error.
* @version since 3.23.0
*/
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_ATTR_FORMAT_ARG(2, 3)
WINPR_API char* GetEnvironmentSubPathV(char* name, WINPR_FORMAT_ARG const char* path, ...);
/** @brief Append a path to some existing environment name.
*
* @param name The prefix path to use, must not be \b nullptr
* @param path A format string used to generate the path to append. Must not be \b nullptr
* @param ap a va_list containing the format string arguments
*
* @return A string of combined \b basePath and \b path or \b nullptr in case of an
* error.
* * @version since 3.23.0
*/
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_ATTR_FORMAT_ARG(2, 0)
WINPR_API char* GetEnvironmentSubPathVA(char* name, WINPR_FORMAT_ARG const char* path,
va_list ap);
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* GetCombinedPath(const char* basePath, const char* subPath);
/** @brief Append a path to some existing path. A system dependent path separator will be added
* automatically.
*
* @bug before version 3.23.0 the function did not allow subPath to be a format string.
*
* @param basePath The prefix path to use, must not be \b nullptr
* @param subPathFmt A format string used to generate the path to append. Must not be \b
* nullptr
*
* @return A string of combined \b basePath and \b subPathFmt or \b nullptr in case of an
* error.
*/
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_ATTR_FORMAT_ARG(2, 3)
WINPR_API char* GetCombinedPathV(const char* basePath, WINPR_FORMAT_ARG const char* subPathFmt,
...);
/** @brief Append a path to some existing path. A system dependent path separator will be added
* automatically.
*
* @param basePath The prefix path to use, must not be \b nullptr
* @param subPathFmt A format string used to generate the path to append. Must not be \b
* nullptr
* @param ap a va_list containing the format string arguments
*
* @return A string of combined \b basePath and \b subPathFmt or \b nullptr in case of an
* error.
* @version since 3.23.0
*/
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_ATTR_FORMAT_ARG(2, 0)
WINPR_API char* GetCombinedPathVA(const char* basePath, WINPR_FORMAT_ARG const char* subPathFmt,
va_list ap);
WINPR_API BOOL PathMakePathA(LPCSTR path, LPSECURITY_ATTRIBUTES lpAttributes);
WINPR_API BOOL PathMakePathW(LPCWSTR path, LPSECURITY_ATTRIBUTES lpAttributes);
#if !defined(_WIN32) || defined(_UWP)
WINPR_API BOOL PathIsRelativeA(LPCSTR pszPath);
WINPR_API BOOL PathIsRelativeW(LPCWSTR pszPath);
WINPR_API BOOL PathFileExistsA(LPCSTR pszPath);
WINPR_API BOOL PathFileExistsW(LPCWSTR pszPath);
WINPR_API BOOL PathIsDirectoryEmptyA(LPCSTR pszPath);
WINPR_API BOOL PathIsDirectoryEmptyW(LPCWSTR pszPath);
#ifdef UNICODE
#define PathFileExists PathFileExistsW
#define PathIsDirectoryEmpty PathIsDirectoryEmptyW
#else
#define PathFileExists PathFileExistsA
#define PathIsDirectoryEmpty PathIsDirectoryEmptyA
#endif
#endif
WINPR_API BOOL winpr_MoveFile(LPCSTR lpExistingFileName, LPCSTR lpNewFileName);
WINPR_API BOOL winpr_MoveFileEx(LPCSTR lpExistingFileName, LPCSTR lpNewFileName, DWORD dwFlags);
WINPR_API BOOL winpr_DeleteFile(const char* lpFileName);
WINPR_API BOOL winpr_RemoveDirectory(LPCSTR lpPathName);
WINPR_API BOOL winpr_RemoveDirectory_RecursiveA(LPCSTR lpPathName);
WINPR_API BOOL winpr_RemoveDirectory_RecursiveW(LPCWSTR lpPathName);
WINPR_API BOOL winpr_PathFileExists(const char* pszPath);
WINPR_API BOOL winpr_PathMakePath(const char* path, LPSECURITY_ATTRIBUTES lpAttributes);
#ifdef __cplusplus
}
#endif
#ifdef _WIN32
#include <shlwapi.h>
#endif
#endif /* WINPR_PATH_H */

View File

@@ -0,0 +1,132 @@
/**
* WinPR: Windows Portable Runtime
* Pipe Functions
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_PIPE_H
#define WINPR_PIPE_H
#include <winpr/file.h>
#include <winpr/winpr.h>
#include <winpr/error.h>
#include <winpr/handle.h>
#include <winpr/wtypes.h>
#ifndef _WIN32
#define PIPE_UNLIMITED_INSTANCES 0xFF
#define PIPE_ACCESS_INBOUND 0x00000001
#define PIPE_ACCESS_OUTBOUND 0x00000002
#define PIPE_ACCESS_DUPLEX 0x00000003
#define FILE_FLAG_FIRST_PIPE_INSTANCE 0x00080000
#define FILE_FLAG_WRITE_THROUGH 0x80000000
#define FILE_FLAG_OVERLAPPED 0x40000000
#define PIPE_CLIENT_END 0x00000000
#define PIPE_SERVER_END 0x00000001
#define PIPE_TYPE_BYTE 0x00000000
#define PIPE_TYPE_MESSAGE 0x00000004
#define PIPE_READMODE_BYTE 0x00000000
#define PIPE_READMODE_MESSAGE 0x00000002
#define PIPE_WAIT 0x00000000
#define PIPE_NOWAIT 0x00000001
#define PIPE_ACCEPT_REMOTE_CLIENTS 0x00000000
#define PIPE_REJECT_REMOTE_CLIENTS 0x00000008
#define NMPWAIT_USE_DEFAULT_WAIT 0x00000000
#define NMPWAIT_NOWAIT 0x00000001
#define NMPWAIT_WAIT_FOREVER 0xFFFFFFFF
#ifdef __cplusplus
extern "C"
{
#endif
/**
* Unnamed pipe
*/
WINPR_API BOOL CreatePipe(PHANDLE hReadPipe, PHANDLE hWritePipe,
LPSECURITY_ATTRIBUTES lpPipeAttributes, DWORD nSize);
/**
* Named pipe
*/
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateNamedPipeA(LPCSTR lpName, DWORD dwOpenMode, DWORD dwPipeMode,
DWORD nMaxInstances, DWORD nOutBufferSize,
DWORD nInBufferSize, DWORD nDefaultTimeOut,
LPSECURITY_ATTRIBUTES lpSecurityAttributes);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateNamedPipeW(LPCWSTR lpName, DWORD dwOpenMode, DWORD dwPipeMode,
DWORD nMaxInstances, DWORD nOutBufferSize,
DWORD nInBufferSize, DWORD nDefaultTimeOut,
LPSECURITY_ATTRIBUTES lpSecurityAttributes);
WINPR_API BOOL ConnectNamedPipe(HANDLE hNamedPipe, LPOVERLAPPED lpOverlapped);
WINPR_API BOOL DisconnectNamedPipe(HANDLE hNamedPipe);
WINPR_API BOOL PeekNamedPipe(HANDLE hNamedPipe, LPVOID lpBuffer, DWORD nBufferSize,
LPDWORD lpBytesRead, LPDWORD lpTotalBytesAvail,
LPDWORD lpBytesLeftThisMessage);
WINPR_API BOOL TransactNamedPipe(HANDLE hNamedPipe, LPVOID lpInBuffer, DWORD nInBufferSize,
LPVOID lpOutBuffer, DWORD nOutBufferSize, LPDWORD lpBytesRead,
LPOVERLAPPED lpOverlapped);
WINPR_API BOOL WaitNamedPipeA(LPCSTR lpNamedPipeName, DWORD nTimeOut);
WINPR_API BOOL WaitNamedPipeW(LPCWSTR lpNamedPipeName, DWORD nTimeOut);
WINPR_API BOOL SetNamedPipeHandleState(HANDLE hNamedPipe, LPDWORD lpMode,
LPDWORD lpMaxCollectionCount,
LPDWORD lpCollectDataTimeout);
WINPR_API BOOL ImpersonateNamedPipeClient(HANDLE hNamedPipe);
WINPR_API BOOL GetNamedPipeClientComputerNameA(HANDLE Pipe, LPCSTR ClientComputerName,
ULONG ClientComputerNameLength);
WINPR_API BOOL GetNamedPipeClientComputerNameW(HANDLE Pipe, LPCWSTR ClientComputerName,
ULONG ClientComputerNameLength);
#ifdef UNICODE
#define CreateNamedPipe CreateNamedPipeW
#define WaitNamedPipe WaitNamedPipeW
#define GetNamedPipeClientComputerName GetNamedPipeClientComputerNameW
#else
#define CreateNamedPipe CreateNamedPipeA
#define WaitNamedPipe WaitNamedPipeA
#define GetNamedPipeClientComputerName GetNamedPipeClientComputerNameA
#endif
#ifdef __cplusplus
}
#endif
#endif
#endif /* WINPR_PIPE_H */

View File

@@ -0,0 +1,708 @@
/**
* WinPR: Windows Portable Runtime
* Platform-Specific Definitions
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_PLATFORM_H
#define WINPR_PLATFORM_H
#include <stdlib.h>
/* MSVC only defines _Pragma if you compile with /std:c11 with no extensions
* see
* https://learn.microsoft.com/en-us/cpp/preprocessor/pragma-directives-and-the-pragma-keyword?view=msvc-170#the-pragma-preprocessing-operator
*/
#if !defined(_MSC_VER)
#define WINPR_DO_PRAGMA(x) _Pragma(#x)
#else
#define WINPR_DO_PRAGMA(x) __pragma(#x)
#endif
/* COVERITY_BUILD must be defined by build system */
#if !defined(COVERITY_BUILD)
#define WINPR_DO_COVERITY_PRAGMA(x)
#else
#define WINPR_DO_COVERITY_PRAGMA(x) WINPR_DO_PRAGMA(x)
#endif
#if defined(__GNUC__)
#define WINPR_PRAGMA_WARNING(msg) WINPR_DO_PRAGMA(GCC warning #msg)
#elif defined(__clang__)
#define WINPR_PRAGMA_WARNING(msg) WINPR_DO_PRAGMA(GCC warning #msg)
#elif defined(_MSC_VER) && (_MSC_VER >= 1920)
#define WINPR_PRAGMA_WARNING(msg) WINPR_DO_PRAGMA(message \x28 #msg \x29)
#else
#define WINPR_PRAGMA_WARNING(msg)
#endif
// C99 related macros
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
#define WINPR_RESTRICT restrict
#elif defined(_MSC_VER) && _MSC_VER >= 1900
#define WINPR_RESTRICT __restrict
#else
#define WINPR_RESTRICT
#endif
// C23 related macros
#if defined(__cplusplus) && (__cplusplus >= 201703L)
#define WINPR_FALLTHROUGH \
(void)0; \
[[fallthrough]];
#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L)
#define WINPR_FALLTHROUGH \
(void)0; \
[[fallthrough]];
#elif defined(__clang__)
#define WINPR_FALLTHROUGH \
(void)0; \
__attribute__((fallthrough));
#elif defined(__GNUC__) && (__GNUC__ >= 7)
#define WINPR_FALLTHROUGH \
(void)0; \
__attribute__((fallthrough));
#else
#define WINPR_FALLTHROUGH (void)0;
#endif
#if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202003L)) || defined(__cplusplus)
#define WINPR_C_ARRAY_INIT \
{ \
} /** @since version 3.24.0 */
#else
#define WINPR_C_ARRAY_INIT { 0 } /** @since version 3.24.0 */
#define nullptr NULL /** @since version 3.24.0 */
#endif
#if defined(WINPR_DEFINE_ATTR_NODISCARD)
#if defined(__cplusplus) && (__cplusplus >= 201703L)
#define WINPR_ATTR_NODISCARD [[nodiscard]]
#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L)
#define WINPR_ATTR_NODISCARD [[nodiscard]]
#elif defined(__clang__)
#define WINPR_ATTR_NODISCARD __attribute__((warn_unused_result))
#elif defined(__GNUC__) && (__GNUC__ >= 7)
#define WINPR_ATTR_NODISCARD __attribute__((warn_unused_result))
#else
#define WINPR_ATTR_NODISCARD
#endif
#else
#define WINPR_ATTR_NODISCARD
#endif
/* GCC does not like [[nodiscard]] on function pointers.
* it does not complain when using attribute syntax thoug...
*/
#if defined(__GNUC__) && !defined(__clang__)
#undef WINPR_ATTR_NODISCARD
#define WINPR_ATTR_NODISCARD __attribute__((warn_unused_result))
#endif
#if defined(__clang__)
#define WINPR_PRAGMA_DIAG_PUSH WINPR_DO_PRAGMA(clang diagnostic push)
#define WINPR_PRAGMA_DIAG_IGNORED_OVERLENGTH_STRINGS \
WINPR_DO_PRAGMA(clang diagnostic ignored "-Woverlength-strings") /** @since version 3.9.0 \
*/
#define WINPR_PRAGMA_DIAG_IGNORED_QUALIFIERS
/* unsupported by clang WINPR_DO_PRAGMA(clang diagnostic ignored "-Wdiscarded-qualifiers") */ /** @since version 3.9.0 */
#define WINPR_PRAGMA_DIAG_IGNORED_PEDANTIC WINPR_DO_PRAGMA(clang diagnostic ignored "-Wpedantic")
#define WINPR_PRAGMA_DIAG_IGNORED_MISSING_PROTOTYPES \
WINPR_DO_PRAGMA(clang diagnostic ignored "-Wmissing-prototypes")
#define WINPR_PRAGMA_DIAG_IGNORED_STRICT_PROTOTYPES \
WINPR_DO_PRAGMA(clang diagnostic ignored "-Wstrict-prototypes")
#define WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO \
WINPR_DO_PRAGMA(clang diagnostic ignored "-Wreserved-id-macro")
#define WINPR_PRAGMA_DIAG_IGNORED_UNUSED_MACRO \
WINPR_DO_PRAGMA(clang diagnostic ignored "-Wunused-macros")
#define WINPR_PRAGMA_DIAG_IGNORED_UNKNOWN_PRAGMAS \
WINPR_DO_PRAGMA(clang diagnostic ignored "-Wunknown-pragmas") /** @since version 3.10.0 */
#define WINPR_PRAGMA_DIAG_IGNORED_DEPRECATED_DECL \
WINPR_DO_PRAGMA(clang diagnostic ignored \
"-Wdeprecated-declarations") /** @since version 3.17.2 */
#if __clang_major__ >= 13
#define WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER \
WINPR_DO_PRAGMA(clang diagnostic ignored "-Wreserved-identifier")
#else
#define WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER
#endif
#define WINPR_PRAGMA_DIAG_IGNORED_ATOMIC_SEQ_CST \
WINPR_DO_PRAGMA(clang diagnostic ignored "-Watomic-implicit-seq-cst")
#define WINPR_PRAGMA_DIAG_IGNORED_UNUSED_CONST_VAR \
WINPR_DO_PRAGMA(clang diagnostic ignored "-Wunused-const-variable")
#define WINPR_PRAGMA_DIAG_IGNORED_FORMAT_SECURITY \
WINPR_DO_PRAGMA(clang diagnostic ignored "-Wformat-security")
#define WINPR_PRAGMA_DIAG_TAUTOLOGICAL_CONSTANT_OUT_OF_RANGE_COMPARE \
WINPR_DO_PRAGMA(clang diagnostic ignored \
"-Wtautological-constant-out-of-range-compare") /** @since \
version \
3.9.0 \
*/
#if __clang_major__ >= 12
#define WINPR_PRAGMA_DIAG_TAUTOLOGICAL_VALUE_RANGE_COMPARE \
WINPR_DO_PRAGMA(clang diagnostic ignored \
"-Wtautological-value-range-compare") /** @since \
version 3.10.0 */
#else
#define WINPR_PRAGMA_DIAG_TAUTOLOGICAL_VALUE_RANGE_COMPARE
#endif
#define WINPR_PRAGMA_DIAG_IGNORED_FORMAT_NONLITERAL \
WINPR_DO_PRAGMA(clang diagnostic ignored "-Wformat-nonliteral") /** @since version 3.9.0 \
*/
#define WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC /** @since version 3.3.0 */ /* not \
supported WINPR_DO_PRAGMA(clang diagnostic ignored "-Wmismatched-dealloc") */
#define WINPR_PRAGMA_DIAG_POP WINPR_DO_PRAGMA(clang diagnostic pop)
#define WINPR_PRAGMA_UNROLL_LOOP \
_Pragma("clang loop vectorize_width(8) interleave_count(8)") /** @since version 3.6.0 \
*/
#elif defined(__GNUC__)
#define WINPR_PRAGMA_DIAG_PUSH WINPR_DO_PRAGMA(GCC diagnostic push)
#define WINPR_PRAGMA_DIAG_IGNORED_OVERLENGTH_STRINGS \
WINPR_DO_PRAGMA(GCC diagnostic ignored "-Woverlength-strings") /** @since version 3.9.0 */
#define WINPR_PRAGMA_DIAG_IGNORED_QUALIFIERS \
WINPR_DO_PRAGMA(GCC diagnostic ignored "-Wdiscarded-qualifiers") /** @since version 3.9.0 \
*/
#define WINPR_PRAGMA_DIAG_IGNORED_PEDANTIC WINPR_DO_PRAGMA(GCC diagnostic ignored "-Wpedantic")
#define WINPR_PRAGMA_DIAG_IGNORED_MISSING_PROTOTYPES \
WINPR_DO_PRAGMA(GCC diagnostic ignored "-Wmissing-prototypes")
#define WINPR_PRAGMA_DIAG_IGNORED_STRICT_PROTOTYPES \
WINPR_DO_PRAGMA(GCC diagnostic ignored "-Wstrict-prototypes")
#define WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO /* not supported WINPR_DO_PRAGMA(GCC \
diagnostic ignored \
"-Wreserved-id-macro") \
*/
#define WINPR_PRAGMA_DIAG_IGNORED_UNUSED_MACRO \
WINPR_DO_PRAGMA(GCC diagnostic ignored "-Wunused-macros")
#define WINPR_PRAGMA_DIAG_IGNORED_UNKNOWN_PRAGMAS \
WINPR_DO_PRAGMA(GCC diagnostic ignored "-Wunknown-pragmas") /** @since version 3.10.0 */
#define WINPR_PRAGMA_DIAG_IGNORED_DEPRECATED_DECL \
WINPR_DO_PRAGMA(GCC diagnostic ignored "-Wdeprecated-declarations") /** @since version 3.17.2 \
*/
#define WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER
/* not supported WINPR_DO_PRAGMA(GCC diagnostic ignored "-Wreserved-identifier") */
#define WINPR_PRAGMA_DIAG_IGNORED_ATOMIC_SEQ_CST /* not supported WINPR_DO_PRAGMA(GCC \
diagnostic ignored \
"-Watomic-implicit-seq-cst") */
#define WINPR_PRAGMA_DIAG_IGNORED_UNUSED_CONST_VAR \
WINPR_DO_PRAGMA(GCC diagnostic ignored "-Wunused-const-variable")
#define WINPR_PRAGMA_DIAG_IGNORED_FORMAT_SECURITY \
WINPR_DO_PRAGMA(GCC diagnostic ignored "-Wformat-security")
#define WINPR_PRAGMA_DIAG_TAUTOLOGICAL_CONSTANT_OUT_OF_RANGE_COMPARE /* not supported
WINPR_DO_PRAGMA(GCC diagnostic ignored "-Wtautological-constant-out-of-range-compare") */ /** @since version 3.9.0 */
#define WINPR_PRAGMA_DIAG_TAUTOLOGICAL_VALUE_RANGE_COMPARE /* not supported
WINPR_DO_PRAGMA(GCC diagnostic ignored "-Wtautological-value-range-compare") */ /** @since version 3.10.0 */
#define WINPR_PRAGMA_DIAG_IGNORED_FORMAT_NONLITERAL \
WINPR_DO_PRAGMA(GCC diagnostic ignored "-Wformat-nonliteral") /** @since version 3.9.0 */
#if __GNUC__ >= 11
#define WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC \
WINPR_DO_PRAGMA(GCC diagnostic ignored "-Wmismatched-dealloc") /** @since version 3.3.0 */
#else
#define WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
#endif
#define WINPR_PRAGMA_DIAG_POP WINPR_DO_PRAGMA(GCC diagnostic pop)
#define WINPR_PRAGMA_UNROLL_LOOP \
WINPR_DO_PRAGMA(GCC unroll 8) WINPR_DO_PRAGMA(GCC ivdep) /** @since version 3.6.0 */
#else
#define WINPR_PRAGMA_DIAG_PUSH
#define WINPR_PRAGMA_DIAG_IGNORED_PEDANTIC
#define WINPR_PRAGMA_DIAG_IGNORED_QUALIFIERS /** @since version 3.9.0 */
#define WINPR_PRAGMA_DIAG_IGNORED_OVERLENGTH_STRINGS /** @since version 3.9.0 */
#define WINPR_PRAGMA_DIAG_IGNORED_MISSING_PROTOTYPES
#define WINPR_PRAGMA_DIAG_IGNORED_STRICT_PROTOTYPES
#define WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO
#define WINPR_PRAGMA_DIAG_IGNORED_UNUSED_MACRO
#define WINPR_PRAGMA_DIAG_IGNORED_UNKNOWN_PRAGMAS /** @since version 3.10.0 */
#define WINPR_PRAGMA_DIAG_IGNORED_DEPRECATED_DECL /** @since version 3.17.2 */
#define WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER
#define WINPR_PRAGMA_DIAG_IGNORED_ATOMIC_SEQ_CST
#define WINPR_PRAGMA_DIAG_IGNORED_UNUSED_CONST_VAR
#define WINPR_PRAGMA_DIAG_IGNORED_FORMAT_SECURITY
#define WINPR_PRAGMA_DIAG_TAUTOLOGICAL_CONSTANT_OUT_OF_RANGE_COMPARE /** @since version 3.9.0 \
*/
#define WINPR_PRAGMA_DIAG_TAUTOLOGICAL_VALUE_RANGE_COMPARE /** @since version 3.10.0 */
#define WINPR_PRAGMA_DIAG_IGNORED_FORMAT_NONLITERAL /** @since version 3.9.0 */
#define WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC /** @since version 3.3.0 */
#define WINPR_PRAGMA_DIAG_POP
#define WINPR_PRAGMA_UNROLL_LOOP /** @since version 3.6.0 */
#endif
#if defined(MSVC)
#undef WINPR_PRAGMA_UNROLL_LOOP
#define WINPR_PRAGMA_UNROLL_LOOP WINPR_DO_PRAGMA(loop(ivdep)) /** @since version 3.6.0 */
#endif
WINPR_PRAGMA_DIAG_PUSH
WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO
/*
* Processor Architectures:
* http://sourceforge.net/p/predef/wiki/Architectures/
*
* Visual Studio Predefined Macros:
* http://msdn.microsoft.com/en-ca/library/vstudio/b0084kay.aspx
*/
/* Intel x86 (_M_IX86) */
#if defined(i386) || defined(__i386) || defined(__i386__) || defined(__i486__) || \
defined(__i586__) || defined(__i686__) || defined(__X86__) || defined(_X86_) || \
defined(__I86__) || defined(__IA32__) || defined(__THW_INTEL__) || defined(__INTEL__) || \
defined(_M_IX86)
#ifndef _M_IX86
#define _M_IX86 1
#endif
#endif
/* AMD64 (_M_AMD64) */
#if defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || \
defined(_M_X64)
#ifndef _M_AMD64
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _M_AMD64 1
#endif
#endif
/* Intel ia64 */
#if defined(__ia64) || defined(__ia64__) || defined(_M_IA64)
#ifndef _M_IA64
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _M_IA64 1
#endif
#endif
/* Intel x86 or AMD64 (_M_IX86_AMD64) */
#if defined(_M_IX86) || defined(_M_AMD64)
#ifndef _M_IX86_AMD64
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _M_IX86_AMD64 1
#endif
#endif
/* ARM (_M_ARM) */
#if defined(__arm__) || defined(__thumb__) || defined(__TARGET_ARCH_ARM) || \
defined(__TARGET_ARCH_THUMB)
#ifndef _M_ARM
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _M_ARM 1
#endif
#endif
/* ARM64 (_M_ARM64) */
#if defined(__aarch64__)
#ifndef _M_ARM64
#define _M_ARM64 1
#endif
#endif
/* MIPS (_M_MIPS) */
#if defined(mips) || defined(__mips) || defined(__mips__) || defined(__MIPS__)
#ifndef _M_MIPS
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _M_MIPS 1
#endif
#endif
/* MIPS64 (_M_MIPS64) */
#if defined(mips64) || defined(__mips64) || defined(__mips64__) || defined(__MIPS64__)
#ifndef _M_MIPS64
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _M_MIPS64 1
#endif
#endif
/* PowerPC (_M_PPC) */
#if defined(__ppc__) || defined(__powerpc) || defined(__powerpc__) || defined(__POWERPC__) || \
defined(_ARCH_PPC)
#ifndef _M_PPC
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _M_PPC 1
#endif
#endif
/* Intel Itanium (_M_IA64) */
#if defined(__ia64) || defined(__ia64__) || defined(_IA64) || defined(__IA64__)
#ifndef _M_IA64
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _M_IA64 1
#endif
#endif
/* Alpha (_M_ALPHA) */
#if defined(__alpha) || defined(__alpha__)
#ifndef _M_ALPHA
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _M_ALPHA 1
#endif
#endif
/* SPARC (_M_SPARC) */
#if defined(__sparc) || defined(__sparc__)
#ifndef _M_SPARC
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _M_SPARC 1
#endif
#endif
/* E2K (_M_E2K) */
#if defined(__e2k__)
#ifndef _M_E2K
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _M_E2K 1
#endif
#endif
/**
* Operating Systems:
* http://sourceforge.net/p/predef/wiki/OperatingSystems/
*/
/* Windows (_WIN32) */
/* WinRT (_WINRT) */
#if defined(WINAPI_FAMILY)
#if (WINAPI_FAMILY == WINAPI_FAMILY_APP)
#ifndef _WINRT
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _WINRT 1
#endif
#endif
#endif
#if defined(__cplusplus_winrt)
#ifndef _WINRT
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _WINRT 1
#endif
#endif
/* Linux (__linux__) */
#if defined(linux) || defined(__linux)
#ifndef __linux__
#define __linux__ 1
#endif
#endif
/* GNU/Linux (__gnu_linux__) */
/* Apple Platforms (iOS, Mac OS X) */
#if (defined(__APPLE__) && defined(__MACH__))
#include <TargetConditionals.h>
#if (TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)
/* iOS (__IOS__) */
#ifndef __IOS__
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define __IOS__ 1
#endif
#elif (TARGET_OS_MAC == 1)
/* Mac OS X (__MACOSX__) */
#ifndef __MACOSX__
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define __MACOSX__ 1
#endif
#endif
#endif
/* Android (__ANDROID__) */
/* Cygwin (__CYGWIN__) */
/* FreeBSD (__FreeBSD__) */
/* NetBSD (__NetBSD__) */
/* OpenBSD (__OpenBSD__) */
/* DragonFly (__DragonFly__) */
/* Solaris (__sun) */
#if defined(sun)
#ifndef __sun
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define __sun 1
#endif
#endif
/* IRIX (__sgi) */
#if defined(sgi)
#ifndef __sgi
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define __sgi 1
#endif
#endif
/* AIX (_AIX) */
#if defined(__TOS_AIX__)
#ifndef _AIX
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _AIX 1
#endif
#endif
/* HP-UX (__hpux) */
#if defined(hpux) || defined(_hpux)
#ifndef __hpux
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define __hpux 1
#endif
#endif
/* BeOS (__BEOS__) */
/* QNX (__QNXNTO__) */
/**
* Endianness:
* http://sourceforge.net/p/predef/wiki/Endianness/
*/
#if defined(__gnu_linux__)
#include <endian.h>
#endif
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
defined(__DragonFly__) || defined(__APPLE__)
#include <sys/param.h>
#endif
/* Big-Endian */
#ifdef __BYTE_ORDER
#if (__BYTE_ORDER == __BIG_ENDIAN)
#ifndef __BIG_ENDIAN__
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define __BIG_ENDIAN__ 1
#endif
#endif
#else
#if defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || defined(_MIPSEB) || \
defined(__MIPSEB) || defined(__MIPSEB__)
#ifndef __BIG_ENDIAN__
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define __BIG_ENDIAN__ 1
#endif
#endif
#endif /* __BYTE_ORDER */
/* Little-Endian */
#ifdef __BYTE_ORDER
#if (__BYTE_ORDER == __LITTLE_ENDIAN)
#ifndef __LITTLE_ENDIAN__
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define __LITTLE_ENDIAN__ 1
#endif
#endif
#else
#if defined(__ARMEL__) || defined(__THUMBEL__) || defined(__AARCH64EL__) || defined(_MIPSEL) || \
defined(__MIPSEL) || defined(__MIPSEL__) || defined(__e2k__)
#ifndef __LITTLE_ENDIAN__
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define __LITTLE_ENDIAN__ 1
#endif
#endif
#endif /* __BYTE_ORDER */
WINPR_PRAGMA_DIAG_POP
#if defined(__cplusplus) && (__cplusplus >= 201703L)
#define WINPR_DEPRECATED(obj) [[deprecated]] obj
#define WINPR_DEPRECATED_VAR(text, obj) [[deprecated("[deprecated] " text)]] obj
#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L)
#define WINPR_DEPRECATED(obj) [[deprecated]] obj
#define WINPR_DEPRECATED_VAR(text, obj) [[deprecated("[deprecated] " text)]] obj
#elif defined(__GNUC__)
#define WINPR_DEPRECATED(obj) obj __attribute__((deprecated))
#define WINPR_DEPRECATED_VAR(text, obj) obj __attribute__((deprecated("[deprecated] " text)))
#else
#define WINPR_DEPRECATED(obj) obj
#define WINPR_DEPRECATED_VAR(text, obj) obj
#endif
#if defined(__cplusplus) && (__cplusplus >= 201703L)
#define WINPR_NORETURN(obj) [[noreturn]] obj
#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L)
#define WINPR_NORETURN(obj) [[noreturn]] obj
#elif defined(WIN32) && !defined(__CYGWIN__)
#define WINPR_NORETURN(obj) __declspec(noreturn) obj
#elif defined(__GNUC__)
#define WINPR_NORETURN(obj) __attribute__((__noreturn__)) obj
#else
#define WINPR_NORETURN(obj) obj
#endif
#define INLINE inline
#ifdef WINPR_DLL
#if defined _WIN32 || defined __CYGWIN__
#ifdef WINPR_EXPORTS
#ifdef __GNUC__
#define WINPR_API __attribute__((dllexport))
#else
#define WINPR_API __declspec(dllexport)
#endif
#else
#ifdef __GNUC__
#define WINPR_API __attribute__((dllimport))
#else
#define WINPR_API __declspec(dllimport)
#endif
#endif
#else
#if defined(__GNUC__) && (__GNUC__ >= 4)
#if defined(__cplusplus) && (__cplusplus >= 201703L)
#define WINPR_API [[gnu::visibility("default")]]
#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L)
#define WINPR_API [[gnu::visibility("default")]]
#else
#define WINPR_API __attribute__((visibility("default")))
#endif
#else
#define WINPR_API
#endif
#endif
#else /* WINPR_DLL */
#define WINPR_API
#endif
#if defined(__clang__)
#if defined(__cplusplus) && (__cplusplus >= 201703L)
#define WINPR_ATTR_MALLOC(deallocator, ptrindex) \
[[gnu::malloc, nodiscard]] /** @since version 3.3.0 */
#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L)
#define WINPR_ATTR_MALLOC(deallocator, ptrindex) \
[[gnu::malloc, nodiscard]] /** @since version 3.3.0 */
#else
#define WINPR_ATTR_MALLOC(deallocator, ptrindex) \
__attribute__((malloc, warn_unused_result)) /** @since version 3.3.0 */
#endif
#elif defined(__GNUC__)
#if (__GNUC__ <= 10)
#define WINPR_ATTR_MALLOC(deallocator, ptrindex) \
__attribute__((malloc, warn_unused_result)) /** @since version 3.3.0 */
#else
#if defined(__cplusplus) && (__cplusplus >= 201703L)
#define WINPR_ATTR_MALLOC(deallocator, ptrindex) \
[[gnu::malloc(deallocator, ptrindex), nodiscard]] /** @since version 3.3.0 */
#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L)
#define WINPR_ATTR_MALLOC(deallocator, ptrindex) \
[[gnu::malloc(deallocator, ptrindex), nodiscard]] /** @since version 3.3.0 */
#else
#define WINPR_ATTR_MALLOC(deallocator, ptrindex) \
__attribute__((malloc(deallocator, ptrindex), warn_unused_result)) /** @since version 3.3.0 */
#endif
#endif
#elif defined(_MSC_VER)
#define WINPR_ATTR_MALLOC(deallocator, ptrindex) __declspec(restrict) /** @since version 3.3.0 */
#endif
#if defined(__GNUC__) || defined(__clang__)
#define WINPR_ATTR_FORMAT_ARG(pos, args) __attribute__((__format__(__printf__, pos, args)))
#define WINPR_FORMAT_ARG /**/
#elif defined(_MSC_VER)
#define WINPR_ATTR_FORMAT_ARG(pos, args)
#define WINPR_FORMAT_ARG _Printf_format_string_
#endif
#if defined(EXPORT_ALL_SYMBOLS)
#define WINPR_LOCAL WINPR_API
#else
#if defined _WIN32 || defined __CYGWIN__
#define WINPR_LOCAL
#else
#if defined(__GNUC__) && (__GNUC__ >= 4)
#define WINPR_LOCAL __attribute__((visibility("hidden")))
#else
#define WINPR_LOCAL
#endif
#endif
#endif
// WARNING: *do not* use thread-local storage for new code because it is not portable
// It is only used for VirtualChannelInit, and all FreeRDP channels use VirtualChannelInitEx
// The old virtual channel API is only realistically used on Windows where TLS is available
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \
!defined(__STDC_NO_THREADS__) // C11
#include <threads.h>
#define WINPR_TLS thread_local
#elif defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define WINPR_TLS __thread
#else
#define WINPR_TLS __declspec(thread)
#endif
#elif !defined(__IOS__)
#define WINPR_TLS __thread
#else
// thread-local storage is not supported on iOS
// don't warn because it isn't actually used on iOS
#define WINPR_TLS
#endif
#define WINPR_ALIGN64 DECLSPEC_ALIGN(8)
#if defined(__cplusplus) && (__cplusplus >= 201703L)
#define WINPR_ATTR_UNUSED [[maybe_unused]] /** @since version 3.12.0 */
#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L)
#define WINPR_ATTR_UNUSED [[maybe_unused]] /** @since version 3.12.0 */
#elif defined(__GNUC__) || defined(__clang__)
#define WINPR_ATTR_UNUSED __attribute__((unused)) /** @since version 3.12.0 */
#else
#define WINPR_ATTR_UNUSED /** @since version 3.12.0 */
#endif
#define WINPR_UNUSED(x) (void)(x)
#endif /* WINPR_PLATFORM_H */

View File

@@ -0,0 +1,282 @@
/**
* WinPR: Windows Portable Runtime
* Thread Pool API
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_POOL_H
#define WINPR_POOL_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/synch.h>
#include <winpr/thread.h>
#ifndef _WIN32
typedef DWORD TP_VERSION, *PTP_VERSION;
typedef struct S_TP_CALLBACK_INSTANCE TP_CALLBACK_INSTANCE, *PTP_CALLBACK_INSTANCE;
typedef VOID (*PTP_SIMPLE_CALLBACK)(PTP_CALLBACK_INSTANCE Instance, PVOID Context);
typedef struct S_TP_POOL TP_POOL, *PTP_POOL;
typedef struct
{
size_t StackReserve;
size_t StackCommit;
} TP_POOL_STACK_INFORMATION, *PTP_POOL_STACK_INFORMATION;
typedef struct S_TP_CLEANUP_GROUP TP_CLEANUP_GROUP, *PTP_CLEANUP_GROUP;
typedef VOID (*PTP_CLEANUP_GROUP_CANCEL_CALLBACK)(PVOID ObjectContext, PVOID CleanupContext);
typedef struct
{
TP_VERSION Version;
PTP_POOL Pool;
PTP_CLEANUP_GROUP CleanupGroup;
PTP_CLEANUP_GROUP_CANCEL_CALLBACK CleanupGroupCancelCallback;
PVOID RaceDll;
PTP_SIMPLE_CALLBACK FinalizationCallback;
union
{
DWORD Flags;
struct
{
DWORD LongFunction : 1;
DWORD Persistent : 1;
DWORD Private : 30;
} s;
} u;
} TP_CALLBACK_ENVIRON_V1;
typedef TP_CALLBACK_ENVIRON_V1 TP_CALLBACK_ENVIRON, *PTP_CALLBACK_ENVIRON;
typedef struct S_TP_WORK TP_WORK, *PTP_WORK;
typedef struct S_TP_TIMER TP_TIMER, *PTP_TIMER;
typedef DWORD TP_WAIT_RESULT;
typedef struct S_TP_WAIT TP_WAIT, *PTP_WAIT;
typedef struct S_TP_IO TP_IO, *PTP_IO;
typedef VOID (*PTP_WORK_CALLBACK)(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WORK Work);
typedef VOID (*PTP_TIMER_CALLBACK)(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_TIMER Timer);
typedef VOID (*PTP_WAIT_CALLBACK)(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WAIT Wait,
TP_WAIT_RESULT WaitResult);
#endif /* _WIN32 not defined */
/*
There is a bug in the Win8 header that defines the IO
callback unconditionally. Versions of Windows greater
than XP will conditionally define it. The following
logic tries to fix that.
*/
#ifdef _THREADPOOLAPISET_H_
#define PTP_WIN32_IO_CALLBACK_DEFINED 1
#else
#if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0600)
#define PTP_WIN32_IO_CALLBACK_DEFINED 1
#endif
#endif
#ifndef PTP_WIN32_IO_CALLBACK_DEFINED
typedef VOID (*PTP_WIN32_IO_CALLBACK)(PTP_CALLBACK_INSTANCE Instance, PVOID Context,
PVOID Overlapped, ULONG IoResult,
ULONG_PTR NumberOfBytesTransferred, PTP_IO Io);
#endif
#if !defined(_WIN32)
#define WINPR_THREAD_POOL 1
#elif defined(_WIN32) && (_WIN32_WINNT < 0x0600)
#define WINPR_THREAD_POOL 1
#elif defined(__MINGW32__) && (__MINGW64_VERSION_MAJOR < 7)
#define WINPR_THREAD_POOL 1
#endif
#ifdef __cplusplus
extern "C"
{
#endif
/* Synch */
#ifdef WINPR_THREAD_POOL
WINPR_API PTP_WAIT winpr_CreateThreadpoolWait(PTP_WAIT_CALLBACK pfnwa, PVOID pv,
PTP_CALLBACK_ENVIRON pcbe);
WINPR_API VOID winpr_CloseThreadpoolWait(PTP_WAIT pwa);
WINPR_API VOID winpr_SetThreadpoolWait(PTP_WAIT pwa, HANDLE h, PFILETIME pftTimeout);
WINPR_API VOID winpr_WaitForThreadpoolWaitCallbacks(PTP_WAIT pwa, BOOL fCancelPendingCallbacks);
#define CreateThreadpoolWait winpr_CreateThreadpoolWait
#define CloseThreadpoolWait winpr_CloseThreadpoolWait
#define SetThreadpoolWait winpr_SetThreadpoolWait
#define WaitForThreadpoolWaitCallbacks winpr_WaitForThreadpoolWaitCallbacks
/* Work */
WINPR_API PTP_WORK winpr_CreateThreadpoolWork(PTP_WORK_CALLBACK pfnwk, PVOID pv,
PTP_CALLBACK_ENVIRON pcbe);
WINPR_API VOID winpr_CloseThreadpoolWork(PTP_WORK pwk);
WINPR_API VOID winpr_SubmitThreadpoolWork(PTP_WORK pwk);
WINPR_API BOOL winpr_TrySubmitThreadpoolCallback(PTP_SIMPLE_CALLBACK pfns, PVOID pv,
PTP_CALLBACK_ENVIRON pcbe);
WINPR_API VOID winpr_WaitForThreadpoolWorkCallbacks(PTP_WORK pwk, BOOL fCancelPendingCallbacks);
#define CreateThreadpoolWork winpr_CreateThreadpoolWork
#define CloseThreadpoolWork winpr_CloseThreadpoolWork
#define SubmitThreadpoolWork winpr_SubmitThreadpoolWork
#define TrySubmitThreadpoolCallback winpr_TrySubmitThreadpoolCallback
#define WaitForThreadpoolWorkCallbacks winpr_WaitForThreadpoolWorkCallbacks
/* Timer */
WINPR_API PTP_TIMER winpr_CreateThreadpoolTimer(PTP_TIMER_CALLBACK pfnti, PVOID pv,
PTP_CALLBACK_ENVIRON pcbe);
WINPR_API VOID winpr_CloseThreadpoolTimer(PTP_TIMER pti);
WINPR_API BOOL winpr_IsThreadpoolTimerSet(PTP_TIMER pti);
WINPR_API VOID winpr_SetThreadpoolTimer(PTP_TIMER pti, PFILETIME pftDueTime, DWORD msPeriod,
DWORD msWindowLength);
WINPR_API VOID winpr_WaitForThreadpoolTimerCallbacks(PTP_TIMER pti,
BOOL fCancelPendingCallbacks);
#define CreateThreadpoolTimer winpr_CreateThreadpoolTimer
#define CloseThreadpoolTimer winpr_CloseThreadpoolTimer
#define IsThreadpoolTimerSet winpr_IsThreadpoolTimerSet
#define SetThreadpoolTimer winpr_SetThreadpoolTimer
#define WaitForThreadpoolTimerCallbacks winpr_WaitForThreadpoolTimerCallbacks
/* I/O */
WINPR_API PTP_IO winpr_CreateThreadpoolIo(HANDLE fl, PTP_WIN32_IO_CALLBACK pfnio, PVOID pv,
PTP_CALLBACK_ENVIRON pcbe);
WINPR_API VOID winpr_CloseThreadpoolIo(PTP_IO pio);
WINPR_API VOID winpr_StartThreadpoolIo(PTP_IO pio);
WINPR_API VOID winpr_CancelThreadpoolIo(PTP_IO pio);
WINPR_API VOID winpr_WaitForThreadpoolIoCallbacks(PTP_IO pio, BOOL fCancelPendingCallbacks);
#define CreateThreadpoolIo winpr_CreateThreadpoolIo
#define CloseThreadpoolIo winpr_CloseThreadpoolIo
#define StartThreadpoolIo winpr_StartThreadpoolIo
#define CancelThreadpoolIo winpr_CancelThreadpoolIo
#define WaitForThreadpoolIoCallbacks winpr_WaitForThreadpoolIoCallbacks
/* Clean-up Group */
WINPR_API VOID winpr_SetThreadpoolCallbackCleanupGroup(PTP_CALLBACK_ENVIRON pcbe,
PTP_CLEANUP_GROUP ptpcg,
PTP_CLEANUP_GROUP_CANCEL_CALLBACK pfng);
WINPR_API PTP_CLEANUP_GROUP winpr_CreateThreadpoolCleanupGroup(void);
WINPR_API VOID winpr_CloseThreadpoolCleanupGroupMembers(PTP_CLEANUP_GROUP ptpcg,
BOOL fCancelPendingCallbacks,
PVOID pvCleanupContext);
WINPR_API VOID winpr_CloseThreadpoolCleanupGroup(PTP_CLEANUP_GROUP ptpcg);
#define SetThreadpoolCallbackCleanupGroup winpr_SetThreadpoolCallbackCleanupGroup
#define CreateThreadpoolCleanupGroup winpr_CreateThreadpoolCleanupGroup
#define CloseThreadpoolCleanupGroupMembers winpr_CloseThreadpoolCleanupGroupMembers
#define CloseThreadpoolCleanupGroup winpr_CloseThreadpoolCleanupGroup
/* Pool */
WINPR_API PTP_POOL winpr_CreateThreadpool(PVOID reserved);
WINPR_API VOID winpr_CloseThreadpool(PTP_POOL ptpp);
WINPR_API BOOL winpr_SetThreadpoolThreadMinimum(PTP_POOL ptpp, DWORD cthrdMic);
WINPR_API VOID winpr_SetThreadpoolThreadMaximum(PTP_POOL ptpp, DWORD cthrdMost);
#define CreateThreadpool winpr_CreateThreadpool
#define CloseThreadpool winpr_CloseThreadpool
#define SetThreadpoolThreadMinimum winpr_SetThreadpoolThreadMinimum
#define SetThreadpoolThreadMaximum winpr_SetThreadpoolThreadMaximum
/* Callback */
WINPR_API BOOL winpr_CallbackMayRunLong(PTP_CALLBACK_INSTANCE pci);
/* Callback Clean-up */
WINPR_API VOID winpr_SetEventWhenCallbackReturns(PTP_CALLBACK_INSTANCE pci, HANDLE evt);
WINPR_API VOID winpr_ReleaseSemaphoreWhenCallbackReturns(PTP_CALLBACK_INSTANCE pci, HANDLE sem,
DWORD crel);
WINPR_API VOID winpr_ReleaseMutexWhenCallbackReturns(PTP_CALLBACK_INSTANCE pci, HANDLE mut);
WINPR_API VOID winpr_LeaveCriticalSectionWhenCallbackReturns(PTP_CALLBACK_INSTANCE pci,
PCRITICAL_SECTION pcs);
WINPR_API VOID winpr_FreeLibraryWhenCallbackReturns(PTP_CALLBACK_INSTANCE pci, HMODULE mod);
WINPR_API VOID winpr_DisassociateCurrentThreadFromCallback(PTP_CALLBACK_INSTANCE pci);
#define SetEventWhenCallbackReturns winpr_SetEventWhenCallbackReturns
#define ReleaseSemaphoreWhenCallbackReturns winpr_ReleaseSemaphoreWhenCallbackReturns
#define ReleaseMutexWhenCallbackReturns winpr_ReleaseMutexWhenCallbackReturns
#define LeaveCriticalSectionWhenCallbackReturns winpr_LeaveCriticalSectionWhenCallbackReturns
#define FreeLibraryWhenCallbackReturns winpr_FreeLibraryWhenCallbackReturns
#define DisassociateCurrentThreadFromCallback winpr_DisassociateCurrentThreadFromCallback
#endif /* WINPR_THREAD_POOL */
#if !defined(_WIN32)
#define WINPR_CALLBACK_ENVIRON 1
#elif defined(_WIN32) && (_WIN32_WINNT < 0x0600)
#define WINPR_CALLBACK_ENVIRON 1
#elif defined(__MINGW32__) && (__MINGW64_VERSION_MAJOR < 9)
#define WINPR_CALLBACK_ENVIRON 1
#endif
#ifdef WINPR_CALLBACK_ENVIRON
/* some version of mingw are missing Callback Environment functions */
/* Callback Environment */
static inline VOID InitializeThreadpoolEnvironment(PTP_CALLBACK_ENVIRON pcbe)
{
const TP_CALLBACK_ENVIRON empty = WINPR_C_ARRAY_INIT;
*pcbe = empty;
pcbe->Version = 1;
}
static inline VOID DestroyThreadpoolEnvironment(WINPR_ATTR_UNUSED PTP_CALLBACK_ENVIRON pcbe)
{
/* no actions, this may change in a future release. */
}
static inline VOID SetThreadpoolCallbackPool(PTP_CALLBACK_ENVIRON pcbe, PTP_POOL ptpp)
{
pcbe->Pool = ptpp;
}
static inline VOID SetThreadpoolCallbackRunsLong(PTP_CALLBACK_ENVIRON pcbe)
{
pcbe->u.s.LongFunction = 1;
}
static inline VOID SetThreadpoolCallbackLibrary(PTP_CALLBACK_ENVIRON pcbe, PVOID mod)
{
pcbe->RaceDll = mod;
}
#endif
#ifdef __cplusplus
}
#endif
#endif /* WINPR_POOL_H */

View File

@@ -0,0 +1,56 @@
/**
* WinPR: Windows Portable Runtime
* Print Utils
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_UTILS_PRINT_H
#define WINPR_UTILS_PRINT_H
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/wlog.h>
#define WINPR_HEXDUMP_LINE_LENGTH 16
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API void winpr_HexDump(const char* tag, UINT32 level, const void* data, size_t length);
WINPR_API void winpr_HexLogDump(wLog* log, UINT32 level, const void* data, size_t length);
WINPR_API void winpr_CArrayDump(const char* tag, UINT32 level, const void* data, size_t length,
size_t width);
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* winpr_BinToHexString(const BYTE* data, size_t length, BOOL space);
WINPR_API size_t winpr_BinToHexStringBuffer(const BYTE* data, size_t length, char* dstStr,
size_t dstSize, BOOL space);
WINPR_API size_t winpr_HexStringToBinBuffer(const char* str, size_t strLength, BYTE* data,
size_t dataLength);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_UTILS_PRINT_H */

View File

@@ -0,0 +1,426 @@
/**
* WinPR: Windows Portable Runtime
* Windows Registry
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_REGISTRY_H
#define WINPR_REGISTRY_H
#include <winpr/windows.h>
#if defined(_WIN32) && !defined(_UWP)
#include <winreg.h>
#else
#ifdef __cplusplus
extern "C"
{
#endif
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/nt.h>
#include <winpr/io.h>
#include <winpr/error.h>
#ifndef _WIN32
#define OWNER_SECURITY_INFORMATION 0x00000001
#define GROUP_SECURITY_INFORMATION 0x00000002
#define DACL_SECURITY_INFORMATION 0x00000004
#define SACL_SECURITY_INFORMATION 0x00000008
#define REG_OPTION_RESERVED 0x00000000
#define REG_OPTION_NON_VOLATILE 0x00000000
#define REG_OPTION_VOLATILE 0x00000001
#define REG_OPTION_CREATE_LINK 0x00000002
#define REG_OPTION_BACKUP_RESTORE 0x00000004
#define REG_OPTION_OPEN_LINK 0x00000008
#define REG_CREATED_NEW_KEY 0x00000001
#define REG_OPENED_EXISTING_KEY 0x00000002
#define REG_NOTIFY_CHANGE_NAME 0x01
#define REG_NOTIFY_CHANGE_ATTRIBUTES 0x02
#define REG_NOTIFY_CHANGE_LAST_SET 0x04
#define REG_NOTIFY_CHANGE_SECURITY 0x08
#define KEY_QUERY_VALUE 0x00000001
#define KEY_SET_VALUE 0x00000002
#define KEY_CREATE_SUB_KEY 0x00000004
#define KEY_ENUMERATE_SUB_KEYS 0x00000008
#define KEY_NOTIFY 0x00000010
#define KEY_CREATE_LINK 0x00000020
#define KEY_WOW64_64KEY 0x00000100
#define KEY_WOW64_32KEY 0x00000200
#define KEY_WOW64_RES 0x00000300
#define REG_WHOLE_HIVE_VOLATILE 0x00000001
#define REG_REFRESH_HIVE 0x00000002
#define REG_NO_LAZY_FLUSH 0x00000004
#define REG_FORCE_RESTORE 0x00000008
#define KEY_READ \
((STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY) & \
(~SYNCHRONIZE))
#define KEY_WRITE ((STANDARD_RIGHTS_WRITE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY) & (~SYNCHRONIZE))
#define KEY_EXECUTE ((KEY_READ) & (~SYNCHRONIZE))
#define KEY_ALL_ACCESS \
((STANDARD_RIGHTS_ALL | KEY_QUERY_VALUE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY | \
KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY | KEY_CREATE_LINK) & \
(~SYNCHRONIZE))
typedef enum
{
REG_NONE = 0,
REG_SZ = 1,
REG_EXPAND_SZ = 2,
REG_BINARY = 3,
REG_DWORD = 4,
REG_DWORD_LITTLE_ENDIAN = REG_DWORD,
REG_DWORD_BIG_ENDIAN = 5,
REG_LINK = 6,
REG_MULTI_SZ = 7,
REG_RESOURCE_LIST = 8,
REG_FULL_RESOURCE_DESCRIPTOR = 9,
REG_RESOURCE_REQUIREMENTS_LIST = 10,
REG_QWORD = 11,
REG_QWORD_LITTLE_ENDIAN = REG_QWORD
} eRegTypes;
typedef HANDLE HKEY;
typedef HANDLE* PHKEY;
#endif
typedef ACCESS_MASK REGSAM;
#define HKEY_CLASSES_ROOT ((HKEY)(LONG_PTR)(LONG)0x80000000)
#define HKEY_CURRENT_USER ((HKEY)(LONG_PTR)(LONG)0x80000001)
#define HKEY_LOCAL_MACHINE ((HKEY)(LONG_PTR)(LONG)0x80000002)
#define HKEY_USERS ((HKEY)(LONG_PTR)(LONG)0x80000003)
#define HKEY_PERFORMANCE_DATA ((HKEY)(LONG_PTR)(LONG)0x80000004)
#define HKEY_PERFORMANCE_TEXT ((HKEY)(LONG_PTR)(LONG)0x80000050)
#define HKEY_PERFORMANCE_NLSTEXT ((HKEY)(LONG_PTR)(LONG)0x80000060)
#define HKEY_CURRENT_CONFIG ((HKEY)(LONG_PTR)(LONG)0x80000005)
#define HKEY_DYN_DATA ((HKEY)(LONG_PTR)(LONG)0x80000006)
#define HKEY_CURRENT_USER_LOCAL_SETTINGS ((HKEY)(LONG_PTR)(LONG)0x80000007)
#define RRF_RT_REG_NONE 0x00000001
#define RRF_RT_REG_SZ 0x00000002
#define RRF_RT_REG_EXPAND_SZ 0x00000004
#define RRF_RT_REG_BINARY 0x00000008
#define RRF_RT_REG_DWORD 0x00000010
#define RRF_RT_REG_MULTI_SZ 0x00000020
#define RRF_RT_REG_QWORD 0x00000040
#define RRF_RT_DWORD (RRF_RT_REG_BINARY | RRF_RT_REG_DWORD)
#define RRF_RT_QWORD (RRF_RT_REG_BINARY | RRF_RT_REG_QWORD)
#define RRF_RT_ANY 0x0000FFFF
#define RRF_NOEXPAND 0x10000000
#define RRF_ZEROONFAILURE 0x20000000
struct val_context
{
int valuelen;
LPVOID value_context;
LPVOID val_buff_ptr;
};
typedef struct val_context* PVALCONTEXT;
typedef struct pvalueA
{
LPSTR pv_valuename;
int pv_valuelen;
LPVOID pv_value_context;
DWORD pv_type;
} PVALUEA, *PPVALUEA;
typedef struct pvalueW
{
LPWSTR pv_valuename;
int pv_valuelen;
LPVOID pv_value_context;
DWORD pv_type;
} PVALUEW, *PPVALUEW;
#ifdef UNICODE
typedef PVALUEW PVALUE;
typedef PPVALUEW PPVALUE;
#else
typedef PVALUEA PVALUE;
typedef PPVALUEA PPVALUE;
#endif
typedef struct value_entA
{
LPSTR ve_valuename;
DWORD ve_valuelen;
DWORD_PTR ve_valueptr;
DWORD ve_type;
} VALENTA, *PVALENTA;
typedef struct value_entW
{
LPWSTR ve_valuename;
DWORD ve_valuelen;
DWORD_PTR ve_valueptr;
DWORD ve_type;
} VALENTW, *PVALENTW;
#ifdef UNICODE
typedef VALENTW VALENT;
typedef PVALENTW PVALENT;
#else
typedef VALENTA VALENT;
typedef PVALENTA PVALENT;
#endif
WINPR_API LONG RegCloseKey(HKEY hKey);
WINPR_API LONG RegCopyTreeW(HKEY hKeySrc, LPCWSTR lpSubKey, HKEY hKeyDest);
WINPR_API LONG RegCopyTreeA(HKEY hKeySrc, LPCSTR lpSubKey, HKEY hKeyDest);
#ifdef UNICODE
#define RegCopyTree RegCopyTreeW
#else
#define RegCopyTree RegCopyTreeA
#endif
WINPR_API LONG RegCreateKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD Reserved, LPWSTR lpClass,
DWORD dwOptions, REGSAM samDesired,
LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult,
LPDWORD lpdwDisposition);
WINPR_API LONG RegCreateKeyExA(HKEY hKey, LPCSTR lpSubKey, DWORD Reserved, LPSTR lpClass,
DWORD dwOptions, REGSAM samDesired,
LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult,
LPDWORD lpdwDisposition);
#ifdef UNICODE
#define RegCreateKeyEx RegCreateKeyExW
#else
#define RegCreateKeyEx RegCreateKeyExA
#endif
WINPR_API LONG RegDeleteKeyExW(HKEY hKey, LPCWSTR lpSubKey, REGSAM samDesired, DWORD Reserved);
WINPR_API LONG RegDeleteKeyExA(HKEY hKey, LPCSTR lpSubKey, REGSAM samDesired, DWORD Reserved);
#ifdef UNICODE
#define RegDeleteKeyEx RegDeleteKeyExW
#else
#define RegDeleteKeyEx RegDeleteKeyExA
#endif
WINPR_API LONG RegDeleteTreeW(HKEY hKey, LPCWSTR lpSubKey);
WINPR_API LONG RegDeleteTreeA(HKEY hKey, LPCSTR lpSubKey);
#ifdef UNICODE
#define RegDeleteTree RegDeleteTreeW
#else
#define RegDeleteTree RegDeleteTreeA
#endif
WINPR_API LONG RegDeleteValueW(HKEY hKey, LPCWSTR lpValueName);
WINPR_API LONG RegDeleteValueA(HKEY hKey, LPCSTR lpValueName);
#ifdef UNICODE
#define RegDeleteValue RegDeleteValueW
#else
#define RegDeleteValue RegDeleteValueA
#endif
WINPR_API LONG RegDisablePredefinedCacheEx(void);
WINPR_API LONG RegEnumKeyExW(HKEY hKey, DWORD dwIndex, LPWSTR lpName, LPDWORD lpcName,
LPDWORD lpReserved, LPWSTR lpClass, LPDWORD lpcClass,
PFILETIME lpftLastWriteTime);
WINPR_API LONG RegEnumKeyExA(HKEY hKey, DWORD dwIndex, LPSTR lpName, LPDWORD lpcName,
LPDWORD lpReserved, LPSTR lpClass, LPDWORD lpcClass,
PFILETIME lpftLastWriteTime);
#ifdef UNICODE
#define RegEnumKeyEx RegEnumKeyExW
#else
#define RegEnumKeyEx RegEnumKeyExA
#endif
WINPR_API LONG RegEnumValueW(HKEY hKey, DWORD dwIndex, LPWSTR lpValueName,
LPDWORD lpcchValueName, LPDWORD lpReserved, LPDWORD lpType,
LPBYTE lpData, LPDWORD lpcbData);
WINPR_API LONG RegEnumValueA(HKEY hKey, DWORD dwIndex, LPSTR lpValueName,
LPDWORD lpcchValueName, LPDWORD lpReserved, LPDWORD lpType,
LPBYTE lpData, LPDWORD lpcbData);
#ifdef UNICODE
#define RegEnumValue RegEnumValueW
#else
#define RegEnumValue RegEnumValueA
#endif
WINPR_API LONG RegFlushKey(HKEY hKey);
WINPR_API LONG RegGetKeySecurity(HKEY hKey, SECURITY_INFORMATION SecurityInformation,
PSECURITY_DESCRIPTOR pSecurityDescriptor,
LPDWORD lpcbSecurityDescriptor);
WINPR_API LONG RegGetValueW(HKEY hkey, LPCWSTR lpSubKey, LPCWSTR lpValue, DWORD dwFlags,
LPDWORD pdwType, PVOID pvData, LPDWORD pcbData);
WINPR_API LONG RegGetValueA(HKEY hkey, LPCSTR lpSubKey, LPCSTR lpValue, DWORD dwFlags,
LPDWORD pdwType, PVOID pvData, LPDWORD pcbData);
#ifdef UNICODE
#define RegGetValue RegGetValueW
#else
#define RegGetValue RegGetValueA
#endif
WINPR_API LONG RegLoadAppKeyW(LPCWSTR lpFile, PHKEY phkResult, REGSAM samDesired,
DWORD dwOptions, DWORD Reserved);
WINPR_API LONG RegLoadAppKeyA(LPCSTR lpFile, PHKEY phkResult, REGSAM samDesired,
DWORD dwOptions, DWORD Reserved);
#ifdef UNICODE
#define RegLoadAppKey RegLoadAppKeyW
#else
#define RegLoadAppKey RegLoadAppKeyA
#endif
WINPR_API LONG RegLoadKeyW(HKEY hKey, LPCWSTR lpSubKey, LPCWSTR lpFile);
WINPR_API LONG RegLoadKeyA(HKEY hKey, LPCSTR lpSubKey, LPCSTR lpFile);
#ifdef UNICODE
#define RegLoadKey RegLoadKeyW
#else
#define RegLoadKey RegLoadKeyA
#endif
WINPR_API LONG RegLoadMUIStringW(HKEY hKey, LPCWSTR pszValue, LPWSTR pszOutBuf, DWORD cbOutBuf,
LPDWORD pcbData, DWORD Flags, LPCWSTR pszDirectory);
WINPR_API LONG RegLoadMUIStringA(HKEY hKey, LPCSTR pszValue, LPSTR pszOutBuf, DWORD cbOutBuf,
LPDWORD pcbData, DWORD Flags, LPCSTR pszDirectory);
#ifdef UNICODE
#define RegLoadMUIString RegLoadMUIStringW
#else
#define RegLoadMUIString RegLoadMUIStringA
#endif
WINPR_API LONG RegNotifyChangeKeyValue(HKEY hKey, BOOL bWatchSubtree, DWORD dwNotifyFilter,
HANDLE hEvent, BOOL fAsynchronous);
WINPR_API LONG RegOpenCurrentUser(REGSAM samDesired, PHKEY phkResult);
WINPR_API LONG RegOpenKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired,
PHKEY phkResult);
WINPR_API LONG RegOpenKeyExA(HKEY hKey, LPCSTR lpSubKey, DWORD ulOptions, REGSAM samDesired,
PHKEY phkResult);
#ifdef UNICODE
#define RegOpenKeyEx RegOpenKeyExW
#else
#define RegOpenKeyEx RegOpenKeyExA
#endif
WINPR_API LONG RegOpenUserClassesRoot(HANDLE hToken, DWORD dwOptions, REGSAM samDesired,
PHKEY phkResult);
WINPR_API LONG RegQueryInfoKeyW(HKEY hKey, LPWSTR lpClass, LPDWORD lpcClass, LPDWORD lpReserved,
LPDWORD lpcSubKeys, LPDWORD lpcMaxSubKeyLen,
LPDWORD lpcMaxClassLen, LPDWORD lpcValues,
LPDWORD lpcMaxValueNameLen, LPDWORD lpcMaxValueLen,
LPDWORD lpcbSecurityDescriptor, PFILETIME lpftLastWriteTime);
WINPR_API LONG RegQueryInfoKeyA(HKEY hKey, LPSTR lpClass, LPDWORD lpcClass, LPDWORD lpReserved,
LPDWORD lpcSubKeys, LPDWORD lpcMaxSubKeyLen,
LPDWORD lpcMaxClassLen, LPDWORD lpcValues,
LPDWORD lpcMaxValueNameLen, LPDWORD lpcMaxValueLen,
LPDWORD lpcbSecurityDescriptor, PFILETIME lpftLastWriteTime);
#ifdef UNICODE
#define RegQueryInfoKey RegQueryInfoKeyW
#else
#define RegQueryInfoKey RegQueryInfoKeyA
#endif
WINPR_API LONG RegQueryValueExW(HKEY hKey, LPCWSTR lpValueName, LPDWORD lpReserved,
LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData);
WINPR_API LONG RegQueryValueExA(HKEY hKey, LPCSTR lpValueName, LPDWORD lpReserved,
LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData);
#ifdef UNICODE
#define RegQueryValueEx RegQueryValueExW
#else
#define RegQueryValueEx RegQueryValueExA
#endif
WINPR_API LONG RegRestoreKeyW(HKEY hKey, LPCWSTR lpFile, DWORD dwFlags);
WINPR_API LONG RegRestoreKeyA(HKEY hKey, LPCSTR lpFile, DWORD dwFlags);
#ifdef UNICODE
#define RegRestoreKey RegRestoreKeyW
#else
#define RegRestoreKey RegRestoreKeyA
#endif
WINPR_API LONG RegSaveKeyExW(HKEY hKey, LPCWSTR lpFile,
LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD Flags);
WINPR_API LONG RegSaveKeyExA(HKEY hKey, LPCSTR lpFile,
LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD Flags);
#ifdef UNICODE
#define RegSaveKeyEx RegSaveKeyExW
#else
#define RegSaveKeyEx RegSaveKeyExA
#endif
WINPR_API LONG RegSetKeySecurity(HKEY hKey, SECURITY_INFORMATION SecurityInformation,
PSECURITY_DESCRIPTOR pSecurityDescriptor);
WINPR_API LONG RegSetValueExW(HKEY hKey, LPCWSTR lpValueName, DWORD Reserved, DWORD dwType,
const BYTE* lpData, DWORD cbData);
WINPR_API LONG RegSetValueExA(HKEY hKey, LPCSTR lpValueName, DWORD Reserved, DWORD dwType,
const BYTE* lpData, DWORD cbData);
#ifdef UNICODE
#define RegSetValueEx RegSetValueExW
#else
#define RegSetValueEx RegSetValueExA
#endif
WINPR_API LONG RegUnLoadKeyW(HKEY hKey, LPCWSTR lpSubKey);
WINPR_API LONG RegUnLoadKeyA(HKEY hKey, LPCSTR lpSubKey);
#ifdef UNICODE
#define RegUnLoadKey RegUnLoadKeyW
#else
#define RegUnLoadKey RegUnLoadKeyA
#endif
#ifdef __cplusplus
}
#endif
#endif
#endif /* WINPR_REGISTRY_H */

View File

@@ -0,0 +1,724 @@
/**
* WinPR: Windows Portable Runtime
* Microsoft Remote Procedure Call (MSRPC)
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_RPC_H
#define WINPR_RPC_H
#include <winpr/wtypes.h>
typedef struct
{
UINT32 ContextType;
GUID ContextUuid;
} CONTEXT_HANDLE;
typedef PCONTEXT_HANDLE PTUNNEL_CONTEXT_HANDLE_NOSERIALIZE;
typedef PCONTEXT_HANDLE PTUNNEL_CONTEXT_HANDLE_SERIALIZE;
typedef PCONTEXT_HANDLE PCHANNEL_CONTEXT_HANDLE_NOSERIALIZE;
typedef PCONTEXT_HANDLE PCHANNEL_CONTEXT_HANDLE_SERIALIZE;
#if defined(_WIN32) && !defined(_UWP)
#include <rpc.h>
#else
#include <winpr/winpr.h>
#include <winpr/sspi.h>
#include <winpr/spec.h>
#include <winpr/error.h>
#define RPC_S_OK ERROR_SUCCESS
#define RPC_S_INVALID_ARG ERROR_INVALID_PARAMETER
#define RPC_S_OUT_OF_MEMORY ERROR_OUTOFMEMORY
#define RPC_S_OUT_OF_THREADS ERROR_MAX_THRDS_REACHED
#define RPC_S_INVALID_LEVEL ERROR_INVALID_PARAMETER
#define RPC_S_BUFFER_TOO_SMALL ERROR_INSUFFICIENT_BUFFER
#define RPC_S_INVALID_SECURITY_DESC ERROR_INVALID_SECURITY_DESCR
#define RPC_S_ACCESS_DENIED ERROR_ACCESS_DENIED
#define RPC_S_SERVER_OUT_OF_MEMORY ERROR_NOT_ENOUGH_SERVER_MEMORY
#define RPC_S_ASYNC_CALL_PENDING ERROR_IO_PENDING
#define RPC_S_UNKNOWN_PRINCIPAL ERROR_NONE_MAPPED
#define RPC_S_TIMEOUT ERROR_TIMEOUT
#define RPC_X_NO_MEMORY RPC_S_OUT_OF_MEMORY
#define RPC_X_INVALID_BOUND RPC_S_INVALID_BOUND
#define RPC_X_INVALID_TAG RPC_S_INVALID_TAG
#define RPC_X_ENUM_VALUE_TOO_LARGE RPC_X_ENUM_VALUE_OUT_OF_RANGE
#define RPC_X_SS_CONTEXT_MISMATCH ERROR_INVALID_HANDLE
#define RPC_X_INVALID_BUFFER ERROR_INVALID_USER_BUFFER
#define RPC_X_PIPE_APP_MEMORY ERROR_OUTOFMEMORY
#define RPC_X_INVALID_PIPE_OPERATION RPC_X_WRONG_PIPE_ORDER
#define RPC_VAR_ENTRY __cdecl
typedef long RPC_STATUS;
#ifndef _WIN32
typedef CHAR* RPC_CSTR;
typedef WCHAR* RPC_WSTR;
#endif
typedef void* I_RPC_HANDLE;
typedef I_RPC_HANDLE RPC_BINDING_HANDLE;
typedef RPC_BINDING_HANDLE handle_t;
typedef struct
{
unsigned long Count;
RPC_BINDING_HANDLE BindingH[1];
} RPC_BINDING_VECTOR;
#define rpc_binding_vector_t RPC_BINDING_VECTOR
typedef struct
{
unsigned long Count;
UUID* Uuid[1];
} UUID_VECTOR;
#define uuid_vector_t UUID_VECTOR
typedef void* RPC_IF_HANDLE;
typedef struct
{
UUID Uuid;
unsigned short VersMajor;
unsigned short VersMinor;
} RPC_IF_ID;
#define RPC_C_BINDING_INFINITE_TIMEOUT 10
#define RPC_C_BINDING_MIN_TIMEOUT 0
#define RPC_C_BINDING_DEFAULT_TIMEOUT 5
#define RPC_C_BINDING_MAX_TIMEOUT 9
#define RPC_C_CANCEL_INFINITE_TIMEOUT -1
#define RPC_C_LISTEN_MAX_CALLS_DEFAULT 1234
#define RPC_C_PROTSEQ_MAX_REQS_DEFAULT 10
#define RPC_C_BIND_TO_ALL_NICS 1
#define RPC_C_USE_INTERNET_PORT 0x1
#define RPC_C_USE_INTRANET_PORT 0x2
#define RPC_C_DONT_FAIL 0x4
#define RPC_C_MQ_TEMPORARY 0x0000
#define RPC_C_MQ_PERMANENT 0x0001
#define RPC_C_MQ_CLEAR_ON_OPEN 0x0002
#define RPC_C_MQ_USE_EXISTING_SECURITY 0x0004
#define RPC_C_MQ_AUTHN_LEVEL_NONE 0x0000
#define RPC_C_MQ_AUTHN_LEVEL_PKT_INTEGRITY 0x0008
#define RPC_C_MQ_AUTHN_LEVEL_PKT_PRIVACY 0x0010
#define RPC_C_OPT_MQ_DELIVERY 1
#define RPC_C_OPT_MQ_PRIORITY 2
#define RPC_C_OPT_MQ_JOURNAL 3
#define RPC_C_OPT_MQ_ACKNOWLEDGE 4
#define RPC_C_OPT_MQ_AUTHN_SERVICE 5
#define RPC_C_OPT_MQ_AUTHN_LEVEL 6
#define RPC_C_OPT_MQ_TIME_TO_REACH_QUEUE 7
#define RPC_C_OPT_MQ_TIME_TO_BE_RECEIVED 8
#define RPC_C_OPT_BINDING_NONCAUSAL 9
#define RPC_C_OPT_SECURITY_CALLBACK 10
#define RPC_C_OPT_UNIQUE_BINDING 11
#define RPC_C_OPT_CALL_TIMEOUT 12
#define RPC_C_OPT_DONT_LINGER 13
#define RPC_C_OPT_MAX_OPTIONS 14
#define RPC_C_MQ_EXPRESS 0
#define RPC_C_MQ_RECOVERABLE 1
#define RPC_C_MQ_JOURNAL_NONE 0
#define RPC_C_MQ_JOURNAL_DEADLETTER 1
#define RPC_C_MQ_JOURNAL_ALWAYS 2
#define RPC_C_FULL_CERT_CHAIN 0x0001
typedef struct
{
unsigned int Count;
unsigned char* Protseq[1];
} RPC_PROTSEQ_VECTORA;
typedef struct
{
unsigned int Count;
unsigned short* Protseq[1];
} RPC_PROTSEQ_VECTORW;
#ifdef UNICODE
#define RPC_PROTSEQ_VECTOR RPC_PROTSEQ_VECTORW
#else
#define RPC_PROTSEQ_VECTOR RPC_PROTSEQ_VECTORA
#endif
typedef struct
{
unsigned int Length;
unsigned long EndpointFlags;
unsigned long NICFlags;
} RPC_POLICY, *PRPC_POLICY;
typedef void RPC_OBJECT_INQ_FN(UUID* ObjectUuid, UUID* TypeUuid, RPC_STATUS* pStatus);
typedef RPC_STATUS RPC_IF_CALLBACK_FN(RPC_IF_HANDLE InterfaceUuid, void* Context);
typedef void RPC_SECURITY_CALLBACK_FN(void* Context);
#define RPC_MGR_EPV void
typedef struct
{
unsigned int Count;
unsigned long Stats[1];
} RPC_STATS_VECTOR;
#define RPC_C_STATS_CALLS_IN 0
#define RPC_C_STATS_CALLS_OUT 1
#define RPC_C_STATS_PKTS_IN 2
#define RPC_C_STATS_PKTS_OUT 3
typedef struct
{
unsigned long Count;
RPC_IF_ID* IfId[1];
} RPC_IF_ID_VECTOR;
#ifndef _WIN32
typedef void* RPC_AUTH_IDENTITY_HANDLE;
typedef void* RPC_AUTHZ_HANDLE;
#define RPC_C_AUTHN_LEVEL_DEFAULT 0
#define RPC_C_AUTHN_LEVEL_NONE 1
#define RPC_C_AUTHN_LEVEL_CONNECT 2
#define RPC_C_AUTHN_LEVEL_CALL 3
#define RPC_C_AUTHN_LEVEL_PKT 4
#define RPC_C_AUTHN_LEVEL_PKT_INTEGRITY 5
#define RPC_C_AUTHN_LEVEL_PKT_PRIVACY 6
#define RPC_C_IMP_LEVEL_DEFAULT 0
#define RPC_C_IMP_LEVEL_ANONYMOUS 1
#define RPC_C_IMP_LEVEL_IDENTIFY 2
#define RPC_C_IMP_LEVEL_IMPERSONATE 3
#define RPC_C_IMP_LEVEL_DELEGATE 4
#define RPC_C_QOS_IDENTITY_STATIC 0
#define RPC_C_QOS_IDENTITY_DYNAMIC 1
#define RPC_C_QOS_CAPABILITIES_DEFAULT 0x0
#define RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH 0x1
#define RPC_C_QOS_CAPABILITIES_MAKE_FULLSIC 0x2
#define RPC_C_QOS_CAPABILITIES_ANY_AUTHORITY 0x4
#define RPC_C_QOS_CAPABILITIES_IGNORE_DELEGATE_FAILURE 0x8
#define RPC_C_QOS_CAPABILITIES_LOCAL_MA_HINT 0x10
#define RPC_C_PROTECT_LEVEL_DEFAULT (RPC_C_AUTHN_LEVEL_DEFAULT)
#define RPC_C_PROTECT_LEVEL_NONE (RPC_C_AUTHN_LEVEL_NONE)
#define RPC_C_PROTECT_LEVEL_CONNECT (RPC_C_AUTHN_LEVEL_CONNECT)
#define RPC_C_PROTECT_LEVEL_CALL (RPC_C_AUTHN_LEVEL_CALL)
#define RPC_C_PROTECT_LEVEL_PKT (RPC_C_AUTHN_LEVEL_PKT)
#define RPC_C_PROTECT_LEVEL_PKT_INTEGRITY (RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
#define RPC_C_PROTECT_LEVEL_PKT_PRIVACY (RPC_C_AUTHN_LEVEL_PKT_PRIVACY)
#define RPC_C_AUTHN_NONE 0
#define RPC_C_AUTHN_DCE_PRIVATE 1
#define RPC_C_AUTHN_DCE_PUBLIC 2
#define RPC_C_AUTHN_DEC_PUBLIC 4
#define RPC_C_AUTHN_GSS_NEGOTIATE 9
#define RPC_C_AUTHN_WINNT 10
#define RPC_C_AUTHN_GSS_SCHANNEL 14
#define RPC_C_AUTHN_GSS_KERBEROS 16
#define RPC_C_AUTHN_DPA 17
#define RPC_C_AUTHN_MSN 18
#define RPC_C_AUTHN_DIGEST 21
#define RPC_C_AUTHN_MQ 100
#define RPC_C_AUTHN_DEFAULT 0xFFFFFFFFL
#define RPC_C_NO_CREDENTIALS ((RPC_AUTH_IDENTITY_HANDLE)MAXUINT_PTR)
#define RPC_C_SECURITY_QOS_VERSION 1L
#define RPC_C_SECURITY_QOS_VERSION_1 1L
typedef struct
{
unsigned long Version;
unsigned long Capabilities;
unsigned long IdentityTracking;
unsigned long ImpersonationType;
} RPC_SECURITY_QOS, *PRPC_SECURITY_QOS;
#define RPC_C_SECURITY_QOS_VERSION_2 2L
#define RPC_C_AUTHN_INFO_TYPE_HTTP 1
#define RPC_C_HTTP_AUTHN_TARGET_SERVER 1
#define RPC_C_HTTP_AUTHN_TARGET_PROXY 2
#define RPC_C_HTTP_AUTHN_SCHEME_BASIC 0x00000001
#define RPC_C_HTTP_AUTHN_SCHEME_NTLM 0x00000002
#define RPC_C_HTTP_AUTHN_SCHEME_PASSPORT 0x00000004
#define RPC_C_HTTP_AUTHN_SCHEME_DIGEST 0x00000008
#define RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE 0x00000010
#define RPC_C_HTTP_AUTHN_SCHEME_CERT 0x00010000
#define RPC_C_HTTP_FLAG_USE_SSL 1
#define RPC_C_HTTP_FLAG_USE_FIRST_AUTH_SCHEME 2
#define RPC_C_HTTP_FLAG_IGNORE_CERT_CN_INVALID 8
typedef struct
{
SEC_WINNT_AUTH_IDENTITY_W* TransportCredentials;
unsigned long Flags;
unsigned long AuthenticationTarget;
unsigned long NumberOfAuthnSchemes;
unsigned long* AuthnSchemes;
unsigned short* ServerCertificateSubject;
} RPC_HTTP_TRANSPORT_CREDENTIALS_W, *PRPC_HTTP_TRANSPORT_CREDENTIALS_W;
typedef struct
{
SEC_WINNT_AUTH_IDENTITY_A* TransportCredentials;
unsigned long Flags;
unsigned long AuthenticationTarget;
unsigned long NumberOfAuthnSchemes;
unsigned long* AuthnSchemes;
unsigned char* ServerCertificateSubject;
} RPC_HTTP_TRANSPORT_CREDENTIALS_A, *PRPC_HTTP_TRANSPORT_CREDENTIALS_A;
typedef struct
{
unsigned long Version;
unsigned long Capabilities;
unsigned long IdentityTracking;
unsigned long ImpersonationType;
unsigned long AdditionalSecurityInfoType;
union
{
RPC_HTTP_TRANSPORT_CREDENTIALS_W* HttpCredentials;
} u;
} RPC_SECURITY_QOS_V2_W, *PRPC_SECURITY_QOS_V2_W;
typedef struct
{
unsigned long Version;
unsigned long Capabilities;
unsigned long IdentityTracking;
unsigned long ImpersonationType;
unsigned long AdditionalSecurityInfoType;
union
{
RPC_HTTP_TRANSPORT_CREDENTIALS_A* HttpCredentials;
} u;
} RPC_SECURITY_QOS_V2_A, *PRPC_SECURITY_QOS_V2_A;
#define RPC_C_SECURITY_QOS_VERSION_3 3L
typedef struct
{
unsigned long Version;
unsigned long Capabilities;
unsigned long IdentityTracking;
unsigned long ImpersonationType;
unsigned long AdditionalSecurityInfoType;
union
{
RPC_HTTP_TRANSPORT_CREDENTIALS_W* HttpCredentials;
} u;
void* Sid;
} RPC_SECURITY_QOS_V3_W, *PRPC_SECURITY_QOS_V3_W;
typedef struct
{
unsigned long Version;
unsigned long Capabilities;
unsigned long IdentityTracking;
unsigned long ImpersonationType;
unsigned long AdditionalSecurityInfoType;
union
{
RPC_HTTP_TRANSPORT_CREDENTIALS_A* HttpCredentials;
} u;
void* Sid;
} RPC_SECURITY_QOS_V3_A, *PRPC_SECURITY_QOS_V3_A;
typedef enum
{
RPCHTTP_RS_REDIRECT = 1,
RPCHTTP_RS_ACCESS_1,
RPCHTTP_RS_SESSION,
RPCHTTP_RS_ACCESS_2,
RPCHTTP_RS_INTERFACE
} RPC_HTTP_REDIRECTOR_STAGE;
typedef RPC_STATUS (*RPC_NEW_HTTP_PROXY_CHANNEL)(
RPC_HTTP_REDIRECTOR_STAGE RedirectorStage, unsigned short* ServerName,
unsigned short* ServerPort, unsigned short* RemoteUser, unsigned short* AuthType,
void* ResourceUuid, void* Metadata, void* SessionId, void* Interface, void* Reserved,
unsigned long Flags, unsigned short** NewServerName, unsigned short** NewServerPort);
typedef void (*RPC_HTTP_PROXY_FREE_STRING)(unsigned short* String);
#define RPC_C_AUTHZ_NONE 0
#define RPC_C_AUTHZ_NAME 1
#define RPC_C_AUTHZ_DCE 2
#define RPC_C_AUTHZ_DEFAULT 0xFFFFFFFF
#endif
typedef void (*RPC_AUTH_KEY_RETRIEVAL_FN)(void* Arg, unsigned short* ServerPrincName,
unsigned long KeyVer, void** Key, RPC_STATUS* pStatus);
#define DCE_C_ERROR_STRING_LEN 256
typedef I_RPC_HANDLE* RPC_EP_INQ_HANDLE;
#define RPC_C_EP_ALL_ELTS 0
#define RPC_C_EP_MATCH_BY_IF 1
#define RPC_C_EP_MATCH_BY_OBJ 2
#define RPC_C_EP_MATCH_BY_BOTH 3
#define RPC_C_VERS_ALL 1
#define RPC_C_VERS_COMPATIBLE 2
#define RPC_C_VERS_EXACT 3
#define RPC_C_VERS_MAJOR_ONLY 4
#define RPC_C_VERS_UPTO 5
typedef int (*RPC_MGMT_AUTHORIZATION_FN)(RPC_BINDING_HANDLE ClientBinding,
unsigned long RequestedMgmtOperation, RPC_STATUS* pStatus);
#define RPC_C_MGMT_INQ_IF_IDS 0
#define RPC_C_MGMT_INQ_PRINC_NAME 1
#define RPC_C_MGMT_INQ_STATS 2
#define RPC_C_MGMT_IS_SERVER_LISTEN 3
#define RPC_C_MGMT_STOP_SERVER_LISTEN 4
#define RPC_C_PARM_MAX_PACKET_LENGTH 1
#define RPC_C_PARM_BUFFER_LENGTH 2
#define RPC_IF_AUTOLISTEN 0x0001
#define RPC_IF_OLE 0x0002
#define RPC_IF_ALLOW_UNKNOWN_AUTHORITY 0x0004
#define RPC_IF_ALLOW_SECURE_ONLY 0x0008
#define RPC_IF_ALLOW_CALLBACKS_WITH_NO_AUTH 0x0010
#define RPC_IF_ALLOW_LOCAL_ONLY 0x0020
#define RPC_IF_SEC_NO_CACHE 0x0040
typedef struct
{
unsigned long Version;
unsigned long Flags;
unsigned long ComTimeout;
unsigned long CallTimeout;
} RPC_BINDING_HANDLE_OPTIONS_V1, RPC_BINDING_HANDLE_OPTIONS;
typedef struct
{
unsigned long Version;
unsigned short* ServerPrincName;
unsigned long AuthnLevel;
unsigned long AuthnSvc;
SEC_WINNT_AUTH_IDENTITY* AuthIdentity;
RPC_SECURITY_QOS* SecurityQos;
} RPC_BINDING_HANDLE_SECURITY_V1, RPC_BINDING_HANDLE_SECURITY;
typedef struct
{
unsigned long Version;
unsigned long Flags;
unsigned long ProtocolSequence;
unsigned short* NetworkAddress;
unsigned short* StringEndpoint;
union
{
unsigned short* Reserved;
} u1;
UUID ObjectUuid;
} RPC_BINDING_HANDLE_TEMPLATE_V1, RPC_BINDING_HANDLE_TEMPLATE;
#define RPC_CALL_STATUS_IN_PROGRESS 0x01
#define RPC_CALL_STATUS_CANCELLED 0x02
#define RPC_CALL_STATUS_DISCONNECTED 0x03
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API RPC_STATUS RpcBindingCopy(RPC_BINDING_HANDLE SourceBinding,
RPC_BINDING_HANDLE* DestinationBinding);
WINPR_API RPC_STATUS RpcBindingFree(RPC_BINDING_HANDLE* Binding);
WINPR_API RPC_STATUS RpcBindingSetOption(RPC_BINDING_HANDLE hBinding, unsigned long option,
ULONG_PTR optionValue);
WINPR_API RPC_STATUS RpcBindingInqOption(RPC_BINDING_HANDLE hBinding, unsigned long option,
ULONG_PTR* pOptionValue);
WINPR_API RPC_STATUS RpcBindingFromStringBindingA(RPC_CSTR StringBinding,
RPC_BINDING_HANDLE* Binding);
WINPR_API RPC_STATUS RpcBindingFromStringBindingW(RPC_WSTR StringBinding,
RPC_BINDING_HANDLE* Binding);
WINPR_API RPC_STATUS RpcSsGetContextBinding(void* ContextHandle, RPC_BINDING_HANDLE* Binding);
WINPR_API RPC_STATUS RpcBindingInqObject(RPC_BINDING_HANDLE Binding, UUID* ObjectUuid);
WINPR_API RPC_STATUS RpcBindingReset(RPC_BINDING_HANDLE Binding);
WINPR_API RPC_STATUS RpcBindingSetObject(RPC_BINDING_HANDLE Binding, UUID* ObjectUuid);
WINPR_API RPC_STATUS RpcMgmtInqDefaultProtectLevel(unsigned long AuthnSvc,
unsigned long* AuthnLevel);
WINPR_API RPC_STATUS RpcBindingToStringBindingA(RPC_BINDING_HANDLE Binding,
RPC_CSTR* StringBinding);
WINPR_API RPC_STATUS RpcBindingToStringBindingW(RPC_BINDING_HANDLE Binding,
RPC_WSTR* StringBinding);
WINPR_API RPC_STATUS RpcBindingVectorFree(RPC_BINDING_VECTOR** BindingVector);
WINPR_API RPC_STATUS RpcStringBindingComposeA(RPC_CSTR ObjUuid, RPC_CSTR Protseq,
RPC_CSTR NetworkAddr, RPC_CSTR Endpoint,
RPC_CSTR Options, RPC_CSTR* StringBinding);
WINPR_API RPC_STATUS RpcStringBindingComposeW(RPC_WSTR ObjUuid, RPC_WSTR Protseq,
RPC_WSTR NetworkAddr, RPC_WSTR Endpoint,
RPC_WSTR Options, RPC_WSTR* StringBinding);
WINPR_API RPC_STATUS RpcStringBindingParseA(RPC_CSTR StringBinding, RPC_CSTR* ObjUuid,
RPC_CSTR* Protseq, RPC_CSTR* NetworkAddr,
RPC_CSTR* Endpoint, RPC_CSTR* NetworkOptions);
WINPR_API RPC_STATUS RpcStringBindingParseW(RPC_WSTR StringBinding, RPC_WSTR* ObjUuid,
RPC_WSTR* Protseq, RPC_WSTR* NetworkAddr,
RPC_WSTR* Endpoint, RPC_WSTR* NetworkOptions);
WINPR_API RPC_STATUS RpcStringFreeA(RPC_CSTR* String);
WINPR_API RPC_STATUS RpcStringFreeW(RPC_WSTR* String);
WINPR_API RPC_STATUS RpcIfInqId(RPC_IF_HANDLE RpcIfHandle, RPC_IF_ID* RpcIfId);
WINPR_API RPC_STATUS RpcNetworkIsProtseqValidA(RPC_CSTR Protseq);
WINPR_API RPC_STATUS RpcNetworkIsProtseqValidW(RPC_WSTR Protseq);
WINPR_API RPC_STATUS RpcMgmtInqComTimeout(RPC_BINDING_HANDLE Binding, unsigned int* Timeout);
WINPR_API RPC_STATUS RpcMgmtSetComTimeout(RPC_BINDING_HANDLE Binding, unsigned int Timeout);
WINPR_API RPC_STATUS RpcMgmtSetCancelTimeout(long Timeout);
WINPR_API RPC_STATUS RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** ProtseqVector);
WINPR_API RPC_STATUS RpcNetworkInqProtseqsW(RPC_PROTSEQ_VECTORW** ProtseqVector);
WINPR_API RPC_STATUS RpcObjectInqType(UUID* ObjUuid, UUID* TypeUuid);
WINPR_API RPC_STATUS RpcObjectSetInqFn(RPC_OBJECT_INQ_FN* InquiryFn);
WINPR_API RPC_STATUS RpcObjectSetType(UUID* ObjUuid, UUID* TypeUuid);
WINPR_API RPC_STATUS RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA** ProtseqVector);
WINPR_API RPC_STATUS RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW** ProtseqVector);
WINPR_API RPC_STATUS RpcServerInqBindings(RPC_BINDING_VECTOR** BindingVector);
WINPR_API RPC_STATUS RpcServerInqIf(RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid,
RPC_MGR_EPV** MgrEpv);
WINPR_API RPC_STATUS RpcServerListen(unsigned int MinimumCallThreads, unsigned int MaxCalls,
unsigned int DontWait);
WINPR_API RPC_STATUS RpcServerRegisterIf(RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid,
RPC_MGR_EPV* MgrEpv);
WINPR_API RPC_STATUS RpcServerRegisterIfEx(RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid,
RPC_MGR_EPV* MgrEpv, unsigned int Flags,
unsigned int MaxCalls,
RPC_IF_CALLBACK_FN* IfCallback);
WINPR_API RPC_STATUS RpcServerRegisterIf2(RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid,
RPC_MGR_EPV* MgrEpv, unsigned int Flags,
unsigned int MaxCalls, unsigned int MaxRpcSize,
RPC_IF_CALLBACK_FN* IfCallbackFn);
WINPR_API RPC_STATUS RpcServerUnregisterIf(RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid,
unsigned int WaitForCallsToComplete);
WINPR_API RPC_STATUS RpcServerUnregisterIfEx(RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid,
int RundownContextHandles);
WINPR_API RPC_STATUS RpcServerUseAllProtseqs(unsigned int MaxCalls, void* SecurityDescriptor);
WINPR_API RPC_STATUS RpcServerUseAllProtseqsEx(unsigned int MaxCalls, void* SecurityDescriptor,
PRPC_POLICY Policy);
WINPR_API RPC_STATUS RpcServerUseAllProtseqsIf(unsigned int MaxCalls, RPC_IF_HANDLE IfSpec,
void* SecurityDescriptor);
WINPR_API RPC_STATUS RpcServerUseAllProtseqsIfEx(unsigned int MaxCalls, RPC_IF_HANDLE IfSpec,
void* SecurityDescriptor, PRPC_POLICY Policy);
WINPR_API RPC_STATUS RpcServerUseProtseqA(RPC_CSTR Protseq, unsigned int MaxCalls,
void* SecurityDescriptor);
WINPR_API RPC_STATUS RpcServerUseProtseqExA(RPC_CSTR Protseq, unsigned int MaxCalls,
void* SecurityDescriptor, PRPC_POLICY Policy);
WINPR_API RPC_STATUS RpcServerUseProtseqW(RPC_WSTR Protseq, unsigned int MaxCalls,
void* SecurityDescriptor);
WINPR_API RPC_STATUS RpcServerUseProtseqExW(RPC_WSTR Protseq, unsigned int MaxCalls,
void* SecurityDescriptor, PRPC_POLICY Policy);
WINPR_API RPC_STATUS RpcServerUseProtseqEpA(RPC_CSTR Protseq, unsigned int MaxCalls,
RPC_CSTR Endpoint, void* SecurityDescriptor);
WINPR_API RPC_STATUS RpcServerUseProtseqEpExA(RPC_CSTR Protseq, unsigned int MaxCalls,
RPC_CSTR Endpoint, void* SecurityDescriptor,
PRPC_POLICY Policy);
WINPR_API RPC_STATUS RpcServerUseProtseqEpW(RPC_WSTR Protseq, unsigned int MaxCalls,
RPC_WSTR Endpoint, void* SecurityDescriptor);
WINPR_API RPC_STATUS RpcServerUseProtseqEpExW(RPC_WSTR Protseq, unsigned int MaxCalls,
RPC_WSTR Endpoint, void* SecurityDescriptor,
PRPC_POLICY Policy);
WINPR_API RPC_STATUS RpcServerUseProtseqIfA(RPC_CSTR Protseq, unsigned int MaxCalls,
RPC_IF_HANDLE IfSpec, void* SecurityDescriptor);
WINPR_API RPC_STATUS RpcServerUseProtseqIfExA(RPC_CSTR Protseq, unsigned int MaxCalls,
RPC_IF_HANDLE IfSpec, void* SecurityDescriptor,
PRPC_POLICY Policy);
WINPR_API RPC_STATUS RpcServerUseProtseqIfW(RPC_WSTR Protseq, unsigned int MaxCalls,
RPC_IF_HANDLE IfSpec, void* SecurityDescriptor);
WINPR_API RPC_STATUS RpcServerUseProtseqIfExW(RPC_WSTR Protseq, unsigned int MaxCalls,
RPC_IF_HANDLE IfSpec, void* SecurityDescriptor,
PRPC_POLICY Policy);
WINPR_API void RpcServerYield(void);
WINPR_API RPC_STATUS RpcMgmtStatsVectorFree(RPC_STATS_VECTOR** StatsVector);
WINPR_API RPC_STATUS RpcMgmtInqStats(RPC_BINDING_HANDLE Binding, RPC_STATS_VECTOR** Statistics);
WINPR_API RPC_STATUS RpcMgmtIsServerListening(RPC_BINDING_HANDLE Binding);
WINPR_API RPC_STATUS RpcMgmtStopServerListening(RPC_BINDING_HANDLE Binding);
WINPR_API RPC_STATUS RpcMgmtWaitServerListen(void);
WINPR_API RPC_STATUS RpcMgmtSetServerStackSize(unsigned long ThreadStackSize);
WINPR_API void RpcSsDontSerializeContext(void);
WINPR_API RPC_STATUS RpcMgmtEnableIdleCleanup(void);
WINPR_API RPC_STATUS RpcMgmtInqIfIds(RPC_BINDING_HANDLE Binding, RPC_IF_ID_VECTOR** IfIdVector);
WINPR_API RPC_STATUS RpcIfIdVectorFree(RPC_IF_ID_VECTOR** IfIdVector);
WINPR_API RPC_STATUS RpcMgmtInqServerPrincNameA(RPC_BINDING_HANDLE Binding,
unsigned long AuthnSvc,
RPC_CSTR* ServerPrincName);
WINPR_API RPC_STATUS RpcMgmtInqServerPrincNameW(RPC_BINDING_HANDLE Binding,
unsigned long AuthnSvc,
RPC_WSTR* ServerPrincName);
WINPR_API RPC_STATUS RpcServerInqDefaultPrincNameA(unsigned long AuthnSvc, RPC_CSTR* PrincName);
WINPR_API RPC_STATUS RpcServerInqDefaultPrincNameW(unsigned long AuthnSvc, RPC_WSTR* PrincName);
WINPR_API RPC_STATUS RpcEpResolveBinding(RPC_BINDING_HANDLE Binding, RPC_IF_HANDLE IfSpec);
WINPR_API RPC_STATUS RpcNsBindingInqEntryNameA(RPC_BINDING_HANDLE Binding,
unsigned long EntryNameSyntax,
RPC_CSTR* EntryName);
WINPR_API RPC_STATUS RpcNsBindingInqEntryNameW(RPC_BINDING_HANDLE Binding,
unsigned long EntryNameSyntax,
RPC_WSTR* EntryName);
WINPR_API RPC_STATUS RpcImpersonateClient(RPC_BINDING_HANDLE BindingHandle);
WINPR_API RPC_STATUS RpcRevertToSelfEx(RPC_BINDING_HANDLE BindingHandle);
WINPR_API RPC_STATUS RpcRevertToSelf(void);
WINPR_API RPC_STATUS RpcBindingInqAuthClientA(RPC_BINDING_HANDLE ClientBinding,
RPC_AUTHZ_HANDLE* Privs,
RPC_CSTR* ServerPrincName,
unsigned long* AuthnLevel,
unsigned long* AuthnSvc, unsigned long* AuthzSvc);
WINPR_API RPC_STATUS RpcBindingInqAuthClientW(RPC_BINDING_HANDLE ClientBinding,
RPC_AUTHZ_HANDLE* Privs,
RPC_WSTR* ServerPrincName,
unsigned long* AuthnLevel,
unsigned long* AuthnSvc, unsigned long* AuthzSvc);
WINPR_API RPC_STATUS RpcBindingInqAuthClientExA(RPC_BINDING_HANDLE ClientBinding,
RPC_AUTHZ_HANDLE* Privs,
RPC_CSTR* ServerPrincName,
unsigned long* AuthnLevel,
unsigned long* AuthnSvc,
unsigned long* AuthzSvc, unsigned long Flags);
WINPR_API RPC_STATUS RpcBindingInqAuthClientExW(RPC_BINDING_HANDLE ClientBinding,
RPC_AUTHZ_HANDLE* Privs,
RPC_WSTR* ServerPrincName,
unsigned long* AuthnLevel,
unsigned long* AuthnSvc,
unsigned long* AuthzSvc, unsigned long Flags);
WINPR_API RPC_STATUS RpcBindingInqAuthInfoA(RPC_BINDING_HANDLE Binding,
RPC_CSTR* ServerPrincName,
unsigned long* AuthnLevel, unsigned long* AuthnSvc,
RPC_AUTH_IDENTITY_HANDLE* AuthIdentity,
unsigned long* AuthzSvc);
WINPR_API RPC_STATUS RpcBindingInqAuthInfoW(RPC_BINDING_HANDLE Binding,
RPC_WSTR* ServerPrincName,
unsigned long* AuthnLevel, unsigned long* AuthnSvc,
RPC_AUTH_IDENTITY_HANDLE* AuthIdentity,
unsigned long* AuthzSvc);
WINPR_API RPC_STATUS RpcBindingSetAuthInfoA(RPC_BINDING_HANDLE Binding,
RPC_CSTR ServerPrincName, unsigned long AuthnLevel,
unsigned long AuthnSvc,
RPC_AUTH_IDENTITY_HANDLE AuthIdentity,
unsigned long AuthzSvc);
WINPR_API RPC_STATUS RpcBindingSetAuthInfoExA(RPC_BINDING_HANDLE Binding,
RPC_CSTR ServerPrincName,
unsigned long AuthnLevel, unsigned long AuthnSvc,
RPC_AUTH_IDENTITY_HANDLE AuthIdentity,
unsigned long AuthzSvc,
RPC_SECURITY_QOS* SecurityQos);
WINPR_API RPC_STATUS RpcBindingSetAuthInfoW(RPC_BINDING_HANDLE Binding,
RPC_WSTR ServerPrincName, unsigned long AuthnLevel,
unsigned long AuthnSvc,
RPC_AUTH_IDENTITY_HANDLE AuthIdentity,
unsigned long AuthzSvc);
WINPR_API RPC_STATUS RpcBindingSetAuthInfoExW(RPC_BINDING_HANDLE Binding,
RPC_WSTR ServerPrincName,
unsigned long AuthnLevel, unsigned long AuthnSvc,
RPC_AUTH_IDENTITY_HANDLE AuthIdentity,
unsigned long AuthzSvc,
RPC_SECURITY_QOS* SecurityQOS);
WINPR_API RPC_STATUS RpcBindingInqAuthInfoExA(
RPC_BINDING_HANDLE Binding, RPC_CSTR* ServerPrincName, unsigned long* AuthnLevel,
unsigned long* AuthnSvc, RPC_AUTH_IDENTITY_HANDLE* AuthIdentity, unsigned long* AuthzSvc,
unsigned long RpcQosVersion, RPC_SECURITY_QOS* SecurityQOS);
WINPR_API RPC_STATUS RpcBindingInqAuthInfoExW(
RPC_BINDING_HANDLE Binding, RPC_WSTR* ServerPrincName, unsigned long* AuthnLevel,
unsigned long* AuthnSvc, RPC_AUTH_IDENTITY_HANDLE* AuthIdentity, unsigned long* AuthzSvc,
unsigned long RpcQosVersion, RPC_SECURITY_QOS* SecurityQOS);
WINPR_API RPC_STATUS RpcServerRegisterAuthInfoA(RPC_CSTR ServerPrincName,
unsigned long AuthnSvc,
RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn, void* Arg);
WINPR_API RPC_STATUS RpcServerRegisterAuthInfoW(RPC_WSTR ServerPrincName,
unsigned long AuthnSvc,
RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn, void* Arg);
WINPR_API RPC_STATUS RpcBindingServerFromClient(RPC_BINDING_HANDLE ClientBinding,
RPC_BINDING_HANDLE* ServerBinding);
WINPR_API DECLSPEC_NORETURN void RpcRaiseException(RPC_STATUS exception);
WINPR_API RPC_STATUS RpcTestCancel(void);
WINPR_API RPC_STATUS RpcServerTestCancel(RPC_BINDING_HANDLE BindingHandle);
WINPR_API RPC_STATUS RpcCancelThread(void* Thread);
WINPR_API RPC_STATUS RpcCancelThreadEx(void* Thread, long Timeout);
WINPR_API RPC_STATUS UuidCreate(UUID* Uuid);
WINPR_API RPC_STATUS UuidCreateSequential(UUID* Uuid);
WINPR_API RPC_STATUS UuidToStringA(const UUID* Uuid, RPC_CSTR* StringUuid);
WINPR_API RPC_STATUS UuidFromStringA(RPC_CSTR StringUuid, UUID* Uuid);
WINPR_API RPC_STATUS UuidToStringW(const UUID* Uuid, RPC_WSTR* StringUuid);
WINPR_API RPC_STATUS UuidFromStringW(RPC_WSTR StringUuid, UUID* Uuid);
WINPR_API signed int UuidCompare(const UUID* Uuid1, const UUID* Uuid2, RPC_STATUS* Status);
WINPR_API RPC_STATUS UuidCreateNil(UUID* NilUuid);
WINPR_API int UuidEqual(const UUID* Uuid1, const UUID* Uuid2, RPC_STATUS* Status);
WINPR_API unsigned short UuidHash(const UUID* Uuid, RPC_STATUS* Status);
WINPR_API int UuidIsNil(const UUID* Uuid, RPC_STATUS* Status);
WINPR_API RPC_STATUS RpcEpRegisterNoReplaceA(RPC_IF_HANDLE IfSpec,
RPC_BINDING_VECTOR* BindingVector,
UUID_VECTOR* UuidVector, RPC_CSTR Annotation);
WINPR_API RPC_STATUS RpcEpRegisterNoReplaceW(RPC_IF_HANDLE IfSpec,
RPC_BINDING_VECTOR* BindingVector,
UUID_VECTOR* UuidVector, RPC_WSTR Annotation);
WINPR_API RPC_STATUS RpcEpRegisterA(RPC_IF_HANDLE IfSpec, RPC_BINDING_VECTOR* BindingVector,
UUID_VECTOR* UuidVector, RPC_CSTR Annotation);
WINPR_API RPC_STATUS RpcEpRegisterW(RPC_IF_HANDLE IfSpec, RPC_BINDING_VECTOR* BindingVector,
UUID_VECTOR* UuidVector, RPC_WSTR Annotation);
WINPR_API RPC_STATUS RpcEpUnregister(RPC_IF_HANDLE IfSpec, RPC_BINDING_VECTOR* BindingVector,
UUID_VECTOR* UuidVector);
WINPR_API RPC_STATUS DceErrorInqTextA(RPC_STATUS RpcStatus, RPC_CSTR ErrorText);
WINPR_API RPC_STATUS DceErrorInqTextW(RPC_STATUS RpcStatus, RPC_WSTR ErrorText);
WINPR_API RPC_STATUS RpcMgmtEpEltInqBegin(RPC_BINDING_HANDLE EpBinding,
unsigned long InquiryType, RPC_IF_ID* IfId,
unsigned long VersOption, UUID* ObjectUuid,
RPC_EP_INQ_HANDLE* InquiryContext);
WINPR_API RPC_STATUS RpcMgmtEpEltInqDone(RPC_EP_INQ_HANDLE* InquiryContext);
WINPR_API RPC_STATUS RpcMgmtEpEltInqNextA(RPC_EP_INQ_HANDLE InquiryContext, RPC_IF_ID* IfId,
RPC_BINDING_HANDLE* Binding, UUID* ObjectUuid,
RPC_CSTR* Annotation);
WINPR_API RPC_STATUS RpcMgmtEpEltInqNextW(RPC_EP_INQ_HANDLE InquiryContext, RPC_IF_ID* IfId,
RPC_BINDING_HANDLE* Binding, UUID* ObjectUuid,
RPC_WSTR* Annotation);
WINPR_API RPC_STATUS RpcMgmtEpUnregister(RPC_BINDING_HANDLE EpBinding, RPC_IF_ID* IfId,
RPC_BINDING_HANDLE Binding, UUID* ObjectUuid);
WINPR_API RPC_STATUS RpcMgmtSetAuthorizationFn(RPC_MGMT_AUTHORIZATION_FN AuthorizationFn);
WINPR_API RPC_STATUS RpcServerInqBindingHandle(RPC_BINDING_HANDLE* Binding);
#ifdef __cplusplus
}
#endif
#endif
#endif /* WINPR_RPC_H */

View File

@@ -0,0 +1,59 @@
/**
* WinPR: Windows Portable Runtime
* Security Accounts Manager (SAM)
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_UTILS_SAM_H
#define WINPR_UTILS_SAM_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
typedef struct winpr_sam WINPR_SAM;
struct winpr_sam_entry
{
LPSTR User;
UINT32 UserLength;
LPSTR Domain;
UINT32 DomainLength;
BYTE LmHash[16];
BYTE NtHash[16];
};
typedef struct winpr_sam_entry WINPR_SAM_ENTRY;
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API WINPR_SAM_ENTRY* SamLookupUserA(WINPR_SAM* sam, LPCSTR User, UINT32 UserLength,
LPCSTR Domain, UINT32 DomainLength);
WINPR_API WINPR_SAM_ENTRY* SamLookupUserW(WINPR_SAM* sam, LPCWSTR User, UINT32 UserLength,
LPCWSTR Domain, UINT32 DomainLength);
WINPR_API void SamResetEntry(WINPR_SAM_ENTRY* entry);
WINPR_API void SamFreeEntry(WINPR_SAM* sam, WINPR_SAM_ENTRY* entry);
WINPR_API WINPR_SAM* SamOpen(const char* filename, BOOL readOnly);
WINPR_API void SamClose(WINPR_SAM* sam);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_UTILS_SAM_H */

View File

@@ -0,0 +1,284 @@
/**
* WinPR: Windows Portable Runtime
* Schannel Security Package
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_SSPI_SCHANNEL_H
#define WINPR_SSPI_SCHANNEL_H
#include <winpr/sspi.h>
#include <winpr/crypto.h>
#if defined(_WIN32) && !defined(_UWP)
#include <schannel.h>
#else
#define SCHANNEL_NAME_A "Schannel"
#define SCHANNEL_NAME_W L"Schannel"
#ifdef _UNICODE
#define SCHANNEL_NAME SCHANNEL_NAME_W
#else
#define SCHANNEL_NAME SCHANNEL_NAME_A
#endif
#define SECPKG_ATTR_SUPPORTED_ALGS 86
#define SECPKG_ATTR_CIPHER_STRENGTHS 87
#define SECPKG_ATTR_SUPPORTED_PROTOCOLS 88
typedef struct
{
DWORD cSupportedAlgs;
ALG_ID* palgSupportedAlgs;
} SecPkgCred_SupportedAlgs, *PSecPkgCred_SupportedAlgs;
typedef struct
{
DWORD dwMinimumCipherStrength;
DWORD dwMaximumCipherStrength;
} SecPkgCred_CipherStrengths, *PSecPkgCred_CipherStrengths;
typedef struct
{
DWORD grbitProtocol;
} SecPkgCred_SupportedProtocols, *PSecPkgCred_SupportedProtocols;
enum eTlsSignatureAlgorithm
{
TlsSignatureAlgorithm_Anonymous = 0,
TlsSignatureAlgorithm_Rsa = 1,
TlsSignatureAlgorithm_Dsa = 2,
TlsSignatureAlgorithm_Ecdsa = 3
};
enum eTlsHashAlgorithm
{
TlsHashAlgorithm_None = 0,
TlsHashAlgorithm_Md5 = 1,
TlsHashAlgorithm_Sha1 = 2,
TlsHashAlgorithm_Sha224 = 3,
TlsHashAlgorithm_Sha256 = 4,
TlsHashAlgorithm_Sha384 = 5,
TlsHashAlgorithm_Sha512 = 6
};
#define SCH_CRED_V1 0x00000001
#define SCH_CRED_V2 0x00000002
#define SCH_CRED_VERSION 0x00000002
#define SCH_CRED_V3 0x00000003
#define SCHANNEL_CRED_VERSION 0x00000004
typedef struct
{
DWORD dwVersion;
DWORD cCreds;
PCCERT_CONTEXT* paCred;
HCERTSTORE hRootStore;
DWORD cSupportedAlgs;
ALG_ID* palgSupportedAlgs;
DWORD grbitEnabledProtocols;
DWORD dwMinimumCipherStrength;
DWORD dwMaximumCipherStrength;
DWORD dwSessionLifespan;
DWORD dwFlags;
DWORD dwCredFormat;
} SCHANNEL_CRED, *PSCHANNEL_CRED;
#define SCH_CRED_FORMAT_CERT_CONTEXT 0x00000000
#define SCH_CRED_FORMAT_CERT_HASH 0x00000001
#define SCH_CRED_FORMAT_CERT_HASH_STORE 0x00000002
#define SCH_CRED_MAX_STORE_NAME_SIZE 128
#define SCH_CRED_MAX_SUPPORTED_ALGS 256
#define SCH_CRED_MAX_SUPPORTED_CERTS 100
typedef struct
{
DWORD dwLength;
DWORD dwFlags;
HCRYPTPROV hProv;
BYTE ShaHash[20];
} SCHANNEL_CERT_HASH, *PSCHANNEL_CERT_HASH;
typedef struct
{
DWORD dwLength;
DWORD dwFlags;
HCRYPTPROV hProv;
BYTE ShaHash[20];
WCHAR pwszStoreName[SCH_CRED_MAX_STORE_NAME_SIZE];
} SCHANNEL_CERT_HASH_STORE, *PSCHANNEL_CERT_HASH_STORE;
#define SCH_MACHINE_CERT_HASH 0x00000001
#define SCH_CRED_NO_SYSTEM_MAPPER 0x00000002
#define SCH_CRED_NO_SERVERNAME_CHECK 0x00000004
#define SCH_CRED_MANUAL_CRED_VALIDATION 0x00000008
#define SCH_CRED_NO_DEFAULT_CREDS 0x00000010
#define SCH_CRED_AUTO_CRED_VALIDATION 0x00000020
#define SCH_CRED_USE_DEFAULT_CREDS 0x00000040
#define SCH_CRED_DISABLE_RECONNECTS 0x00000080
#define SCH_CRED_REVOCATION_CHECK_END_CERT 0x00000100
#define SCH_CRED_REVOCATION_CHECK_CHAIN 0x00000200
#define SCH_CRED_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT 0x00000400
#define SCH_CRED_IGNORE_NO_REVOCATION_CHECK 0x00000800
#define SCH_CRED_IGNORE_REVOCATION_OFFLINE 0x00001000
#define SCH_CRED_RESTRICTED_ROOTS 0x00002000
#define SCH_CRED_REVOCATION_CHECK_CACHE_ONLY 0x00004000
#define SCH_CRED_CACHE_ONLY_URL_RETRIEVAL 0x00008000
#define SCH_CRED_MEMORY_STORE_CERT 0x00010000
#define SCH_CRED_CACHE_ONLY_URL_RETRIEVAL_ON_CREATE 0x00020000
#define SCH_SEND_ROOT_CERT 0x00040000
#define SCH_CRED_SNI_CREDENTIAL 0x00080000
#define SCH_CRED_SNI_ENABLE_OCSP 0x00100000
#define SCH_SEND_AUX_RECORD 0x00200000
#define SCHANNEL_RENEGOTIATE 0
#define SCHANNEL_SHUTDOWN 1
#define SCHANNEL_ALERT 2
#define SCHANNEL_SESSION 3
typedef struct
{
DWORD dwTokenType;
DWORD dwAlertType;
DWORD dwAlertNumber;
} SCHANNEL_ALERT_TOKEN;
#define TLS1_ALERT_WARNING 1
#define TLS1_ALERT_FATAL 2
#define TLS1_ALERT_CLOSE_NOTIFY 0
#define TLS1_ALERT_UNEXPECTED_MESSAGE 10
#define TLS1_ALERT_BAD_RECORD_MAC 20
#define TLS1_ALERT_DECRYPTION_FAILED 21
#define TLS1_ALERT_RECORD_OVERFLOW 22
#define TLS1_ALERT_DECOMPRESSION_FAIL 30
#define TLS1_ALERT_HANDSHAKE_FAILURE 40
#define TLS1_ALERT_BAD_CERTIFICATE 42
#define TLS1_ALERT_UNSUPPORTED_CERT 43
#define TLS1_ALERT_CERTIFICATE_REVOKED 44
#define TLS1_ALERT_CERTIFICATE_EXPIRED 45
#define TLS1_ALERT_CERTIFICATE_UNKNOWN 46
#define TLS1_ALERT_ILLEGAL_PARAMETER 47
#define TLS1_ALERT_UNKNOWN_CA 48
#define TLS1_ALERT_ACCESS_DENIED 49
#define TLS1_ALERT_DECODE_ERROR 50
#define TLS1_ALERT_DECRYPT_ERROR 51
#define TLS1_ALERT_EXPORT_RESTRICTION 60
#define TLS1_ALERT_PROTOCOL_VERSION 70
#define TLS1_ALERT_INSUFFIENT_SECURITY 71
#define TLS1_ALERT_INTERNAL_ERROR 80
#define TLS1_ALERT_USER_CANCELED 90
#define TLS1_ALERT_NO_RENEGOTIATION 100
#define TLS1_ALERT_UNSUPPORTED_EXT 110
#define SSL_SESSION_ENABLE_RECONNECTS 1
#define SSL_SESSION_DISABLE_RECONNECTS 2
typedef struct
{
DWORD dwTokenType;
DWORD dwFlags;
} SCHANNEL_SESSION_TOKEN;
typedef struct
{
DWORD cbLength;
ALG_ID aiHash;
DWORD cbHash;
BYTE HashValue[36];
BYTE CertThumbprint[20];
} SCHANNEL_CLIENT_SIGNATURE, *PSCHANNEL_CLIENT_SIGNATURE;
#define SP_PROT_SSL3_SERVER 0x00000010
#define SP_PROT_SSL3_CLIENT 0x00000020
#define SP_PROT_SSL3 (SP_PROT_SSL3_SERVER | SP_PROT_SSL3_CLIENT)
#define SP_PROT_TLS1_SERVER 0x00000040
#define SP_PROT_TLS1_CLIENT 0x00000080
#define SP_PROT_TLS1 (SP_PROT_TLS1_SERVER | SP_PROT_TLS1_CLIENT)
#define SP_PROT_SSL3TLS1_CLIENTS (SP_PROT_TLS1_CLIENT | SP_PROT_SSL3_CLIENT)
#define SP_PROT_SSL3TLS1_SERVERS (SP_PROT_TLS1_SERVER | SP_PROT_SSL3_SERVER)
#define SP_PROT_SSL3TLS1 (SP_PROT_SSL3 | SP_PROT_TLS1)
#define SP_PROT_UNI_SERVER 0x40000000
#define SP_PROT_UNI_CLIENT 0x80000000
#define SP_PROT_UNI (SP_PROT_UNI_SERVER | SP_PROT_UNI_CLIENT)
#define SP_PROT_ALL 0xFFFFFFFF
#define SP_PROT_NONE 0
#define SP_PROT_CLIENTS (SP_PROT_SSL3_CLIENT | SP_PROT_UNI_CLIENT | SP_PROT_TLS1_CLIENT)
#define SP_PROT_SERVERS (SP_PROT_SSL3_SERVER | SP_PROT_UNI_SERVER | SP_PROT_TLS1_SERVER)
#define SP_PROT_TLS1_0_SERVER SP_PROT_TLS1_SERVER
#define SP_PROT_TLS1_0_CLIENT SP_PROT_TLS1_CLIENT
#define SP_PROT_TLS1_0 (SP_PROT_TLS1_0_SERVER | SP_PROT_TLS1_0_CLIENT)
#define SP_PROT_TLS1_1_SERVER 0x00000100
#define SP_PROT_TLS1_1_CLIENT 0x00000200
#define SP_PROT_TLS1_1 (SP_PROT_TLS1_1_SERVER | SP_PROT_TLS1_1_CLIENT)
#define SP_PROT_TLS1_2_SERVER 0x00000400
#define SP_PROT_TLS1_2_CLIENT 0x00000800
#define SP_PROT_TLS1_2 (SP_PROT_TLS1_2_SERVER | SP_PROT_TLS1_2_CLIENT)
#define SP_PROT_DTLS_SERVER 0x00010000
#define SP_PROT_DTLS_CLIENT 0x00020000
#define SP_PROT_DTLS (SP_PROT_DTLS_SERVER | SP_PROT_DTLS_CLIENT)
#define SP_PROT_DTLS1_0_SERVER SP_PROT_DTLS_SERVER
#define SP_PROT_DTLS1_0_CLIENT SP_PROT_DTLS_CLIENT
#define SP_PROT_DTLS1_0 (SP_PROT_DTLS1_0_SERVER | SP_PROT_DTLS1_0_CLIENT)
#define SP_PROT_DTLS1_X_SERVER SP_PROT_DTLS1_0_SERVER
#define SP_PROT_DTLS1_X_CLIENT SP_PROT_DTLS1_0_CLIENT
#define SP_PROT_DTLS1_X (SP_PROT_DTLS1_X_SERVER | SP_PROT_DTLS1_X_CLIENT)
#define SP_PROT_TLS1_1PLUS_SERVER (SP_PROT_TLS1_1_SERVER | SP_PROT_TLS1_2_SERVER)
#define SP_PROT_TLS1_1PLUS_CLIENT (SP_PROT_TLS1_1_CLIENT | SP_PROT_TLS1_2_CLIENT)
#define SP_PROT_TLS1_1PLUS (SP_PROT_TLS1_1PLUS_SERVER | SP_PROT_TLS1_1PLUS_CLIENT)
#define SP_PROT_TLS1_X_SERVER \
(SP_PROT_TLS1_0_SERVER | SP_PROT_TLS1_1_SERVER | SP_PROT_TLS1_2_SERVER)
#define SP_PROT_TLS1_X_CLIENT \
(SP_PROT_TLS1_0_CLIENT | SP_PROT_TLS1_1_CLIENT | SP_PROT_TLS1_2_CLIENT)
#define SP_PROT_TLS1_X (SP_PROT_TLS1_X_SERVER | SP_PROT_TLS1_X_CLIENT)
#define SP_PROT_SSL3TLS1_X_CLIENTS (SP_PROT_TLS1_X_CLIENT | SP_PROT_SSL3_CLIENT)
#define SP_PROT_SSL3TLS1_X_SERVERS (SP_PROT_TLS1_X_SERVER | SP_PROT_SSL3_SERVER)
#define SP_PROT_SSL3TLS1_X (SP_PROT_SSL3 | SP_PROT_TLS1_X)
#define SP_PROT_X_CLIENTS (SP_PROT_CLIENTS | SP_PROT_TLS1_X_CLIENT | SP_PROT_DTLS1_X_CLIENT)
#define SP_PROT_X_SERVERS (SP_PROT_SERVERS | SP_PROT_TLS1_X_SERVER | SP_PROT_DTLS1_X_SERVER)
#endif
#endif /* WINPR_SSPI_SCHANNEL_H */

View File

@@ -0,0 +1,111 @@
/**
* WinPR: Windows Portable Runtime
* Schannel Security Package
*
* Copyright 2023 David Fort <contact@hardening-consulting.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_SECAPI_H_
#define WINPR_SECAPI_H_
#ifdef _WIN32
#define _NTDEF_
#include <ntsecapi.h>
#define KerbInvalidValue 0
#else
#include <winpr/wtypes.h>
typedef enum
{
KerbInvalidValue = 0, /** @since version 3.9.0 */
KerbInteractiveLogon = 2,
KerbSmartCardLogon = 6,
KerbWorkstationUnlockLogon = 7,
KerbSmartCardUnlockLogon = 8,
KerbProxyLogon = 9,
KerbTicketLogon = 10,
KerbTicketUnlockLogon = 11,
KerbS4ULogon = 12, /** @since _WIN32_WINNT >= 0x0501 */
KerbCertificateLogon = 13, /** @since _WIN32_WINNT >= 0x0600 */
KerbCertificateS4ULogon = 14, /** @since _WIN32_WINNT >= 0x0600 */
KerbCertificateUnlockLogon = 15, /** @since _WIN32_WINNT >= 0x0600 */
KerbNoElevationLogon = 83, /** @since _WIN32_WINNT >= 0x0602 */
KerbLuidLogon = 84 /** @since _WIN32_WINNT >= 0x0602 */
} KERB_LOGON_SUBMIT_TYPE,
*PKERB_LOGON_SUBMIT_TYPE;
typedef struct
{
KERB_LOGON_SUBMIT_TYPE MessageType;
ULONG Flags;
ULONG ServiceTicketLength;
ULONG TicketGrantingTicketLength;
PUCHAR ServiceTicket;
PUCHAR TicketGrantingTicket;
} KERB_TICKET_LOGON, *PKERB_TICKET_LOGON;
#define KERB_LOGON_FLAG_ALLOW_EXPIRED_TICKET 0x1
#define MSV1_0_OWF_PASSWORD_LENGTH 16
typedef struct
{
ULONG Version;
ULONG Flags;
UCHAR LmPassword[MSV1_0_OWF_PASSWORD_LENGTH];
UCHAR NtPassword[MSV1_0_OWF_PASSWORD_LENGTH];
} MSV1_0_SUPPLEMENTAL_CREDENTIAL, *PMSV1_0_SUPPLEMENTAL_CREDENTIAL;
#define MSV1_0_CRED_VERSION_REMOTE 0xffff0002
typedef enum
{
InvalidCredKey,
DeprecatedIUMCredKey,
DomainUserCredKey,
LocalUserCredKey,
ExternallySuppliedCredKey
} MSV1_0_CREDENTIAL_KEY_TYPE;
#define MSV1_0_CREDENTIAL_KEY_LENGTH 20
#define MSV1_0_CRED_LM_PRESENT 0x1
#define MSV1_0_CRED_NT_PRESENT 0x2
#define MSV1_0_CRED_REMOVED 0x4
#define MSV1_0_CRED_CREDKEY_PRESENT 0x8
#define MSV1_0_CRED_SHA_PRESENT 0x10
typedef struct
{
UCHAR Data[MSV1_0_CREDENTIAL_KEY_LENGTH];
} MSV1_0_CREDENTIAL_KEY, *PMSV1_0_CREDENTIAL_KEY;
typedef struct
{
ULONG Version;
ULONG Flags;
MSV1_0_CREDENTIAL_KEY CredentialKey;
MSV1_0_CREDENTIAL_KEY_TYPE CredentialKeyType;
ULONG EncryptedCredsSize;
UCHAR EncryptedCreds[1];
} MSV1_0_REMOTE_SUPPLEMENTAL_CREDENTIAL, *PMSV1_0_REMOTE_SUPPLEMENTAL_CREDENTIAL;
#endif /* _WIN32 */
#ifndef KERB_LOGON_FLAG_REDIRECTED
#define KERB_LOGON_FLAG_REDIRECTED 0x2
#endif
#endif /* WINPR_SECAPI_H_ */

View File

@@ -0,0 +1,449 @@
/**
* WinPR: Windows Portable Runtime
* Security Definitions
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_SECURITY_H
#define WINPR_SECURITY_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
/**
* Windows Integrity Mechanism Design:
* http://msdn.microsoft.com/en-us/library/bb625963.aspx
*/
#ifndef _WIN32
#include <winpr/nt.h>
#define ANYSIZE_ARRAY 1
typedef enum
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
} SECURITY_IMPERSONATION_LEVEL,
*PSECURITY_IMPERSONATION_LEVEL;
#define SECURITY_MAX_IMPERSONATION_LEVEL SecurityDelegation
#define SECURITY_MIN_IMPERSONATION_LEVEL SecurityAnonymous
#define DEFAULT_IMPERSONATION_LEVEL SecurityImpersonation
#define VALID_IMPERSONATION_LEVEL(L) \
(((L) >= SECURITY_MIN_IMPERSONATION_LEVEL) && ((L) <= SECURITY_MAX_IMPERSONATION_LEVEL))
#define TOKEN_ASSIGN_PRIMARY (0x0001)
#define TOKEN_DUPLICATE (0x0002)
#define TOKEN_IMPERSONATE (0x0004)
#define TOKEN_QUERY (0x0008)
#define TOKEN_QUERY_SOURCE (0x0010)
#define TOKEN_ADJUST_PRIVILEGES (0x0020)
#define TOKEN_ADJUST_GROUPS (0x0040)
#define TOKEN_ADJUST_DEFAULT (0x0080)
#define TOKEN_ADJUST_SESSIONID (0x0100)
#define TOKEN_ALL_ACCESS_P \
(STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | \
TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | \
TOKEN_ADJUST_DEFAULT)
#define TOKEN_ALL_ACCESS (TOKEN_ALL_ACCESS_P | TOKEN_ADJUST_SESSIONID)
#define TOKEN_READ (STANDARD_RIGHTS_READ | TOKEN_QUERY)
#define TOKEN_WRITE \
(STANDARD_RIGHTS_WRITE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT)
#define TOKEN_EXECUTE (STANDARD_RIGHTS_EXECUTE)
#define TOKEN_MANDATORY_POLICY_OFF 0x0
#define TOKEN_MANDATORY_POLICY_NO_WRITE_UP 0x1
#define TOKEN_MANDATORY_POLICY_NEW_PROCESS_MIN 0x2
#define TOKEN_MANDATORY_POLICY_VALID_MASK \
(TOKEN_MANDATORY_POLICY_NO_WRITE_UP | TOKEN_MANDATORY_POLICY_NEW_PROCESS_MIN)
#define POLICY_AUDIT_SUBCATEGORY_COUNT (56)
#define TOKEN_SOURCE_LENGTH 8
#define SID_REVISION (1)
#define SID_MAX_SUB_AUTHORITIES (15)
#define SID_RECOMMENDED_SUB_AUTHORITIES (1)
#define SID_HASH_SIZE 32
#define SECURITY_MANDATORY_UNTRUSTED_RID 0x0000
#define SECURITY_MANDATORY_LOW_RID 0x1000
#define SECURITY_MANDATORY_MEDIUM_RID 0x2000
#define SECURITY_MANDATORY_HIGH_RID 0x3000
#define SECURITY_MANDATORY_SYSTEM_RID 0x4000
#define SECURITY_NULL_SID_AUTHORITY \
{ \
0, 0, 0, 0, 0, 0 \
}
#define SECURITY_WORLD_SID_AUTHORITY \
{ \
0, 0, 0, 0, 0, 1 \
}
#define SECURITY_LOCAL_SID_AUTHORITY \
{ \
0, 0, 0, 0, 0, 2 \
}
#define SECURITY_CREATOR_SID_AUTHORITY \
{ \
0, 0, 0, 0, 0, 3 \
}
#define SECURITY_NON_UNIQUE_AUTHORITY \
{ \
0, 0, 0, 0, 0, 4 \
}
#define SECURITY_RESOURCE_MANAGER_AUTHORITY \
{ \
0, 0, 0, 0, 0, 9 \
}
#define SECURITY_NULL_RID (0x00000000L)
#define SECURITY_WORLD_RID (0x00000000L)
#define SECURITY_LOCAL_RID (0x00000000L)
#define SECURITY_LOCAL_LOGON_RID (0x00000001L)
#define SECURITY_CREATOR_OWNER_RID (0x00000000L)
#define SECURITY_CREATOR_GROUP_RID (0x00000001L)
#define SECURITY_CREATOR_OWNER_SERVER_RID (0x00000002L)
#define SECURITY_CREATOR_GROUP_SERVER_RID (0x00000003L)
#define SECURITY_CREATOR_OWNER_RIGHTS_RID (0x00000004L)
typedef PVOID PACCESS_TOKEN;
typedef PVOID PCLAIMS_BLOB;
typedef struct
{
LUID Luid;
DWORD Attributes;
} LUID_AND_ATTRIBUTES, *PLUID_AND_ATTRIBUTES;
typedef LUID_AND_ATTRIBUTES LUID_AND_ATTRIBUTES_ARRAY[ANYSIZE_ARRAY];
typedef LUID_AND_ATTRIBUTES_ARRAY* PLUID_AND_ATTRIBUTES_ARRAY;
typedef struct
{
BYTE Value[6];
} SID_IDENTIFIER_AUTHORITY, *PSID_IDENTIFIER_AUTHORITY;
typedef struct
{
BYTE Revision;
BYTE SubAuthorityCount;
SID_IDENTIFIER_AUTHORITY IdentifierAuthority;
DWORD SubAuthority[ANYSIZE_ARRAY];
} SID, *PISID;
typedef enum
{
SidTypeUser = 1,
SidTypeGroup,
SidTypeDomain,
SidTypeAlias,
SidTypeWellKnownGroup,
SidTypeDeletedAccount,
SidTypeInvalid,
SidTypeUnknown,
SidTypeComputer,
SidTypeLabel
} SID_NAME_USE,
*PSID_NAME_USE;
typedef struct
{
PSID Sid;
DWORD Attributes;
} SID_AND_ATTRIBUTES, *PSID_AND_ATTRIBUTES;
typedef SID_AND_ATTRIBUTES SID_AND_ATTRIBUTES_ARRAY[ANYSIZE_ARRAY];
typedef SID_AND_ATTRIBUTES_ARRAY* PSID_AND_ATTRIBUTES_ARRAY;
typedef ULONG_PTR SID_HASH_ENTRY, *PSID_HASH_ENTRY;
typedef struct
{
DWORD SidCount;
PSID_AND_ATTRIBUTES SidAttr;
SID_HASH_ENTRY Hash[SID_HASH_SIZE];
} SID_AND_ATTRIBUTES_HASH, *PSID_AND_ATTRIBUTES_HASH;
typedef enum
{
TokenPrimary = 1,
TokenImpersonation
} TOKEN_TYPE;
typedef TOKEN_TYPE* PTOKEN_TYPE;
typedef enum
{
TokenElevationTypeDefault = 1,
TokenElevationTypeFull,
TokenElevationTypeLimited
} TOKEN_ELEVATION_TYPE,
*PTOKEN_ELEVATION_TYPE;
typedef enum
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUIAccess,
TokenMandatoryPolicy,
TokenLogonSid,
TokenIsAppContainer,
TokenCapabilities,
TokenAppContainerSid,
TokenAppContainerNumber,
TokenUserClaimAttributes,
TokenDeviceClaimAttributes,
TokenRestrictedUserClaimAttributes,
TokenRestrictedDeviceClaimAttributes,
TokenDeviceGroups,
TokenRestrictedDeviceGroups,
TokenSecurityAttributes,
TokenIsRestricted,
MaxTokenInfoClass
} TOKEN_INFORMATION_CLASS,
*PTOKEN_INFORMATION_CLASS;
typedef struct
{
SID_AND_ATTRIBUTES User;
} TOKEN_USER, *PTOKEN_USER;
typedef struct
{
DWORD GroupCount;
SID_AND_ATTRIBUTES Groups[ANYSIZE_ARRAY];
} TOKEN_GROUPS, *PTOKEN_GROUPS;
typedef struct
{
DWORD PrivilegeCount;
LUID_AND_ATTRIBUTES Privileges[ANYSIZE_ARRAY];
} TOKEN_PRIVILEGES, *PTOKEN_PRIVILEGES;
typedef struct
{
PSID Owner;
} TOKEN_OWNER, *PTOKEN_OWNER;
typedef struct
{
PSID PrimaryGroup;
} TOKEN_PRIMARY_GROUP, *PTOKEN_PRIMARY_GROUP;
typedef struct
{
PACL DefaultDacl;
} TOKEN_DEFAULT_DACL, *PTOKEN_DEFAULT_DACL;
typedef struct
{
PCLAIMS_BLOB UserClaims;
} TOKEN_USER_CLAIMS, *PTOKEN_USER_CLAIMS;
typedef struct
{
PCLAIMS_BLOB DeviceClaims;
} TOKEN_DEVICE_CLAIMS, *PTOKEN_DEVICE_CLAIMS;
typedef struct
{
DWORD SidCount;
DWORD SidLength;
PSID_AND_ATTRIBUTES Sids;
DWORD RestrictedSidCount;
DWORD RestrictedSidLength;
PSID_AND_ATTRIBUTES RestrictedSids;
DWORD PrivilegeCount;
DWORD PrivilegeLength;
PLUID_AND_ATTRIBUTES Privileges;
LUID AuthenticationId;
} TOKEN_GROUPS_AND_PRIVILEGES, *PTOKEN_GROUPS_AND_PRIVILEGES;
typedef struct
{
HANDLE LinkedToken;
} TOKEN_LINKED_TOKEN, *PTOKEN_LINKED_TOKEN;
typedef struct
{
DWORD TokenIsElevated;
} TOKEN_ELEVATION, *PTOKEN_ELEVATION;
typedef struct
{
SID_AND_ATTRIBUTES Label;
} TOKEN_MANDATORY_LABEL, *PTOKEN_MANDATORY_LABEL;
typedef struct
{
DWORD Policy;
} TOKEN_MANDATORY_POLICY, *PTOKEN_MANDATORY_POLICY;
typedef struct
{
PSID_AND_ATTRIBUTES_HASH SidHash;
PSID_AND_ATTRIBUTES_HASH RestrictedSidHash;
PTOKEN_PRIVILEGES Privileges;
LUID AuthenticationId;
TOKEN_TYPE TokenType;
SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
TOKEN_MANDATORY_POLICY MandatoryPolicy;
DWORD Flags;
DWORD AppContainerNumber;
PSID PackageSid;
PSID_AND_ATTRIBUTES_HASH CapabilitiesHash;
} TOKEN_ACCESS_INFORMATION, *PTOKEN_ACCESS_INFORMATION;
typedef struct
{
BYTE PerUserPolicy[((POLICY_AUDIT_SUBCATEGORY_COUNT) >> 1) + 1];
} TOKEN_AUDIT_POLICY, *PTOKEN_AUDIT_POLICY;
typedef struct
{
CHAR SourceName[TOKEN_SOURCE_LENGTH];
LUID SourceIdentifier;
} TOKEN_SOURCE, *PTOKEN_SOURCE;
typedef struct
{
LUID TokenId;
LUID AuthenticationId;
LARGE_INTEGER ExpirationTime;
TOKEN_TYPE TokenType;
SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
DWORD DynamicCharged;
DWORD DynamicAvailable;
DWORD GroupCount;
DWORD PrivilegeCount;
LUID ModifiedId;
} TOKEN_STATISTICS, *PTOKEN_STATISTICS;
typedef struct
{
LUID TokenId;
LUID AuthenticationId;
LUID ModifiedId;
TOKEN_SOURCE TokenSource;
} TOKEN_CONTROL, *PTOKEN_CONTROL;
typedef struct
{
LUID OriginatingLogonSession;
} TOKEN_ORIGIN, *PTOKEN_ORIGIN;
typedef enum
{
MandatoryLevelUntrusted = 0,
MandatoryLevelLow,
MandatoryLevelMedium,
MandatoryLevelHigh,
MandatoryLevelSystem,
MandatoryLevelSecureProcess,
MandatoryLevelCount
} MANDATORY_LEVEL,
*PMANDATORY_LEVEL;
typedef struct
{
PSID TokenAppContainer;
} TOKEN_APPCONTAINER_INFORMATION, *PTOKEN_APPCONTAINER_INFORMATION;
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API BOOL InitializeSecurityDescriptor(PSECURITY_DESCRIPTOR pSecurityDescriptor,
DWORD dwRevision);
WINPR_API DWORD GetSecurityDescriptorLength(PSECURITY_DESCRIPTOR pSecurityDescriptor);
WINPR_API BOOL IsValidSecurityDescriptor(PSECURITY_DESCRIPTOR pSecurityDescriptor);
WINPR_API BOOL GetSecurityDescriptorControl(PSECURITY_DESCRIPTOR pSecurityDescriptor,
PSECURITY_DESCRIPTOR_CONTROL pControl,
LPDWORD lpdwRevision);
WINPR_API BOOL SetSecurityDescriptorControl(PSECURITY_DESCRIPTOR pSecurityDescriptor,
SECURITY_DESCRIPTOR_CONTROL ControlBitsOfInterest,
SECURITY_DESCRIPTOR_CONTROL ControlBitsToSet);
WINPR_API BOOL GetSecurityDescriptorDacl(PSECURITY_DESCRIPTOR pSecurityDescriptor,
LPBOOL lpbDaclPresent, PACL* pDacl,
LPBOOL lpbDaclDefaulted);
WINPR_API BOOL SetSecurityDescriptorDacl(PSECURITY_DESCRIPTOR pSecurityDescriptor,
BOOL bDaclPresent, PACL pDacl, BOOL bDaclDefaulted);
WINPR_API BOOL GetSecurityDescriptorGroup(PSECURITY_DESCRIPTOR pSecurityDescriptor,
PSID* pGroup, LPBOOL lpbGroupDefaulted);
WINPR_API BOOL SetSecurityDescriptorGroup(PSECURITY_DESCRIPTOR pSecurityDescriptor, PSID pGroup,
BOOL bGroupDefaulted);
WINPR_API BOOL GetSecurityDescriptorOwner(PSECURITY_DESCRIPTOR pSecurityDescriptor,
PSID* pOwner, LPBOOL lpbOwnerDefaulted);
WINPR_API BOOL SetSecurityDescriptorOwner(PSECURITY_DESCRIPTOR pSecurityDescriptor, PSID pOwner,
BOOL bOwnerDefaulted);
WINPR_API DWORD GetSecurityDescriptorRMControl(PSECURITY_DESCRIPTOR SecurityDescriptor,
PUCHAR RMControl);
WINPR_API DWORD SetSecurityDescriptorRMControl(PSECURITY_DESCRIPTOR SecurityDescriptor,
PUCHAR RMControl);
WINPR_API BOOL GetSecurityDescriptorSacl(PSECURITY_DESCRIPTOR pSecurityDescriptor,
LPBOOL lpbSaclPresent, PACL* pSacl,
LPBOOL lpbSaclDefaulted);
WINPR_API BOOL SetSecurityDescriptorSacl(PSECURITY_DESCRIPTOR pSecurityDescriptor,
BOOL bSaclPresent, PACL pSacl, BOOL bSaclDefaulted);
#ifdef __cplusplus
}
#endif
#endif
#endif /* WINPR_SECURITY_H */

View File

@@ -0,0 +1,108 @@
/**
* WinPR: Windows Portable Runtime
* Shell Functions
*
* Copyright 2015 Dell Software <Mike.McDonald@software.dell.com>
* Copyright 2016 David PHAM-VAN <d.phamvan@inuvika.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_SHELL_H
#define WINPR_SHELL_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#ifdef _WIN32
#include <shlobj.h>
#include <userenv.h>
#else
/* Shell clipboard formats */
typedef struct
{
DWORD dwFlags;
CLSID clsid;
SIZEL sizel;
POINTL pointl;
DWORD dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
DWORD nFileSizeHigh;
DWORD nFileSizeLow;
WCHAR cFileName[260];
} FILEDESCRIPTORW;
/* Legacy definition, some types do not match the windows equivalent. */
typedef struct
{
DWORD dwFlags;
BYTE clsid[16];
BYTE sizel[8];
BYTE pointl[8];
DWORD dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
DWORD nFileSizeHigh;
DWORD nFileSizeLow;
WCHAR cFileName[260];
} FILEDESCRIPTOR;
/* FILEDESCRIPTOR.dwFlags */
typedef enum
{
FD_CLSID = 0x00000001,
FD_SIZEPOINT = 0x00000002,
FD_ATTRIBUTES = 0x00000004,
FD_CREATETIME = 0x00000008,
FD_ACCESSTIME = 0x00000010,
FD_WRITESTIME = 0x00000020,
FD_FILESIZE = 0x00000040,
FD_PROGRESSUI = 0x00004000,
FD_LINKUI = 0x00008000,
} FD_FLAGS;
#define FD_UNICODE 0x80000000
/* Deprecated, here for compatibility */
#define FD_SHOWPROGRESSUI FD_PROGRESSUI
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API BOOL GetUserProfileDirectoryA(HANDLE hToken, LPSTR lpProfileDir, LPDWORD lpcchSize);
WINPR_API BOOL GetUserProfileDirectoryW(HANDLE hToken, LPWSTR lpProfileDir, LPDWORD lpcchSize);
#ifdef __cplusplus
}
#endif
#ifdef UNICODE
#define GetUserProfileDirectory GetUserProfileDirectoryW
#else
#define GetUserProfileDirectory GetUserProfileDirectoryA
#endif
#endif
#endif /* WINPR_SHELL_H */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,49 @@
/**
* WinPR: Windows Portable Runtime
* OpenSSL Library Initialization
*
* Copyright 2014 Thincast Technologies GmbH
* Copyright 2014 Norbert Federa <norbert.federa@thincast.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_SSL_H
#define WINPR_SSL_H
#include <winpr/wtypes.h>
#include <winpr/winpr.h>
#define WINPR_SSL_INIT_DEFAULT 0x00
#define WINPR_SSL_INIT_ALREADY_INITIALIZED 0x01
#define WINPR_SSL_INIT_ENABLE_LOCKING 0x2
#define WINPR_SSL_INIT_ENABLE_FIPS 0x4
#define WINPR_SSL_CLEANUP_GLOBAL 0x01
#define WINPR_SSL_CLEANUP_THREAD 0x02
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API BOOL winpr_InitializeSSL(DWORD flags);
WINPR_API BOOL winpr_CleanupSSL(DWORD flags);
WINPR_API BOOL winpr_FIPSMode(void);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_SSL_H */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,147 @@
/**
* WinPR: Windows Portable Runtime
* Security Support Provider Interface
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_SSPICLI_H
#define WINPR_SSPICLI_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#ifndef _WIN32
#define LOGON32_LOGON_INTERACTIVE 2
#define LOGON32_LOGON_NETWORK 3
#define LOGON32_LOGON_BATCH 4
#define LOGON32_LOGON_SERVICE 5
#define LOGON32_LOGON_UNLOCK 7
#define LOGON32_LOGON_NETWORK_CLEARTEXT 8
#define LOGON32_LOGON_NEW_CREDENTIALS 9
#define LOGON32_PROVIDER_DEFAULT 0
#define LOGON32_PROVIDER_WINNT35 1
#define LOGON32_PROVIDER_WINNT40 2
#define LOGON32_PROVIDER_WINNT50 3
#define LOGON32_PROVIDER_VIRTUAL 4
typedef struct
{
size_t PagedPoolLimit;
size_t NonPagedPoolLimit;
size_t MinimumWorkingSetSize;
size_t MaximumWorkingSetSize;
size_t PagefileLimit;
LARGE_INTEGER TimeLimit;
} QUOTA_LIMITS, *PQUOTA_LIMITS;
typedef enum
{
/* An unknown name type */
NameUnknown = 0,
/* The fully qualified distinguished name (for example, CN=Jeff
Smith,OU=Users,DC=Engineering,DC=Microsoft,DC=Com) */
NameFullyQualifiedDN = 1,
/*
* A legacy account name (for example, Engineering\JSmith).
* The domain-only version includes trailing backslashes (\\)
*/
NameSamCompatible = 2,
/*
* A "friendly" display name (for example, Jeff Smith).
* The display name is not necessarily the defining relative distinguished name (RDN)
*/
NameDisplay = 3,
/* A GUID string that the IIDFromString function returns (for example,
{4fa050f0-f561-11cf-bdd9-00aa003a77b6}) */
NameUniqueId = 6,
/*
* The complete canonical name (for example, engineering.microsoft.com/software/someone).
* The domain-only version includes a trailing forward slash (/)
*/
NameCanonical = 7,
/* The user principal name (for example, someone@example.com) */
NameUserPrincipal = 8,
/*
* The same as NameCanonical except that the rightmost forward slash (/)
* is replaced with a new line character (\n), even in a domain-only case
* (for example, engineering.microsoft.com/software\nJSmith)
*/
NameCanonicalEx = 9,
/* The generalized service principal name (for example, www/www.microsoft.com@microsoft.com) */
NameServicePrincipal = 10,
/* The DNS domain name followed by a backward-slash and the SAM user name */
NameDnsDomain = 12
} EXTENDED_NAME_FORMAT,
*PEXTENDED_NAME_FORMAT;
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API BOOL LogonUserA(LPCSTR lpszUsername, LPCSTR lpszDomain, LPCSTR lpszPassword,
DWORD dwLogonType, DWORD dwLogonProvider, PHANDLE phToken);
WINPR_API BOOL LogonUserW(LPCWSTR lpszUsername, LPCWSTR lpszDomain, LPCWSTR lpszPassword,
DWORD dwLogonType, DWORD dwLogonProvider, PHANDLE phToken);
WINPR_API BOOL LogonUserExA(LPCSTR lpszUsername, LPCSTR lpszDomain, LPCSTR lpszPassword,
DWORD dwLogonType, DWORD dwLogonProvider, PHANDLE phToken,
PSID* ppLogonSid, PVOID* ppProfileBuffer, LPDWORD pdwProfileLength,
PQUOTA_LIMITS pQuotaLimits);
WINPR_API BOOL LogonUserExW(LPCWSTR lpszUsername, LPCWSTR lpszDomain, LPCWSTR lpszPassword,
DWORD dwLogonType, DWORD dwLogonProvider, PHANDLE phToken,
PSID* ppLogonSid, PVOID* ppProfileBuffer, LPDWORD pdwProfileLength,
PQUOTA_LIMITS pQuotaLimits);
WINPR_API BOOL GetUserNameExA(EXTENDED_NAME_FORMAT NameFormat, LPSTR lpNameBuffer,
PULONG nSize);
WINPR_API BOOL GetUserNameExW(EXTENDED_NAME_FORMAT NameFormat, LPWSTR lpNameBuffer,
PULONG nSize);
#ifdef __cplusplus
}
#endif
#ifdef UNICODE
#define LogonUser LogonUserW
#define LogonUserEx LogonUserExW
#define GetUserNameEx GetUserNameExW
#else
#define LogonUser LogonUserA
#define LogonUserEx LogonUserExA
#define GetUserNameEx GetUserNameExA
#endif
#endif
#endif /* WINPR_SSPICLI_H */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,460 @@
/**
* WinPR: Windows Portable Runtime
* String Manipulation (CRT)
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2016 David PHAM-VAN <d.phamvan@inuvika.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_CRT_STRING_H
#define WINPR_CRT_STRING_H
#include <wchar.h>
#include <stdio.h>
#include <string.h>
#include <winpr/config.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
WINPR_PRAGMA_DIAG_PUSH
WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER
// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API char* winpr_str_url_encode(const char* str, size_t len);
WINPR_API char* winpr_str_url_decode(const char* str, size_t len);
WINPR_API BOOL winpr_str_append(const char* what, char* buffer, size_t size,
const char* separator);
WINPR_API int winpr_asprintf(char** s, size_t* slen, const char* templ, ...);
WINPR_API int winpr_vasprintf(char** s, size_t* slen, const char* templ, va_list ap);
#ifndef _WIN32
#define CSTR_LESS_THAN 1
#define CSTR_EQUAL 2
#define CSTR_GREATER_THAN 3
#define CP_ACP 0
#define CP_OEMCP 1
#define CP_MACCP 2
#define CP_THREAD_ACP 3
#define CP_SYMBOL 42
#define CP_UTF7 65000
#define CP_UTF8 65001
#define MB_PRECOMPOSED 0x00000001
#define MB_COMPOSITE 0x00000002
#define MB_USEGLYPHCHARS 0x00000004
#define MB_ERR_INVALID_CHARS 0x00000008
WINPR_API char* _strdup(const char* strSource);
WINPR_API WCHAR* _wcsdup(const WCHAR* strSource);
WINPR_API int _stricmp(const char* string1, const char* string2);
WINPR_API int _strnicmp(const char* string1, const char* string2, size_t count);
WINPR_API int _wcscmp(const WCHAR* string1, const WCHAR* string2);
WINPR_API int _wcsncmp(const WCHAR* string1, const WCHAR* string2, size_t count);
WINPR_API size_t _wcslen(const WCHAR* str);
WINPR_API size_t _wcsnlen(const WCHAR* str, size_t maxNumberOfElements);
WINPR_API WCHAR* _wcsstr(const WCHAR* str, const WCHAR* strSearch);
WINPR_API WCHAR* _wcschr(const WCHAR* str, WCHAR c);
WINPR_API WCHAR* _wcsrchr(const WCHAR* str, WCHAR c);
WINPR_API char* strtok_s(char* strToken, const char* strDelimit, char** context);
WINPR_API WCHAR* wcstok_s(WCHAR* strToken, const WCHAR* strDelimit, WCHAR** context);
WINPR_API WCHAR* _wcsncat(WCHAR* dst, const WCHAR* src, size_t sz);
#else
#define _wcscmp wcscmp
#define _wcsncmp wcsncmp
#define _wcslen wcslen
#define _wcsnlen wcsnlen
#define _wcsstr wcsstr
#define _wcschr wcschr
#define _wcsrchr wcsrchr
#define _wcsncat wcsncat
#endif /* _WIN32 */
#if !defined(_WIN32) || defined(_UWP)
WINPR_API LPSTR CharUpperA(LPSTR lpsz);
WINPR_API LPWSTR CharUpperW(LPWSTR lpsz);
#ifdef UNICODE
#define CharUpper CharUpperW
#else
#define CharUpper CharUpperA
#endif
WINPR_API DWORD CharUpperBuffA(LPSTR lpsz, DWORD cchLength);
WINPR_API DWORD CharUpperBuffW(LPWSTR lpsz, DWORD cchLength);
#ifdef UNICODE
#define CharUpperBuff CharUpperBuffW
#else
#define CharUpperBuff CharUpperBuffA
#endif
WINPR_API LPSTR CharLowerA(LPSTR lpsz);
WINPR_API LPWSTR CharLowerW(LPWSTR lpsz);
#ifdef UNICODE
#define CharLower CharLowerW
#else
#define CharLower CharLowerA
#endif
WINPR_API DWORD CharLowerBuffA(LPSTR lpsz, DWORD cchLength);
WINPR_API DWORD CharLowerBuffW(LPWSTR lpsz, DWORD cchLength);
#ifdef UNICODE
#define CharLowerBuff CharLowerBuffW
#else
#define CharLowerBuff CharLowerBuffA
#endif
WINPR_API BOOL IsCharAlphaA(CHAR ch);
WINPR_API BOOL IsCharAlphaW(WCHAR ch);
#ifdef UNICODE
#define IsCharAlpha IsCharAlphaW
#else
#define IsCharAlpha IsCharAlphaA
#endif
WINPR_API BOOL IsCharAlphaNumericA(CHAR ch);
WINPR_API BOOL IsCharAlphaNumericW(WCHAR ch);
#ifdef UNICODE
#define IsCharAlphaNumeric IsCharAlphaNumericW
#else
#define IsCharAlphaNumeric IsCharAlphaNumericA
#endif
WINPR_API BOOL IsCharUpperA(CHAR ch);
WINPR_API BOOL IsCharUpperW(WCHAR ch);
#ifdef UNICODE
#define IsCharUpper IsCharUpperW
#else
#define IsCharUpper IsCharUpperA
#endif
WINPR_API BOOL IsCharLowerA(CHAR ch);
WINPR_API BOOL IsCharLowerW(WCHAR ch);
#ifdef UNICODE
#define IsCharLower IsCharLowerW
#else
#define IsCharLower IsCharLowerA
#endif
#endif
#ifndef _WIN32
#define sprintf_s snprintf
#define _snprintf snprintf
#define _scprintf(...) snprintf(nullptr, 0, __VA_ARGS__)
#define _scprintf(...) snprintf(nullptr, 0, __VA_ARGS__)
/* Unicode Conversion */
#if defined(WITH_WINPR_DEPRECATED)
WINPR_DEPRECATED_VAR("Use ConvertUtf8ToWChar instead",
WINPR_API int MultiByteToWideChar(UINT CodePage, DWORD dwFlags,
LPCSTR lpMultiByteStr, int cbMultiByte,
LPWSTR lpWideCharStr, int cchWideChar));
WINPR_DEPRECATED_VAR("Use ConvertWCharToUtf8 instead",
WINPR_API int WideCharToMultiByte(UINT CodePage, DWORD dwFlags,
LPCWSTR lpWideCharStr, int cchWideChar,
LPSTR lpMultiByteStr, int cbMultiByte,
LPCSTR lpDefaultChar,
LPBOOL lpUsedDefaultChar));
#endif
#endif
/* Extended API */
/** \brief Converts form UTF-16 to UTF-8
*
* The function does string conversions of any '\0' terminated input string
*
* Supplying len = 0 will return the required size of the buffer in characters.
*
* \warning Supplying a buffer length smaller than required will result in
* platform dependent (=undefined) behaviour!
*
* \param wstr A '\0' terminated WCHAR string, may be nullptr
* \param str A pointer to the result string
* \param len The length in characters of the result buffer
*
* \return the size of the converted string in char (strlen), or -1 for failure
*/
WINPR_API SSIZE_T ConvertWCharToUtf8(const WCHAR* wstr, char* str, size_t len);
/** \brief Converts form UTF-16 to UTF-8
*
* The function does string conversions of any input string of wlen (or less)
* characters until it reaches the first '\0'.
*
* Supplying len = 0 will return the required size of the buffer in characters.
*
* \warning Supplying a buffer length smaller than required will result in
* platform dependent (=undefined) behaviour!
*
* \param wstr A WCHAR string of \b wlen length
* \param wlen The (buffer) length in characters of \b wstr
* \param str A pointer to the result string
* \param len The length in characters of the result buffer
*
* \return the size of the converted string in char (strlen), or -1 for failure
*/
WINPR_API SSIZE_T ConvertWCharNToUtf8(const WCHAR* wstr, size_t wlen, char* str, size_t len);
/** \brief Converts multistrings form UTF-16 to UTF-8
*
* The function does string conversions of any input string of wlen characters.
* Any character in the buffer (including any '\0') is converted.
*
* Supplying len = 0 will return the required size of the buffer in characters.
*
* \warning Supplying a buffer length smaller than required will result in
* platform dependent (=undefined) behaviour!
*
* \param wstr A WCHAR string of \b wlen length
* \param wlen The (buffer) length in characters of \b wstr
* \param str A pointer to the result string
* \param len The length in characters of the result buffer
*
* \return the size of the converted string in CHAR characters (including any '\0'), or -1 for
* failure
*/
WINPR_API SSIZE_T ConvertMszWCharNToUtf8(const WCHAR* wstr, size_t wlen, char* str, size_t len);
/** \brief Converts form UTF-8 to UTF-16
*
* The function does string conversions of any '\0' terminated input string
*
* Supplying wlen = 0 will return the required size of the buffer in characters.
*
* \warning Supplying a buffer length smaller than required will result in
* platform dependent (=undefined) behaviour!
*
* \param str A '\0' terminated CHAR string, may be nullptr
* \param wstr A pointer to the result WCHAR string
* \param wlen The length in WCHAR characters of the result buffer
*
* \return the size of the converted string in WCHAR characters (wcslen), or -1 for failure
*/
WINPR_API SSIZE_T ConvertUtf8ToWChar(const char* str, WCHAR* wstr, size_t wlen);
/** \brief Converts form UTF-8 to UTF-16
*
* The function does string conversions of any input string of len (or less)
* characters until it reaches the first '\0'.
*
* Supplying wlen = 0 will return the required size of the buffer in characters.
*
* \warning Supplying a buffer length smaller than required will result in
* platform dependent (=undefined) behaviour!
*
* \param str A CHAR string of \b len length
* \param len The (buffer) length in characters of \b str
* \param wstr A pointer to the result WCHAR string
* \param wlen The length in WCHAR characters of the result buffer
*
* \return the size of the converted string in WCHAR characters (wcslen), or -1 for failure
*/
WINPR_API SSIZE_T ConvertUtf8NToWChar(const char* str, size_t len, WCHAR* wstr, size_t wlen);
/** \brief Converts multistrings form UTF-8 to UTF-16
*
* The function does string conversions of any input string of len characters.
* Any character in the buffer (including any '\0') is converted.
*
* Supplying wlen = 0 will return the required size of the buffer in characters.
*
* \warning Supplying a buffer length smaller than required will result in
* platform dependent (=undefined) behaviour!
*
* \param str A CHAR string of \b len length
* \param len The (buffer) length in characters of \b str
* \param wstr A pointer to the result WCHAR string
* \param wlen The length in WCHAR characters of the result buffer
*
* \return the size of the converted string in WCHAR characters (including any '\0'), or -1 for
* failure
*/
WINPR_API SSIZE_T ConvertMszUtf8NToWChar(const char* str, size_t len, WCHAR* wstr, size_t wlen);
/** \brief Converts form UTF-16 to UTF-8, returns an allocated string
*
* The function does string conversions of any '\0' terminated input string
*
* \param wstr A '\0' terminated WCHAR string, may be nullptr
* \param pUtfCharLength Ignored if nullptr, otherwise receives the length of the result string
* in characters (strlen)
*
* \return An allocated zero terminated UTF-8 string or nullptr in case of failure.
*/
WINPR_API char* ConvertWCharToUtf8Alloc(const WCHAR* wstr, size_t* pUtfCharLength);
/** \brief Converts form UTF-16 to UTF-8, returns an allocated string
*
* The function does string conversions of any input string of wlen (or less)
* characters until it reaches the first '\0'.
*
* \param wstr A WCHAR string of \b wlen length
* \param wlen The (buffer) length in characters of \b wstr
* \param pUtfCharLength Ignored if nullptr, otherwise receives the length of the result string
* in characters (strlen)
*
* \return An allocated zero terminated UTF-8 string or nullptr in case of failure.
*/
WINPR_API char* ConvertWCharNToUtf8Alloc(const WCHAR* wstr, size_t wlen,
size_t* pUtfCharLength);
/** \brief Converts multistring form UTF-16 to UTF-8, returns an allocated string
*
* The function does string conversions of any input string of len characters.
* Any character in the buffer (including any '\0') is converted.
*
* \param wstr A WCHAR string of \b len character length
* \param wlen The (buffer) length in characters of \b str
* \param pUtfCharLength Ignored if nullptr, otherwise receives the length of the result string
* in characters (including any '\0' character)
*
* \return An allocated double zero terminated UTF-8 string or nullptr in case of failure.
*/
WINPR_API char* ConvertMszWCharNToUtf8Alloc(const WCHAR* wstr, size_t wlen,
size_t* pUtfCharLength);
/** \brief Converts form UTF-8 to UTF-16, returns an allocated string
*
* The function does string conversions of any '\0' terminated input string
*
* \param str A '\0' terminated CHAR string, may be nullptr
* \param pSize Ignored if nullptr, otherwise receives the length of the result string in
* characters (wcslen)
*
* \return An allocated zero terminated UTF-16 string or nullptr in case of failure.
*/
WINPR_API WCHAR* ConvertUtf8ToWCharAlloc(const char* str, size_t* pSize);
/** \brief Converts form UTF-8 to UTF-16, returns an allocated string
*
* The function does string conversions of any input string of len (or less)
* characters until it reaches the first '\0'.
*
* \param str A CHAR string of \b len length
* \param len The (buffer) length in characters of \b str
* \param pSize Ignored if nullptr, otherwise receives the length of the result string in
* characters (wcslen)
*
* \return An allocated zero terminated UTF-16 string or nullptr in case of failure.
*/
WINPR_API WCHAR* ConvertUtf8NToWCharAlloc(const char* str, size_t len, size_t* pSize);
/** \brief Converts multistring form UTF-8 to UTF-16, returns an allocated string
*
* The function does string conversions of any input string of len characters.
* Any character in the buffer (including any '\0') is converted.
*
* \param str A CHAR string of \b len byte length
* \param len The (buffer) length in characters of \b str
* \param pSize Ignored if nullptr, otherwise receives the length of the result string in
* characters (including any '\0' character)
*
* \return An allocated double zero terminated UTF-16 string or nullptr in case of failure.
*/
WINPR_API WCHAR* ConvertMszUtf8NToWCharAlloc(const char* str, size_t len, size_t* pSize);
/** \brief Helper function to initialize const WCHAR pointer from a Utf8 string
*
* \param str The Utf8 string to use for initialization
* \param buffer The WCHAR buffer used to store the converted data
* \param len The size of the buffer in number of WCHAR
*
* \return The WCHAR string (a pointer to buffer)
*/
WINPR_API const WCHAR* InitializeConstWCharFromUtf8(const char* str, WCHAR* buffer, size_t len);
#if defined(WITH_WINPR_DEPRECATED)
WINPR_DEPRECATED_VAR("Use ConvertUtf8ToWChar functions instead",
WINPR_API int ConvertToUnicode(UINT CodePage, DWORD dwFlags,
LPCSTR lpMultiByteStr, int cbMultiByte,
LPWSTR* lpWideCharStr, int cchWideChar));
WINPR_DEPRECATED_VAR("Use ConvertWCharToUtf8 functions instead",
WINPR_API int ConvertFromUnicode(UINT CodePage, DWORD dwFlags,
LPCWSTR lpWideCharStr, int cchWideChar,
LPSTR* lpMultiByteStr, int cbMultiByte,
LPCSTR lpDefaultChar,
LPBOOL lpUsedDefaultChar));
#endif
WINPR_API const WCHAR* ByteSwapUnicode(WCHAR* wstr, size_t length);
WINPR_API size_t ConvertLineEndingToLF(char* str, size_t size);
WINPR_API char* ConvertLineEndingToCRLF(const char* str, size_t* size);
WINPR_API char* StrSep(char** stringp, const char* delim);
WINPR_API INT64 GetLine(char** lineptr, size_t* size, FILE* stream);
#if !defined(WINPR_HAVE_STRNDUP)
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API char* strndup(const char* s, size_t n);
#endif
/** @brief WCHAR version of \b strndup
* creates a copy of a \b WCHAR string of \b n characters length. The copy will always be \b \0
* terminated
*
* @param s The \b WCHAR string to copy
* @param n The number of WCHAR to copy
*
* @return An allocated copy of \b s, always \b \0 terminated
* @since version 3.10.0
*/
WINPR_ATTR_MALLOC(free, 1)
WINPR_ATTR_NODISCARD
WINPR_API WCHAR* wcsndup(const WCHAR* s, size_t n);
#ifdef __cplusplus
}
#endif
// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
WINPR_PRAGMA_DIAG_POP
#endif /* WINPR_CRT_STRING_H */

View File

@@ -0,0 +1,41 @@
/**
* String list Manipulation (UTILS)
*
* Copyright 2018 Pascal Bourguignon <pjb@informatimago.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_UTILS_STRLST_H
#define WINPR_UTILS_STRLST_H
#include <stdio.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API void string_list_free(char** string_list);
WINPR_API int string_list_length(const char* const* string_list);
WINPR_API char** string_list_copy(const char* const* string_list);
WINPR_API void string_list_print(FILE* out, const char* const* string_list);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_UTILS_STRLST_H */

View File

@@ -0,0 +1,489 @@
/**
* WinPR: Windows Portable Runtime
* Synchronization Functions
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2014 Thincast Technologies GmbH
* Copyright 2014 Norbert Federa <norbert.federa@thincast.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_SYNCH_H
#define WINPR_SYNCH_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/platform.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/error.h>
#include <winpr/handle.h>
#include <winpr/nt.h>
#ifdef __cplusplus
extern "C"
{
#endif
#ifndef _WIN32
/* Mutex */
#define CREATE_MUTEX_INITIAL_OWNER 0x00000001
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateMutexA(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner,
LPCSTR lpName);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateMutexW(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner,
LPCWSTR lpName);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateMutexExA(LPSECURITY_ATTRIBUTES lpMutexAttributes, LPCSTR lpName,
DWORD dwFlags, DWORD dwDesiredAccess);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateMutexExW(LPSECURITY_ATTRIBUTES lpMutexAttributes, LPCWSTR lpName,
DWORD dwFlags, DWORD dwDesiredAccess);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE OpenMutexA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE OpenMutexW(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCWSTR lpName);
WINPR_API BOOL ReleaseMutex(HANDLE hMutex);
#ifdef UNICODE
#define CreateMutex CreateMutexW
#define CreateMutexEx CreateMutexExW
#define OpenMutex OpenMutexW
#else
#define CreateMutex CreateMutexA
#define CreateMutexEx CreateMutexExA
#define OpenMutex OpenMutexA
#endif
/* Semaphore */
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateSemaphoreA(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes,
LONG lInitialCount, LONG lMaximumCount, LPCSTR lpName);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateSemaphoreW(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes,
LONG lInitialCount, LONG lMaximumCount, LPCWSTR lpName);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE OpenSemaphoreA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE OpenSemaphoreW(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCWSTR lpName);
#ifdef UNICODE
#define CreateSemaphore CreateSemaphoreW
#define OpenSemaphore OpenSemaphoreW
#else
#define CreateSemaphore CreateSemaphoreA
#define OpenSemaphore OpenSemaphoreA
#endif
WINPR_API BOOL ReleaseSemaphore(HANDLE hSemaphore, LONG lReleaseCount, LPLONG lpPreviousCount);
/* Event */
#define CREATE_EVENT_MANUAL_RESET 0x00000001
#define CREATE_EVENT_INITIAL_SET 0x00000002
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateEventA(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset,
BOOL bInitialState, LPCSTR lpName);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset,
BOOL bInitialState, LPCWSTR lpName);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateEventExA(LPSECURITY_ATTRIBUTES lpEventAttributes, LPCSTR lpName,
DWORD dwFlags, DWORD dwDesiredAccess);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateEventExW(LPSECURITY_ATTRIBUTES lpEventAttributes, LPCWSTR lpName,
DWORD dwFlags, DWORD dwDesiredAccess);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE OpenEventA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE OpenEventW(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCWSTR lpName);
WINPR_API BOOL SetEvent(HANDLE hEvent);
WINPR_API BOOL ResetEvent(HANDLE hEvent);
#if defined(WITH_DEBUG_EVENTS)
#define DumpEventHandles() DumpEventHandles_(__func__, __FILE__, __LINE__)
WINPR_API void DumpEventHandles_(const char* fkt, const char* file, size_t line);
#endif
#ifdef UNICODE
#define CreateEvent CreateEventW
#define CreateEventEx CreateEventExW
#define OpenEvent OpenEventW
#else
#define CreateEvent CreateEventA
#define CreateEventEx CreateEventExA
#define OpenEvent OpenEventA
#endif
/* Condition Variable */
typedef PVOID RTL_CONDITION_VARIABLE;
typedef RTL_CONDITION_VARIABLE CONDITION_VARIABLE, *PCONDITION_VARIABLE;
/* Critical Section */
typedef struct
{
PVOID DebugInfo;
LONG LockCount;
LONG RecursionCount;
HANDLE OwningThread;
HANDLE LockSemaphore;
ULONG_PTR SpinCount;
} RTL_CRITICAL_SECTION, *PRTL_CRITICAL_SECTION;
typedef RTL_CRITICAL_SECTION CRITICAL_SECTION;
typedef PRTL_CRITICAL_SECTION PCRITICAL_SECTION;
typedef PRTL_CRITICAL_SECTION LPCRITICAL_SECTION;
WINPR_API VOID InitializeCriticalSection(LPCRITICAL_SECTION lpCriticalSection);
WINPR_API BOOL InitializeCriticalSectionEx(LPCRITICAL_SECTION lpCriticalSection,
DWORD dwSpinCount, DWORD Flags);
WINPR_API BOOL InitializeCriticalSectionAndSpinCount(LPCRITICAL_SECTION lpCriticalSection,
DWORD dwSpinCount);
WINPR_API DWORD SetCriticalSectionSpinCount(LPCRITICAL_SECTION lpCriticalSection,
DWORD dwSpinCount);
WINPR_API VOID EnterCriticalSection(LPCRITICAL_SECTION lpCriticalSection);
WINPR_API BOOL TryEnterCriticalSection(LPCRITICAL_SECTION lpCriticalSection);
WINPR_API VOID LeaveCriticalSection(LPCRITICAL_SECTION lpCriticalSection);
WINPR_API VOID DeleteCriticalSection(LPCRITICAL_SECTION lpCriticalSection);
/* Sleep */
WINPR_API VOID Sleep(DWORD dwMilliseconds);
WINPR_API DWORD SleepEx(DWORD dwMilliseconds, BOOL bAlertable);
/* Address */
WINPR_API VOID WakeByAddressAll(PVOID Address);
WINPR_API VOID WakeByAddressSingle(PVOID Address);
WINPR_API BOOL WaitOnAddress(VOID volatile* Address, PVOID CompareAddress, size_t AddressSize,
DWORD dwMilliseconds);
/* Wait */
#define INFINITE 0xFFFFFFFFUL
#define WAIT_OBJECT_0 0x00000000UL
#define WAIT_ABANDONED 0x00000080UL
#define WAIT_IO_COMPLETION 0x000000C0UL
#ifndef WAIT_TIMEOUT
#define WAIT_TIMEOUT 0x00000102UL
#endif
#define WAIT_FAILED 0xFFFFFFFFUL
#define MAXIMUM_WAIT_OBJECTS 64
WINPR_API DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds);
WINPR_API DWORD WaitForSingleObjectEx(HANDLE hHandle, DWORD dwMilliseconds, BOOL bAlertable);
WINPR_API DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE* lpHandles, BOOL bWaitAll,
DWORD dwMilliseconds);
WINPR_API DWORD WaitForMultipleObjectsEx(DWORD nCount, const HANDLE* lpHandles, BOOL bWaitAll,
DWORD dwMilliseconds, BOOL bAlertable);
WINPR_API DWORD SignalObjectAndWait(HANDLE hObjectToSignal, HANDLE hObjectToWaitOn,
DWORD dwMilliseconds, BOOL bAlertable);
/* Waitable Timer */
#define CREATE_WAITABLE_TIMER_MANUAL_RESET 0x00000001
typedef struct
{
ULONG Version;
DWORD Flags;
union
{
struct
{
HMODULE LocalizedReasonModule;
ULONG LocalizedReasonId;
ULONG ReasonStringCount;
LPWSTR* ReasonStrings;
} Detailed;
LPWSTR SimpleReasonString;
} Reason;
} REASON_CONTEXT, *PREASON_CONTEXT;
typedef VOID (*PTIMERAPCROUTINE)(LPVOID lpArgToCompletionRoutine, DWORD dwTimerLowValue,
DWORD dwTimerHighValue);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateWaitableTimerA(LPSECURITY_ATTRIBUTES lpTimerAttributes,
BOOL bManualReset, LPCSTR lpTimerName);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateWaitableTimerW(LPSECURITY_ATTRIBUTES lpTimerAttributes,
BOOL bManualReset, LPCWSTR lpTimerName);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateWaitableTimerExA(LPSECURITY_ATTRIBUTES lpTimerAttributes,
LPCSTR lpTimerName, DWORD dwFlags,
DWORD dwDesiredAccess);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateWaitableTimerExW(LPSECURITY_ATTRIBUTES lpTimerAttributes,
LPCWSTR lpTimerName, DWORD dwFlags,
DWORD dwDesiredAccess);
WINPR_API BOOL SetWaitableTimer(HANDLE hTimer, const LARGE_INTEGER* lpDueTime, LONG lPeriod,
PTIMERAPCROUTINE pfnCompletionRoutine,
LPVOID lpArgToCompletionRoutine, BOOL fResume);
WINPR_API BOOL SetWaitableTimerEx(HANDLE hTimer, const LARGE_INTEGER* lpDueTime, LONG lPeriod,
PTIMERAPCROUTINE pfnCompletionRoutine,
LPVOID lpArgToCompletionRoutine, PREASON_CONTEXT WakeContext,
ULONG TolerableDelay);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE OpenWaitableTimerA(DWORD dwDesiredAccess, BOOL bInheritHandle,
LPCSTR lpTimerName);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE OpenWaitableTimerW(DWORD dwDesiredAccess, BOOL bInheritHandle,
LPCWSTR lpTimerName);
WINPR_API BOOL CancelWaitableTimer(HANDLE hTimer);
#ifdef UNICODE
#define CreateWaitableTimer CreateWaitableTimerW
#define CreateWaitableTimerEx CreateWaitableTimerExW
#define OpenWaitableTimer OpenWaitableTimerW
#else
#define CreateWaitableTimer CreateWaitableTimerA
#define CreateWaitableTimerEx CreateWaitableTimerExA
#define OpenWaitableTimer OpenWaitableTimerA
#endif
WINPR_API int GetTimerFileDescriptor(HANDLE hTimer);
/**
* Timer-Queue Timer
*/
#define WT_EXECUTEDEFAULT 0x00000000
#define WT_EXECUTEINIOTHREAD 0x00000001
#define WT_EXECUTEINUITHREAD 0x00000002
#define WT_EXECUTEINWAITTHREAD 0x00000004
#define WT_EXECUTEONLYONCE 0x00000008
#define WT_EXECUTELONGFUNCTION 0x00000010
#define WT_EXECUTEINTIMERTHREAD 0x00000020
#define WT_EXECUTEINPERSISTENTIOTHREAD 0x00000040
#define WT_EXECUTEINPERSISTENTTHREAD 0x00000080
#define WT_TRANSFER_IMPERSONATION 0x00000100
typedef VOID (*WAITORTIMERCALLBACK)(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateTimerQueue(void);
WINPR_API BOOL DeleteTimerQueue(HANDLE TimerQueue);
WINPR_API BOOL DeleteTimerQueueEx(HANDLE TimerQueue, HANDLE CompletionEvent);
WINPR_API BOOL CreateTimerQueueTimer(HANDLE* phNewTimer, HANDLE TimerQueue,
WAITORTIMERCALLBACK Callback, void* Parameter,
DWORD DueTime, DWORD Period, ULONG Flags);
WINPR_API BOOL ChangeTimerQueueTimer(HANDLE TimerQueue, HANDLE Timer, ULONG DueTime,
ULONG Period);
WINPR_API BOOL DeleteTimerQueueTimer(HANDLE TimerQueue, HANDLE Timer, HANDLE CompletionEvent);
#endif
#if (defined(_WIN32) && (_WIN32_WINNT < 0x0600))
#define InitializeCriticalSectionEx(lpCriticalSection, dwSpinCount, Flags) \
InitializeCriticalSectionAndSpinCount(lpCriticalSection, dwSpinCount)
#endif
WINPR_PRAGMA_DIAG_PUSH
WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO
#ifndef _RTL_RUN_ONCE_DEF
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _RTL_RUN_ONCE_DEF
WINPR_PRAGMA_DIAG_POP
#define RTL_RUN_ONCE_INIT \
{ \
0 \
}
#define RTL_RUN_ONCE_CHECK_ONLY 0x00000001
#define RTL_RUN_ONCE_ASYNC 0x00000002
#define RTL_RUN_ONCE_INIT_FAILED 0x00000004
#define RTL_RUN_ONCE_CTX_RESERVED_BITS 2
typedef struct
{
PVOID Ptr;
} RTL_RUN_ONCE, *PRTL_RUN_ONCE;
typedef ULONG CALLBACK RTL_RUN_ONCE_INIT_FN(PRTL_RUN_ONCE RunOnce, PVOID Parameter,
PVOID* Context);
typedef RTL_RUN_ONCE_INIT_FN* PRTL_RUN_ONCE_INIT_FN;
#endif
#if (!defined(_WIN32)) || (defined(_WIN32) && (_WIN32_WINNT < 0x0600))
/* One-Time Initialization */
#define INIT_ONCE_STATIC_INIT RTL_RUN_ONCE_INIT
typedef RTL_RUN_ONCE INIT_ONCE;
typedef PRTL_RUN_ONCE PINIT_ONCE;
typedef PRTL_RUN_ONCE LPINIT_ONCE;
typedef BOOL(CALLBACK* PINIT_ONCE_FN)(PINIT_ONCE InitOnce, PVOID Parameter, PVOID* Context);
WINPR_API BOOL winpr_InitOnceBeginInitialize(LPINIT_ONCE lpInitOnce, DWORD dwFlags,
PBOOL fPending, LPVOID* lpContext);
WINPR_API BOOL winpr_InitOnceComplete(LPINIT_ONCE lpInitOnce, DWORD dwFlags, LPVOID lpContext);
WINPR_API BOOL winpr_InitOnceExecuteOnce(PINIT_ONCE InitOnce, PINIT_ONCE_FN InitFn,
PVOID Parameter, LPVOID* Context);
WINPR_API VOID winpr_InitOnceInitialize(PINIT_ONCE InitOnce);
#define InitOnceBeginInitialize winpr_InitOnceBeginInitialize
#define InitOnceComplete winpr_InitOnceComplete
#define InitOnceExecuteOnce winpr_InitOnceExecuteOnce
#define InitOnceInitialize winpr_InitOnceInitialize
#endif
/* Synchronization Barrier */
#if (!defined(_WIN32)) || (defined(_WIN32) && (_WIN32_WINNT < 0x0602) && !defined(_SYNCHAPI_H_))
#define WINPR_SYNCHRONIZATION_BARRIER 1
#endif
#ifdef WINPR_SYNCHRONIZATION_BARRIER
typedef struct
{
DWORD Reserved1;
DWORD Reserved2;
ULONG_PTR Reserved3[2];
DWORD Reserved4;
DWORD Reserved5;
} RTL_BARRIER, *PRTL_BARRIER;
typedef RTL_BARRIER SYNCHRONIZATION_BARRIER;
typedef PRTL_BARRIER PSYNCHRONIZATION_BARRIER;
typedef PRTL_BARRIER LPSYNCHRONIZATION_BARRIER;
#define SYNCHRONIZATION_BARRIER_FLAGS_SPIN_ONLY 0x01
#define SYNCHRONIZATION_BARRIER_FLAGS_BLOCK_ONLY 0x02
#define SYNCHRONIZATION_BARRIER_FLAGS_NO_DELETE 0x04
WINPR_API BOOL WINAPI winpr_InitializeSynchronizationBarrier(
LPSYNCHRONIZATION_BARRIER lpBarrier, LONG lTotalThreads, LONG lSpinCount);
WINPR_API BOOL WINAPI winpr_EnterSynchronizationBarrier(LPSYNCHRONIZATION_BARRIER lpBarrier,
DWORD dwFlags);
WINPR_API BOOL WINAPI winpr_DeleteSynchronizationBarrier(LPSYNCHRONIZATION_BARRIER lpBarrier);
#define InitializeSynchronizationBarrier winpr_InitializeSynchronizationBarrier
#define EnterSynchronizationBarrier winpr_EnterSynchronizationBarrier
#define DeleteSynchronizationBarrier winpr_DeleteSynchronizationBarrier
#endif
/* Extended API */
WINPR_API VOID USleep(DWORD dwMicroseconds);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateFileDescriptorEventW(LPSECURITY_ATTRIBUTES lpEventAttributes,
BOOL bManualReset, BOOL bInitialState,
int FileDescriptor, ULONG mode);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateFileDescriptorEventA(LPSECURITY_ATTRIBUTES lpEventAttributes,
BOOL bManualReset, BOOL bInitialState,
int FileDescriptor, ULONG mode);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateWaitObjectEvent(LPSECURITY_ATTRIBUTES lpEventAttributes,
BOOL bManualReset, BOOL bInitialState, void* pObject);
#ifdef UNICODE
#define CreateFileDescriptorEvent CreateFileDescriptorEventW
#else
#define CreateFileDescriptorEvent CreateFileDescriptorEventA
#endif
WINPR_API int GetEventFileDescriptor(HANDLE hEvent);
WINPR_API int SetEventFileDescriptor(HANDLE hEvent, int FileDescriptor, ULONG mode);
WINPR_API void* GetEventWaitObject(HANDLE hEvent);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_SYNCH_H */

View File

@@ -0,0 +1,392 @@
/**
* WinPR: Windows Portable Runtime
* System Information
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_SYSINFO_H
#define WINPR_SYSINFO_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#ifdef __cplusplus
extern "C"
{
#endif
#ifdef _WIN32
#include <winnt.h>
#else
#define PROCESSOR_ARCHITECTURE_INTEL 0
#define PROCESSOR_ARCHITECTURE_MIPS 1
#define PROCESSOR_ARCHITECTURE_ALPHA 2
#define PROCESSOR_ARCHITECTURE_PPC 3
#define PROCESSOR_ARCHITECTURE_SHX 4
#define PROCESSOR_ARCHITECTURE_ARM 5
#define PROCESSOR_ARCHITECTURE_IA64 6
#define PROCESSOR_ARCHITECTURE_ALPHA64 7
#define PROCESSOR_ARCHITECTURE_MSIL 8
#define PROCESSOR_ARCHITECTURE_AMD64 9
#define PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 10
#define PROCESSOR_ARCHITECTURE_NEUTRAL 11
#define PROCESSOR_ARCHITECTURE_ARM64 12
#define PROCESSOR_ARCHITECTURE_MIPS64 13
#define PROCESSOR_ARCHITECTURE_E2K 14
#define PROCESSOR_ARCHITECTURE_UNKNOWN 0xFFFF
#define PROCESSOR_INTEL_386 386
#define PROCESSOR_INTEL_486 486
#define PROCESSOR_INTEL_PENTIUM 586
#define PROCESSOR_INTEL_IA64 2200
#define PROCESSOR_AMD_X8664 8664
#define PROCESSOR_MIPS_R4000 4000
#define PROCESSOR_ALPHA_21064 21064
#define PROCESSOR_PPC_601 601
#define PROCESSOR_PPC_603 603
#define PROCESSOR_PPC_604 604
#define PROCESSOR_PPC_620 620
#define PROCESSOR_HITACHI_SH3 10003
#define PROCESSOR_HITACHI_SH3E 10004
#define PROCESSOR_HITACHI_SH4 10005
#define PROCESSOR_MOTOROLA_821 821
#define PROCESSOR_SHx_SH3 103
#define PROCESSOR_SHx_SH4 104
#define PROCESSOR_STRONGARM 2577
#define PROCESSOR_ARM720 1824
#define PROCESSOR_ARM820 2080
#define PROCESSOR_ARM920 2336
#define PROCESSOR_ARM_7TDMI 70001
#define PROCESSOR_OPTIL 0x494F
typedef struct
{
union
{
DWORD dwOemId;
struct
{
WORD wProcessorArchitecture;
WORD wReserved;
} DUMMYSTRUCTNAME;
} DUMMYUNIONNAME;
DWORD dwPageSize;
LPVOID lpMinimumApplicationAddress;
LPVOID lpMaximumApplicationAddress;
DWORD_PTR dwActiveProcessorMask;
DWORD dwNumberOfProcessors;
DWORD dwProcessorType;
DWORD dwAllocationGranularity;
WORD wProcessorLevel;
WORD wProcessorRevision;
} SYSTEM_INFO, *LPSYSTEM_INFO;
WINPR_API void GetSystemInfo(LPSYSTEM_INFO lpSystemInfo);
WINPR_API void GetNativeSystemInfo(LPSYSTEM_INFO lpSystemInfo);
#if defined(WITH_WINPR_DEPRECATED)
typedef struct
{
DWORD dwOSVersionInfoSize;
DWORD dwMajorVersion;
DWORD dwMinorVersion;
DWORD dwBuildNumber;
DWORD dwPlatformId;
CHAR szCSDVersion[128];
} OSVERSIONINFOA, *POSVERSIONINFOA, *LPOSVERSIONINFOA;
typedef struct
{
DWORD dwOSVersionInfoSize;
DWORD dwMajorVersion;
DWORD dwMinorVersion;
DWORD dwBuildNumber;
DWORD dwPlatformId;
WCHAR szCSDVersion[128];
} OSVERSIONINFOW, *POSVERSIONINFOW, *LPOSVERSIONINFOW;
typedef struct
{
DWORD dwOSVersionInfoSize;
DWORD dwMajorVersion;
DWORD dwMinorVersion;
DWORD dwBuildNumber;
DWORD dwPlatformId;
CHAR szCSDVersion[128];
WORD wServicePackMajor;
WORD wServicePackMinor;
WORD wSuiteMask;
BYTE wProductType;
BYTE wReserved;
} OSVERSIONINFOEXA, *POSVERSIONINFOEXA, *LPOSVERSIONINFOEXA;
typedef struct
{
DWORD dwOSVersionInfoSize;
DWORD dwMajorVersion;
DWORD dwMinorVersion;
DWORD dwBuildNumber;
DWORD dwPlatformId;
WCHAR szCSDVersion[128];
WORD wServicePackMajor;
WORD wServicePackMinor;
WORD wSuiteMask;
BYTE wProductType;
BYTE wReserved;
} OSVERSIONINFOEXW, *POSVERSIONINFOEXW, *LPOSVERSIONINFOEXW;
#ifdef UNICODE
#define OSVERSIONINFO OSVERSIONINFOW
#define OSVERSIONINFOEX OSVERSIONINFOEXW
#define POSVERSIONINFO POSVERSIONINFOW
#define POSVERSIONINFOEX POSVERSIONINFOEXW
#define LPOSVERSIONINFO LPOSVERSIONINFOW
#define LPOSVERSIONINFOEX LPOSVERSIONINFOEXW
#else
#define OSVERSIONINFO OSVERSIONINFOA
#define OSVERSIONINFOEX OSVERSIONINFOEXA
#define POSVERSIONINFO POSVERSIONINFOA
#define POSVERSIONINFOEX POSVERSIONINFOEXA
#define LPOSVERSIONINFO LPOSVERSIONINFOA
#define LPOSVERSIONINFOEX LPOSVERSIONINFOEXA
#endif
#define VER_PLATFORM_WIN32_NT 0x00000002
#define VER_SUITE_BACKOFFICE 0x00000004
#define VER_SUITE_BLADE 0x00000400
#define VER_SUITE_COMPUTE_SERVER 0x00004000
#define VER_SUITE_DATACENTER 0x00000080
#define VER_SUITE_ENTERPRISE 0x00000002
#define VER_SUITE_EMBEDDEDNT 0x00000040
#define VER_SUITE_PERSONAL 0x00000200
#define VER_SUITE_SINGLEUSERTS 0x00000100
#define VER_SUITE_SMALLBUSINESS 0x00000001
#define VER_SUITE_SMALLBUSINESS_RESTRICTED 0x00000020
#define VER_SUITE_STORAGE_SERVER 0x00002000
#define VER_SUITE_TERMINAL 0x00000010
#define VER_SUITE_WH_SERVER 0x00008000
#endif
#define VER_NT_DOMAIN_CONTROLLER 0x0000002
#define VER_NT_SERVER 0x0000003
#define VER_NT_WORKSTATION 0x0000001
WINPR_API void GetSystemTime(LPSYSTEMTIME lpSystemTime);
WINPR_API BOOL SetSystemTime(CONST SYSTEMTIME* lpSystemTime);
WINPR_API VOID GetLocalTime(LPSYSTEMTIME lpSystemTime);
WINPR_API BOOL SetLocalTime(CONST SYSTEMTIME* lpSystemTime);
WINPR_API VOID GetSystemTimeAsFileTime(LPFILETIME lpSystemTimeAsFileTime);
WINPR_API BOOL GetSystemTimeAdjustment(PDWORD lpTimeAdjustment, PDWORD lpTimeIncrement,
PBOOL lpTimeAdjustmentDisabled);
WINPR_API BOOL IsProcessorFeaturePresent(DWORD ProcessorFeature);
#define PF_FLOATING_POINT_PRECISION_ERRATA 0
#define PF_FLOATING_POINT_EMULATED 1
#define PF_COMPARE_EXCHANGE_DOUBLE 2
#define PF_MMX_INSTRUCTIONS_AVAILABLE 3
#define PF_PPC_MOVEMEM_64BIT_OK 4
#define PF_XMMI_INSTRUCTIONS_AVAILABLE 6 /* SSE */
#define PF_3DNOW_INSTRUCTIONS_AVAILABLE 7
#define PF_RDTSC_INSTRUCTION_AVAILABLE 8
#define PF_PAE_ENABLED 9
#define PF_XMMI64_INSTRUCTIONS_AVAILABLE 10 /* SSE2 */
#define PF_SSE_DAZ_MODE_AVAILABLE 11
#define PF_NX_ENABLED 12
#define PF_SSE3_INSTRUCTIONS_AVAILABLE 13
#define PF_COMPARE_EXCHANGE128 14
#define PF_COMPARE64_EXCHANGE128 15
#define PF_CHANNELS_ENABLED 16
#define PF_XSAVE_ENABLED 17
#define PF_ARM_VFP_32_REGISTERS_AVAILABLE 18
#define PF_ARM_NEON_INSTRUCTIONS_AVAILABLE 19
#define PF_SECOND_LEVEL_ADDRESS_TRANSLATION 20
#define PF_VIRT_FIRMWARE_ENABLED 21
#define PF_RDWRFSGSBASE_AVAILABLE 22
#define PF_FASTFAIL_AVAILABLE 23
#define PF_ARM_DIVIDE_INSTRUCTION_AVAILABLE 24
#define PF_ARM_64BIT_LOADSTORE_ATOMIC 25
#define PF_ARM_EXTERNAL_CACHE_AVAILABLE 26
#define PF_ARM_FMAC_INSTRUCTIONS_AVAILABLE 27
#define PF_SSSE3_INSTRUCTIONS_AVAILABLE 36 /** @since version 3.3.0 */
#define PF_SSE4_1_INSTRUCTIONS_AVAILABLE 37 /** @since version 3.3.0 */
#define PF_SSE4_2_INSTRUCTIONS_AVAILABLE 38 /** @since version 3.3.0 */
#define PF_AVX_INSTRUCTIONS_AVAILABLE 39 /** @since version 3.3.0 */
#define PF_AVX2_INSTRUCTIONS_AVAILABLE 40 /** @since version 3.3.0 */
#define PF_AVX512F_INSTRUCTIONS_AVAILABLE 41 /** @since version 3.3.0 */
#define PF_ARM_V8_INSTRUCTIONS_AVAILABLE 29 /** @since version 3.3.0 */
#define PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE 30 /** @since version 3.3.0 */
#define PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE 31 /** @since version 3.3.0 */
#define PF_ARM_V81_ATOMIC_INSTRUCTIONS_AVAILABLE 34 /** @since version 3.3.0 */
#define PF_ARM_V82_DP_INSTRUCTIONS_AVAILABLE 43 /** @since version 3.3.0 */
#define PF_ARM_V83_JSCVT_INSTRUCTIONS_AVAILABLE 44 /** @since version 3.3.0 */
#define PF_ARM_V83_LRCPC_INSTRUCTIONS_AVAILABLE 45 /** @since version 3.3.0 */
#define PF_ARM_V4 0x80000001
#define PF_ARM_V5 0x80000002
#define PF_ARM_V6 0x80000003
#define PF_ARM_V7 0x80000004
#define PF_ARM_THUMB 0x80000005
#define PF_ARM_JAZELLE 0x80000006
#define PF_ARM_DSP 0x80000007
#define PF_ARM_MOVE_CP 0x80000008
#define PF_ARM_VFP10 0x80000009
#define PF_ARM_MPU 0x8000000A
#define PF_ARM_WRITE_BUFFER 0x8000000B
#define PF_ARM_MBX 0x8000000C
#define PF_ARM_L2CACHE 0x8000000D
#define PF_ARM_PHYSICALLY_TAGGED_CACHE 0x8000000E
#define PF_ARM_VFP_SINGLE_PRECISION 0x8000000F
#define PF_ARM_VFP_DOUBLE_PRECISION 0x80000010
#define PF_ARM_ITCM 0x80000011
#define PF_ARM_DTCM 0x80000012
#define PF_ARM_UNIFIED_CACHE 0x80000013
#define PF_ARM_WRITE_BACK_CACHE 0x80000014
#define PF_ARM_CACHE_CAN_BE_LOCKED_DOWN 0x80000015
#define PF_ARM_L2CACHE_MEMORY_MAPPED 0x80000016
#define PF_ARM_L2CACHE_COPROC 0x80000017
#define PF_ARM_THUMB2 0x80000018
#define PF_ARM_T2EE 0x80000019
#define PF_ARM_VFP3 0x8000001A
#define PF_ARM_NEON 0x8000001B
#define PF_ARM_UNALIGNED_ACCESS 0x8000001C
#define PF_ARM_INTEL_XSCALE 0x80010001
#define PF_ARM_INTEL_PMU 0x80010002
#define PF_ARM_INTEL_WMMX 0x80010003
#endif
#if !defined(_WIN32) || defined(_UWP)
#if defined(WITH_WINPR_DEPRECATED)
WINPR_API BOOL GetVersionExA(LPOSVERSIONINFOA lpVersionInformation);
WINPR_API BOOL GetVersionExW(LPOSVERSIONINFOW lpVersionInformation);
#ifdef UNICODE
#define GetVersionEx GetVersionExW
#else
#define GetVersionEx GetVersionExA
#endif
#endif
#endif
#if !defined(_WIN32) || defined(_UWP)
WINPR_API DWORD GetTickCount(void);
typedef enum
{
ComputerNameNetBIOS,
ComputerNameDnsHostname,
ComputerNameDnsDomain,
ComputerNameDnsFullyQualified,
ComputerNamePhysicalNetBIOS,
ComputerNamePhysicalDnsHostname,
ComputerNamePhysicalDnsDomain,
ComputerNamePhysicalDnsFullyQualified,
ComputerNameMax
} COMPUTER_NAME_FORMAT;
#define MAX_COMPUTERNAME_LENGTH 31
WINPR_API BOOL GetComputerNameA(LPSTR lpBuffer, LPDWORD lpnSize);
WINPR_API BOOL GetComputerNameW(LPWSTR lpBuffer, LPDWORD lpnSize);
WINPR_API BOOL GetComputerNameExA(COMPUTER_NAME_FORMAT NameType, LPSTR lpBuffer,
LPDWORD lpnSize);
WINPR_API BOOL GetComputerNameExW(COMPUTER_NAME_FORMAT NameType, LPWSTR lpBuffer,
LPDWORD lpnSize);
#ifdef UNICODE
#define GetComputerName GetComputerNameW
#define GetComputerNameEx GetComputerNameExW
#else
#define GetComputerName GetComputerNameA
#define GetComputerNameEx GetComputerNameExA
#endif
#endif
#if (!defined(_WIN32)) || (defined(_WIN32) && (_WIN32_WINNT < 0x0600))
WINPR_API ULONGLONG winpr_GetTickCount64(void);
#define GetTickCount64 winpr_GetTickCount64
#endif
#define WINPR_TIME_NS_TO_S(ns) ((ns) / 1000000000ull) /** @since version 3.4.0 */
#define WINPR_TIME_NS_TO_MS(ns) ((ns) / 1000000ull) /** @since version 3.4.0 */
#define WINPR_TIME_NS_TO_US(ns) ((ns) / 1000ull) /** @since version 3.4.0 */
#define WINPR_TIME_NS_REM_NS(ns) ((ns) % 1000000000ull) /** @since version 3.4.0 */
#define WINPR_TIME_NS_REM_US(ns) (WINPR_TIME_NS_REM_NS(ns) / 1000ull) /** @since version 3.4.0 */
#define WINPR_TIME_NS_REM_MS(ns) (WINPR_TIME_NS_REM_US(ns) / 1000ull) /** @since version 3.4.0 */
/** @brief get current tick count in nano second resolution
* @since version 3.4.0
* @return The tick count in nanosecond resolution since a undefined reference data
*/
WINPR_API UINT64 winpr_GetTickCount64NS(void);
/** @brief the the current time in nano second resolution
* @since version 3.4.0
* @return The nano seconds since 1.1.1970
*/
WINPR_API UINT64 winpr_GetUnixTimeNS(void);
WINPR_API DWORD GetTickCountPrecise(void);
WINPR_API BOOL IsProcessorFeaturePresentEx(DWORD ProcessorFeature);
/* extended flags */
#define PF_EX_LZCNT 1
#define PF_EX_3DNOW_PREFETCH 2
#define PF_EX_SSSE3 3
#define PF_EX_SSE41 4
#define PF_EX_SSE42 5
#define PF_EX_AVX 6
#define PF_EX_FMA 7
#define PF_EX_AVX_AES 8
#define PF_EX_AVX2 9
#define PF_EX_ARM_VFP1 10
#define PF_EX_ARM_VFP3D16 11
#define PF_EX_ARM_VFP4 12
#define PF_EX_ARM_IDIVA 13
#define PF_EX_ARM_IDIVT 14
#define PF_EX_AVX_PCLMULQDQ 15
#define PF_EX_AVX512F 16
/*
* some "aliases" for the standard defines
* to be more clear
*/
#define PF_SSE_INSTRUCTIONS_AVAILABLE PF_XMMI_INSTRUCTIONS_AVAILABLE
#define PF_SSE2_INSTRUCTIONS_AVAILABLE PF_XMMI64_INSTRUCTIONS_AVAILABLE
#ifdef __cplusplus
}
#endif
#endif /* WINPR_SYSINFO_H */

View File

@@ -0,0 +1,74 @@
/**
* WinPR: Windows Portable Runtime
* TCHAR
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_TCHAR_H
#define WINPR_TCHAR_H
#include <winpr/crt.h>
#include <winpr/wtypes.h>
#ifdef _WIN32
#include <tchar.h>
#else
#ifdef UNICODE
typedef WCHAR TCHAR;
#else
typedef CHAR TCHAR;
#endif
#ifdef UNICODE
#define _tprintf wprintf
#define _sntprintf snwprintf
#define _tcslen _wcslen
#define _tcsnlen _wcsnlen
#define _tcsdup _wcsdup
#define _tcscmp wcscmp
#define _tcsncmp wcsncmp
#define _tcscpy wcscpy
#define _tcsncpy wcsncpy
#define _tcscat wcscat
#define _tcschr wcschr
#define _tcsrchr wcsrchr
#define _tcsstr wcsstr
#define _stprintf_s swprintf_s
#define _tcsnccmp wcsncmp
#else
#define _tprintf printf
#define _sntprintf snprintf
#define _tcslen strlen
#define _tcsnlen strnlen
#define _tcsdup _strdup
#define _tcscmp strcmp
#define _tcsncmp strncmp
#define _tcscpy strcpy
#define _tcsncpy strncpy
#define _tcscat strcat
#define _tcschr strchr
#define _tcsrchr strrchr
#define _tcsstr strstr
#define _stprintf_s sprintf_s
#define _tcsnccmp strncmp
#endif
#endif
#endif /* WINPR_TCHAR_H */

View File

@@ -0,0 +1,304 @@
/**
* WinPR: Windows Portable Runtime
* Process Thread Functions
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_THREAD_H
#define WINPR_THREAD_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/spec.h>
#include <winpr/handle.h>
#ifdef __cplusplus
extern "C"
{
#endif
#ifndef _WIN32
typedef struct
{
DWORD cb;
LPSTR lpReserved;
LPSTR lpDesktop;
LPSTR lpTitle;
DWORD dwX;
DWORD dwY;
DWORD dwXSize;
DWORD dwYSize;
DWORD dwXCountChars;
DWORD dwYCountChars;
DWORD dwFillAttribute;
DWORD dwFlags;
WORD wShowWindow;
WORD cbReserved2;
LPBYTE lpReserved2;
HANDLE hStdInput;
HANDLE hStdOutput;
HANDLE hStdError;
} STARTUPINFOA, *LPSTARTUPINFOA;
typedef struct
{
DWORD cb;
LPWSTR lpReserved;
LPWSTR lpDesktop;
LPWSTR lpTitle;
DWORD dwX;
DWORD dwY;
DWORD dwXSize;
DWORD dwYSize;
DWORD dwXCountChars;
DWORD dwYCountChars;
DWORD dwFillAttribute;
DWORD dwFlags;
WORD wShowWindow;
WORD cbReserved2;
LPBYTE lpReserved2;
HANDLE hStdInput;
HANDLE hStdOutput;
HANDLE hStdError;
} STARTUPINFOW, *LPSTARTUPINFOW;
#ifdef UNICODE
typedef STARTUPINFOW STARTUPINFO;
typedef LPSTARTUPINFOW LPSTARTUPINFO;
#else
typedef STARTUPINFOA STARTUPINFO;
typedef LPSTARTUPINFOA LPSTARTUPINFO;
#endif
#define STARTF_USESHOWWINDOW 0x00000001
#define STARTF_USESIZE 0x00000002
#define STARTF_USEPOSITION 0x00000004
#define STARTF_USECOUNTCHARS 0x00000008
#define STARTF_USEFILLATTRIBUTE 0x00000010
#define STARTF_RUNFULLSCREEN 0x00000020
#define STARTF_FORCEONFEEDBACK 0x00000040
#define STARTF_FORCEOFFFEEDBACK 0x00000080
#define STARTF_USESTDHANDLES 0x00000100
#define STARTF_USEHOTKEY 0x00000200
#define STARTF_TITLEISLINKNAME 0x00000800
#define STARTF_TITLEISAPPID 0x00001000
#define STARTF_PREVENTPINNING 0x00002000
/* Process */
#define LOGON_WITH_PROFILE 0x00000001
#define LOGON_NETCREDENTIALS_ONLY 0x00000002
#define LOGON_ZERO_PASSWORD_BUFFER 0x80000000
WINPR_API BOOL CreateProcessA(LPCSTR lpApplicationName, LPSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles,
DWORD dwCreationFlags, LPVOID lpEnvironment,
LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation);
WINPR_API BOOL CreateProcessW(LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles,
DWORD dwCreationFlags, LPVOID lpEnvironment,
LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation);
WINPR_API BOOL CreateProcessAsUserA(HANDLE hToken, LPCSTR lpApplicationName,
LPSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles, DWORD dwCreationFlags,
LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
LPSTARTUPINFOA lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation);
WINPR_API BOOL CreateProcessAsUserW(HANDLE hToken, LPCWSTR lpApplicationName,
LPWSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles, DWORD dwCreationFlags,
LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
LPSTARTUPINFOW lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation);
WINPR_API BOOL CreateProcessWithLogonA(LPCSTR lpUsername, LPCSTR lpDomain, LPCSTR lpPassword,
DWORD dwLogonFlags, LPCSTR lpApplicationName,
LPSTR lpCommandLine, DWORD dwCreationFlags,
LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
LPSTARTUPINFOA lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation);
WINPR_API BOOL CreateProcessWithLogonW(LPCWSTR lpUsername, LPCWSTR lpDomain, LPCWSTR lpPassword,
DWORD dwLogonFlags, LPCWSTR lpApplicationName,
LPWSTR lpCommandLine, DWORD dwCreationFlags,
LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
LPSTARTUPINFOW lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation);
WINPR_API BOOL CreateProcessWithTokenA(HANDLE hToken, DWORD dwLogonFlags,
LPCSTR lpApplicationName, LPSTR lpCommandLine,
DWORD dwCreationFlags, LPVOID lpEnvironment,
LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation);
WINPR_API BOOL CreateProcessWithTokenW(HANDLE hToken, DWORD dwLogonFlags,
LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
DWORD dwCreationFlags, LPVOID lpEnvironment,
LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation);
#ifdef UNICODE
#define CreateProcess CreateProcessW
#define CreateProcessAsUser CreateProcessAsUserW
#define CreateProcessWithLogon CreateProcessWithLogonW
#define CreateProcessWithToken CreateProcessWithTokenW
#else
#define CreateProcess CreateProcessA
#define CreateProcessAsUser CreateProcessAsUserA
#define CreateProcessWithLogon CreateProcessWithLogonA
#define CreateProcessWithToken CreateProcessWithTokenA
#endif
DECLSPEC_NORETURN WINPR_API VOID ExitProcess(UINT uExitCode);
WINPR_API BOOL GetExitCodeProcess(HANDLE hProcess, LPDWORD lpExitCode);
WINPR_PRAGMA_DIAG_PUSH
WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
WINPR_API HANDLE _GetCurrentProcess(void);
WINPR_PRAGMA_DIAG_POP
WINPR_API DWORD GetCurrentProcessId(void);
WINPR_API BOOL TerminateProcess(HANDLE hProcess, UINT uExitCode);
/* Process Argument Vector Parsing */
WINPR_API LPWSTR* CommandLineToArgvW(LPCWSTR lpCmdLine, int* pNumArgs);
#ifdef UNICODE
#define CommandLineToArgv CommandLineToArgvW
#else
#define CommandLineToArgv CommandLineToArgvA
#endif
/* Thread */
#define THREAD_MODE_BACKGROUND_BEGIN 0x00010000 /** @since version 3.6.0 */
#define THREAD_MODE_BACKGROUND_END 0x00020000 /** @since version 3.6.0 */
/** @defgroup THREAD_PRIORITY THREAD_PRIORITY
* @brief Known THREAD_PRIORITY values
* @since version 3.6.0
* @{
*/
#define THREAD_PRIORITY_ABOVE_NORMAL 1 /** @since version 3.6.0 */
#define THREAD_PRIORITY_BELOW_NORMAL -1 /** @since version 3.6.0 */
#define THREAD_PRIORITY_HIGHEST 2 /** @since version 3.6.0 */
#define THREAD_PRIORITY_IDLE -15 /** @since version 3.6.0 */
#define THREAD_PRIORITY_LOWEST -2 /** @since version 3.6.0 */
#define THREAD_PRIORITY_NORMAL 0 /** @since version 3.6.0 */
#define THREAD_PRIORITY_TIME_CRITICAL 15 /** @since version 3.6.0 */
/** @} */
/**
* @brief Change the thread priority
*
* @param hThread the thhread handle to manipulate
* @param nPriority The priority to set, see @ref THREAD_PRIORITY
* @return \b TRUE for success, \b FALSE otherwise
* @since version 3.6.0
*/
WINPR_API BOOL SetThreadPriority(HANDLE hThread, int nPriority);
#define CREATE_SUSPENDED 0x00000004
#define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes, size_t dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter,
DWORD dwCreationFlags, LPDWORD lpThreadId);
WINPR_ATTR_MALLOC(CloseHandle, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE CreateRemoteThread(HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes,
size_t dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter, DWORD dwCreationFlags,
LPDWORD lpThreadId);
WINPR_API VOID ExitThread(DWORD dwExitCode);
WINPR_API BOOL GetExitCodeThread(HANDLE hThread, LPDWORD lpExitCode);
WINPR_PRAGMA_DIAG_PUSH
WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
WINPR_API HANDLE _GetCurrentThread(void);
WINPR_PRAGMA_DIAG_POP
WINPR_API DWORD GetCurrentThreadId(void);
typedef void (*PAPCFUNC)(ULONG_PTR Parameter);
WINPR_API DWORD QueueUserAPC(PAPCFUNC pfnAPC, HANDLE hThread, ULONG_PTR dwData);
WINPR_API DWORD ResumeThread(HANDLE hThread);
WINPR_API DWORD SuspendThread(HANDLE hThread);
WINPR_API BOOL SwitchToThread(void);
WINPR_API BOOL TerminateThread(HANDLE hThread, DWORD dwExitCode);
/* Processor */
WINPR_API DWORD GetCurrentProcessorNumber(void);
/* Thread-Local Storage */
#define TLS_OUT_OF_INDEXES ((DWORD)0xFFFFFFFF)
WINPR_API DWORD TlsAlloc(void);
WINPR_API LPVOID TlsGetValue(DWORD dwTlsIndex);
WINPR_API BOOL TlsSetValue(DWORD dwTlsIndex, LPVOID lpTlsValue);
WINPR_API BOOL TlsFree(DWORD dwTlsIndex);
#else
/*
* GetCurrentProcess / GetCurrentThread cause a conflict on Mac OS X
*/
WINPR_PRAGMA_DIAG_PUSH
WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER
#define _GetCurrentProcess GetCurrentProcess
#define _GetCurrentThread GetCurrentThread
WINPR_PRAGMA_DIAG_POP
#endif
/* CommandLineToArgvA is not present in the original Windows API, WinPR always exports it */
WINPR_API LPSTR* CommandLineToArgvA(LPCSTR lpCmdLine, int* pNumArgs);
WINPR_API VOID DumpThreadHandles(void);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_THREAD_H */

View File

@@ -0,0 +1,128 @@
/**
* WinPR: Windows Portable Runtime
* Time Zone
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_TIMEZONE_H
#define WINPR_TIMEZONE_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/windows.h>
#ifdef __cplusplus
extern "C"
{
#endif
#ifndef _WIN32
typedef struct
{
LONG Bias;
WCHAR StandardName[32];
SYSTEMTIME StandardDate;
LONG StandardBias;
WCHAR DaylightName[32];
SYSTEMTIME DaylightDate;
LONG DaylightBias;
} TIME_ZONE_INFORMATION, *PTIME_ZONE_INFORMATION, *LPTIME_ZONE_INFORMATION;
typedef struct
{
LONG Bias;
WCHAR StandardName[32];
SYSTEMTIME StandardDate;
LONG StandardBias;
WCHAR DaylightName[32];
SYSTEMTIME DaylightDate;
LONG DaylightBias;
WCHAR TimeZoneKeyName[128];
BOOLEAN DynamicDaylightTimeDisabled;
} DYNAMIC_TIME_ZONE_INFORMATION, *PDYNAMIC_TIME_ZONE_INFORMATION,
*LPDYNAMIC_TIME_ZONE_INFORMATION;
/** @defgroup TIME_ZONE_ID TIME_ZONE_ID
* @brief Known values of TIME_ZONE_ID
* @since version 3.6.0
* @{
*/
#define TIME_ZONE_ID_UNKNOWN 0
#define TIME_ZONE_ID_STANDARD 1
#define TIME_ZONE_ID_DAYLIGHT 2
/** @} */
WINPR_API DWORD GetTimeZoneInformation(LPTIME_ZONE_INFORMATION lpTimeZoneInformation);
WINPR_API BOOL SetTimeZoneInformation(const TIME_ZONE_INFORMATION* lpTimeZoneInformation);
WINPR_API BOOL SystemTimeToFileTime(const SYSTEMTIME* lpSystemTime, LPFILETIME lpFileTime);
WINPR_API BOOL FileTimeToSystemTime(const FILETIME* lpFileTime, LPSYSTEMTIME lpSystemTime);
WINPR_API BOOL SystemTimeToTzSpecificLocalTime(LPTIME_ZONE_INFORMATION lpTimeZone,
LPSYSTEMTIME lpUniversalTime,
LPSYSTEMTIME lpLocalTime);
WINPR_API BOOL TzSpecificLocalTimeToSystemTime(LPTIME_ZONE_INFORMATION lpTimeZoneInformation,
LPSYSTEMTIME lpLocalTime,
LPSYSTEMTIME lpUniversalTime);
#endif
/*
* GetDynamicTimeZoneInformation is provided by the SDK if _WIN32_WINNT >= 0x0600 in SDKs above 7.1A
* and incorrectly if _WIN32_WINNT >= 0x0501 in older SDKs
*/
#if !defined(_WIN32) || \
(defined(_WIN32) && (defined(NTDDI_WIN8) && _WIN32_WINNT < 0x0600 || \
!defined(NTDDI_WIN8) && _WIN32_WINNT < 0x0501)) /* Windows Vista */
WINPR_API DWORD
GetDynamicTimeZoneInformation(PDYNAMIC_TIME_ZONE_INFORMATION pTimeZoneInformation);
WINPR_API BOOL
SetDynamicTimeZoneInformation(const DYNAMIC_TIME_ZONE_INFORMATION* lpTimeZoneInformation);
WINPR_API BOOL GetTimeZoneInformationForYear(USHORT wYear, PDYNAMIC_TIME_ZONE_INFORMATION pdtzi,
LPTIME_ZONE_INFORMATION ptzi);
#endif
#if !defined(_WIN32) || (defined(_WIN32) && (_WIN32_WINNT < 0x0601)) /* Windows 7 */
WINPR_API BOOL
SystemTimeToTzSpecificLocalTimeEx(const DYNAMIC_TIME_ZONE_INFORMATION* lpTimeZoneInformation,
const SYSTEMTIME* lpUniversalTime, LPSYSTEMTIME lpLocalTime);
WINPR_API BOOL
TzSpecificLocalTimeToSystemTimeEx(const DYNAMIC_TIME_ZONE_INFORMATION* lpTimeZoneInformation,
const SYSTEMTIME* lpLocalTime, LPSYSTEMTIME lpUniversalTime);
#endif
#if !defined(_WIN32) || (defined(_WIN32) && (_WIN32_WINNT < 0x0602)) /* Windows 8 */
WINPR_API
DWORD EnumDynamicTimeZoneInformation(DWORD dwIndex,
PDYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation);
WINPR_API DWORD GetDynamicTimeZoneInformationEffectiveYears(
const DYNAMIC_TIME_ZONE_INFORMATION* lpTimeZoneInformation, LPDWORD FirstYear,
LPDWORD LastYear);
#else
#pragma comment(lib, "advapi32")
#endif
#ifdef __cplusplus
}
#endif
#endif /* WINPR_TIMEZONE_H */

View File

@@ -0,0 +1,51 @@
/**
* WinPR: Windows Portable Runtime
* makecert replacement
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MAKECERT_TOOL_H
#define MAKECERT_TOOL_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#ifdef __cplusplus
extern "C"
{
#endif
typedef struct S_MAKECERT_CONTEXT MAKECERT_CONTEXT;
WINPR_API int makecert_context_process(MAKECERT_CONTEXT* context, int argc, char** argv);
WINPR_API int makecert_context_set_output_file_name(MAKECERT_CONTEXT* context,
const char* name);
WINPR_API int makecert_context_output_certificate_file(MAKECERT_CONTEXT* context,
const char* path);
WINPR_API int makecert_context_output_private_key_file(MAKECERT_CONTEXT* context,
const char* path);
WINPR_API void makecert_context_free(MAKECERT_CONTEXT* context);
WINPR_ATTR_MALLOC(makecert_context_free, 1)
WINPR_ATTR_NODISCARD
WINPR_API MAKECERT_CONTEXT* makecert_context_new(void);
#ifdef __cplusplus
}
#endif
#endif /* MAKECERT_TOOL_H */

View File

@@ -0,0 +1,298 @@
/**
* WinPR: Windows Portable Runtime
* User Environment
*
* Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_USER_H
#define WINPR_USER_H
#include <winpr/wtypes.h>
/**
* Standard Clipboard Formats
*/
#ifdef _WIN32
#include <winuser.h>
#else
#define MB_OK 0x00000000L
#define MB_OKCANCEL 0x00000001L
#define MB_ABORTRETRYIGNORE 0x00000002L
#define MB_YESNOCANCEL 0x00000003L
#define MB_YESNO 0x00000004L
#define MB_RETRYCANCEL 0x00000005L
#define MB_CANCELTRYCONTINUE 0x00000006L
#define IDOK 1
#define IDCANCEL 2
#define IDABORT 3
#define IDRETRY 4
#define IDIGNORE 5
#define IDYES 6
#define IDNO 7
#define IDTRYAGAIN 10
#define IDCONTINUE 11
#define IDTIMEOUT 32000
#define IDASYNC 32001
#define CF_RAW 0
#define CF_TEXT 1
#define CF_BITMAP 2
#define CF_METAFILEPICT 3
#define CF_SYLK 4
#define CF_DIF 5
#define CF_TIFF 6
#define CF_OEMTEXT 7
#define CF_DIB 8
#define CF_PALETTE 9
#define CF_PENDATA 10
#define CF_RIFF 11
#define CF_WAVE 12
#define CF_UNICODETEXT 13
#define CF_ENHMETAFILE 14
#define CF_HDROP 15
#define CF_LOCALE 16
#define CF_DIBV5 17
#define CF_MAX 18
#define CF_OWNERDISPLAY 0x0080
#define CF_DSPTEXT 0x0081
#define CF_DSPBITMAP 0x0082
#define CF_DSPMETAFILEPICT 0x0083
#define CF_DSPENHMETAFILE 0x008E
#define CF_PRIVATEFIRST 0x0200
#define CF_PRIVATELAST 0x02FF
#define CF_GDIOBJFIRST 0x0300
#define CF_GDIOBJLAST 0x03FF
/* Windows Metafile Picture Format */
#define MM_TEXT 1
#define MM_LOMETRIC 2
#define MM_HIMETRIC 3
#define MM_LOENGLISH 4
#define MM_HIENGLISH 5
#define MM_TWIPS 6
#define MM_ISOTROPIC 7
#define MM_ANISOTROPIC 8
#define MM_MIN MM_TEXT
#define MM_MAX MM_ANISOTROPIC
#define MM_MAX_FIXEDSCALE MM_TWIPS
#endif
/**
* Bitmap Definitions
*/
#if !defined(_WIN32)
#pragma pack(push, 1)
typedef LONG FXPT16DOT16, FAR *LPFXPT16DOT16;
typedef LONG FXPT2DOT30, FAR *LPFXPT2DOT30;
typedef struct tagCIEXYZ
{
FXPT2DOT30 ciexyzX;
FXPT2DOT30 ciexyzY;
FXPT2DOT30 ciexyzZ;
} CIEXYZ;
typedef CIEXYZ FAR* LPCIEXYZ;
typedef struct tagICEXYZTRIPLE
{
CIEXYZ ciexyzRed;
CIEXYZ ciexyzGreen;
CIEXYZ ciexyzBlue;
} CIEXYZTRIPLE;
typedef CIEXYZTRIPLE FAR* LPCIEXYZTRIPLE;
typedef struct tagBITMAP
{
LONG bmType;
LONG bmWidth;
LONG bmHeight;
LONG bmWidthBytes;
WORD bmPlanes;
WORD bmBitsPixel;
LPVOID bmBits;
} BITMAP, *PBITMAP, NEAR *NPBITMAP, FAR *LPBITMAP;
typedef struct tagRGBTRIPLE
{
BYTE rgbtBlue;
BYTE rgbtGreen;
BYTE rgbtRed;
} RGBTRIPLE, *PRGBTRIPLE, NEAR *NPRGBTRIPLE, FAR *LPRGBTRIPLE;
typedef struct tagRGBQUAD
{
BYTE rgbBlue;
BYTE rgbGreen;
BYTE rgbRed;
BYTE rgbReserved;
} RGBQUAD;
typedef RGBQUAD FAR* LPRGBQUAD;
#define BI_RGB 0
#define BI_RLE8 1
#define BI_RLE4 2
#define BI_BITFIELDS 3
#define BI_JPEG 4
#define BI_PNG 5
#define PROFILE_LINKED 'LINK'
#define PROFILE_EMBEDDED 'MBED'
typedef struct tagBITMAPINFOHEADER
{
DWORD biSize;
LONG biWidth;
LONG biHeight;
WORD biPlanes;
WORD biBitCount;
DWORD biCompression;
DWORD biSizeImage;
LONG biXPelsPerMeter;
LONG biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
} BITMAPINFOHEADER, FAR *LPBITMAPINFOHEADER, *PBITMAPINFOHEADER;
typedef struct
{
BITMAPINFOHEADER bmiHeader;
RGBQUAD bmiColors[1];
} BITMAPINFO, FAR *LPBITMAPINFO, *PBITMAPINFO;
typedef enum
{
ORIENTATION_PREFERENCE_NONE = 0x0,
ORIENTATION_PREFERENCE_LANDSCAPE = 0x1,
ORIENTATION_PREFERENCE_PORTRAIT = 0x2,
ORIENTATION_PREFERENCE_LANDSCAPE_FLIPPED = 0x4,
ORIENTATION_PREFERENCE_PORTRAIT_FLIPPED = 0x8
} ORIENTATION_PREFERENCE;
#pragma pack(pop)
#endif
#if !defined(_WIN32) || defined(_UWP)
#pragma pack(push, 1)
typedef struct tagBITMAPCOREHEADER
{
DWORD bcSize;
WORD bcWidth;
WORD bcHeight;
WORD bcPlanes;
WORD bcBitCount;
} BITMAPCOREHEADER, FAR *LPBITMAPCOREHEADER, *PBITMAPCOREHEADER;
typedef struct
{
DWORD bV4Size;
LONG bV4Width;
LONG bV4Height;
WORD bV4Planes;
WORD bV4BitCount;
DWORD bV4V4Compression;
DWORD bV4SizeImage;
LONG bV4XPelsPerMeter;
LONG bV4YPelsPerMeter;
DWORD bV4ClrUsed;
DWORD bV4ClrImportant;
DWORD bV4RedMask;
DWORD bV4GreenMask;
DWORD bV4BlueMask;
DWORD bV4AlphaMask;
DWORD bV4CSType;
CIEXYZTRIPLE bV4Endpoints;
DWORD bV4GammaRed;
DWORD bV4GammaGreen;
DWORD bV4GammaBlue;
} BITMAPV4HEADER, FAR *LPBITMAPV4HEADER, *PBITMAPV4HEADER;
typedef struct
{
DWORD bV5Size;
LONG bV5Width;
LONG bV5Height;
WORD bV5Planes;
WORD bV5BitCount;
DWORD bV5Compression;
DWORD bV5SizeImage;
LONG bV5XPelsPerMeter;
LONG bV5YPelsPerMeter;
DWORD bV5ClrUsed;
DWORD bV5ClrImportant;
DWORD bV5RedMask;
DWORD bV5GreenMask;
DWORD bV5BlueMask;
DWORD bV5AlphaMask;
DWORD bV5CSType;
CIEXYZTRIPLE bV5Endpoints;
DWORD bV5GammaRed;
DWORD bV5GammaGreen;
DWORD bV5GammaBlue;
DWORD bV5Intent;
DWORD bV5ProfileData;
DWORD bV5ProfileSize;
DWORD bV5Reserved;
} BITMAPV5HEADER, FAR *LPBITMAPV5HEADER, *PBITMAPV5HEADER;
typedef struct tagBITMAPCOREINFO
{
BITMAPCOREHEADER bmciHeader;
RGBTRIPLE bmciColors[1];
} BITMAPCOREINFO, FAR *LPBITMAPCOREINFO, *PBITMAPCOREINFO;
typedef struct tagBITMAPFILEHEADER
{
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} BITMAPFILEHEADER, FAR *LPBITMAPFILEHEADER, *PBITMAPFILEHEADER;
#pragma pack(pop)
#endif
#ifdef __cplusplus
extern "C"
{
#endif
#ifdef __cplusplus
}
#endif
#endif /* WINPR_USER_H */

View File

@@ -0,0 +1,738 @@
/**
* WinPR: Windows Portable Runtime
* Cryptography API (CryptoAPI)
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_WINCRYPT_H
#define WINPR_WINCRYPT_H
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/error.h>
#ifdef _WIN32
#include <wincrypt.h>
#endif
#ifndef ALG_TYPE_RESERVED7
#define ALG_TYPE_RESERVED7 (7 << 9)
#endif
#if !defined(NTDDI_VERSION) || (NTDDI_VERSION <= 0x05010200)
#define ALG_SID_SHA_256 12
#define ALG_SID_SHA_384 13
#define ALG_SID_SHA_512 14
#define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
#define CALG_SHA_384 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
#define CALG_SHA_512 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)
#endif
#ifndef _WIN32
/* ncrypt.h */
typedef ULONG_PTR NCRYPT_HANDLE;
typedef ULONG_PTR NCRYPT_PROV_HANDLE;
typedef ULONG_PTR NCRYPT_KEY_HANDLE;
typedef ULONG_PTR NCRYPT_HASH_HANDLE;
typedef ULONG_PTR NCRYPT_SECRET_HANDLE;
/* wincrypt.h */
#define GET_ALG_CLASS(x) (x & (7 << 13))
#define GET_ALG_TYPE(x) (x & (15 << 9))
#define GET_ALG_SID(x) (x & (511))
#define ALG_CLASS_ANY (0)
#define ALG_CLASS_SIGNATURE (1 << 13)
#define ALG_CLASS_MSG_ENCRYPT (2 << 13)
#define ALG_CLASS_DATA_ENCRYPT (3 << 13)
#define ALG_CLASS_HASH (4 << 13)
#define ALG_CLASS_KEY_EXCHANGE (5 << 13)
#define ALG_CLASS_ALL (7 << 13)
#define ALG_TYPE_ANY (0)
#define ALG_TYPE_DSS (1 << 9)
#define ALG_TYPE_RSA (2 << 9)
#define ALG_TYPE_BLOCK (3 << 9)
#define ALG_TYPE_STREAM (4 << 9)
#define ALG_TYPE_DH (5 << 9)
#define ALG_TYPE_SECURECHANNEL (6 << 9)
#define ALG_SID_ANY (0)
#define ALG_SID_RSA_ANY 0
#define ALG_SID_RSA_PKCS 1
#define ALG_SID_RSA_MSATWORK 2
#define ALG_SID_RSA_ENTRUST 3
#define ALG_SID_RSA_PGP 4
#define ALG_SID_DSS_ANY 0
#define ALG_SID_DSS_PKCS 1
#define ALG_SID_DSS_DMS 2
#define ALG_SID_DES 1
#define ALG_SID_3DES 3
#define ALG_SID_DESX 4
#define ALG_SID_IDEA 5
#define ALG_SID_CAST 6
#define ALG_SID_SAFERSK64 7
#define ALG_SID_SAFERSK128 8
#define ALG_SID_3DES_112 9
#define ALG_SID_CYLINK_MEK 12
#define ALG_SID_RC5 13
#define ALG_SID_AES_128 14
#define ALG_SID_AES_192 15
#define ALG_SID_AES_256 16
#define ALG_SID_AES 17
#define ALG_SID_SKIPJACK 10
#define ALG_SID_TEK 11
#define CRYPT_MODE_CBCI 6
#define CRYPT_MODE_CFBP 7
#define CRYPT_MODE_OFBP 8
#define CRYPT_MODE_CBCOFM 9
#define CRYPT_MODE_CBCOFMI 10
#define ALG_SID_RC2 2
#define ALG_SID_RC4 1
#define ALG_SID_SEAL 2
#define ALG_SID_DH_SANDF 1
#define ALG_SID_DH_EPHEM 2
#define ALG_SID_AGREED_KEY_ANY 3
#define ALG_SID_KEA 4
#define ALG_SID_ECDH 5
#define ALG_SID_MD2 1
#define ALG_SID_MD4 2
#define ALG_SID_MD5 3
#define ALG_SID_SHA 4
#define ALG_SID_SHA1 4
#define ALG_SID_MAC 5
#define ALG_SID_RIPEMD 6
#define ALG_SID_RIPEMD160 7
#define ALG_SID_SSL3SHAMD5 8
#define ALG_SID_HMAC 9
#define ALG_SID_TLS1PRF 10
#define ALG_SID_HASH_REPLACE_OWF 11
#define ALG_SID_SHA_256 12
#define ALG_SID_SHA_384 13
#define ALG_SID_SHA_512 14
#define ALG_SID_SSL3_MASTER 1
#define ALG_SID_SCHANNEL_MASTER_HASH 2
#define ALG_SID_SCHANNEL_MAC_KEY 3
#define ALG_SID_PCT1_MASTER 4
#define ALG_SID_SSL2_MASTER 5
#define ALG_SID_TLS1_MASTER 6
#define ALG_SID_SCHANNEL_ENC_KEY 7
#define ALG_SID_ECMQV 1
#define CALG_MD2 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD2)
#define CALG_MD4 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD4)
#define CALG_MD5 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD5)
#define CALG_SHA (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA)
#define CALG_SHA1 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA1)
#define CALG_MAC (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MAC)
#define CALG_RSA_SIGN (ALG_CLASS_SIGNATURE | ALG_TYPE_RSA | ALG_SID_RSA_ANY)
#define CALG_DSS_SIGN (ALG_CLASS_SIGNATURE | ALG_TYPE_DSS | ALG_SID_DSS_ANY)
#define CALG_NO_SIGN (ALG_CLASS_SIGNATURE | ALG_TYPE_ANY | ALG_SID_ANY)
#define CALG_RSA_KEYX (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_RSA | ALG_SID_RSA_ANY)
#define CALG_DES (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_DES)
#define CALG_3DES_112 (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_3DES_112)
#define CALG_3DES (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_3DES)
#define CALG_DESX (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_DESX)
#define CALG_RC2 (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_RC2)
#define CALG_RC4 (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_STREAM | ALG_SID_RC4)
#define CALG_SEAL (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_STREAM | ALG_SID_SEAL)
#define CALG_DH_SF (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_DH_SANDF)
#define CALG_DH_EPHEM (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_DH_EPHEM)
#define CALG_AGREEDKEY_ANY (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_AGREED_KEY_ANY)
#define CALG_KEA_KEYX (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_KEA)
#define CALG_HUGHES_MD5 (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_ANY | ALG_SID_MD5)
#define CALG_SKIPJACK (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_SKIPJACK)
#define CALG_TEK (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_TEK)
#define CALG_CYLINK_MEK (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_CYLINK_MEK)
#define CALG_SSL3_SHAMD5 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SSL3SHAMD5)
#define CALG_SSL3_MASTER (ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL | ALG_SID_SSL3_MASTER)
#define CALG_SCHANNEL_MASTER_HASH \
(ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL | ALG_SID_SCHANNEL_MASTER_HASH)
#define CALG_SCHANNEL_MAC_KEY \
(ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL | ALG_SID_SCHANNEL_MAC_KEY)
#define CALG_SCHANNEL_ENC_KEY \
(ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL | ALG_SID_SCHANNEL_ENC_KEY)
#define CALG_PCT1_MASTER (ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL | ALG_SID_PCT1_MASTER)
#define CALG_SSL2_MASTER (ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL | ALG_SID_SSL2_MASTER)
#define CALG_TLS1_MASTER (ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL | ALG_SID_TLS1_MASTER)
#define CALG_RC5 (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_RC5)
#define CALG_HMAC (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_HMAC)
#define CALG_TLS1PRF (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_TLS1PRF)
#define CALG_HASH_REPLACE_OWF (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_HASH_REPLACE_OWF)
#define CALG_AES_128 (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES_128)
#define CALG_AES_192 (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES_192)
#define CALG_AES_256 (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES_256)
#define CALG_AES (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES)
#define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
#define CALG_SHA_384 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
#define CALG_SHA_512 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)
#define CALG_ECDH (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_ECDH)
#define CALG_ECMQV (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_ANY | ALG_SID_ECMQV)
typedef struct
{
DWORD cbData;
BYTE* pbData;
} CRYPT_INTEGER_BLOB, *PCRYPT_INTEGER_BLOB, CRYPT_UINT_BLOB, *PCRYPT_UINT_BLOB, CRYPT_OBJID_BLOB,
*PCRYPT_OBJID_BLOB, CERT_NAME_BLOB, *PCERT_NAME_BLOB, CERT_RDN_VALUE_BLOB,
*PCERT_RDN_VALUE_BLOB, CERT_BLOB, *PCERT_BLOB, CRL_BLOB, *PCRL_BLOB, DATA_BLOB, *PDATA_BLOB,
CRYPT_DATA_BLOB, *PCRYPT_DATA_BLOB, CRYPT_HASH_BLOB, *PCRYPT_HASH_BLOB, CRYPT_DIGEST_BLOB,
*PCRYPT_DIGEST_BLOB, CRYPT_DER_BLOB, *PCRYPT_DER_BLOB, CRYPT_ATTR_BLOB, *PCRYPT_ATTR_BLOB;
typedef struct
{
LPSTR pszObjId;
CRYPT_OBJID_BLOB Parameters;
} CRYPT_ALGORITHM_IDENTIFIER, *PCRYPT_ALGORITHM_IDENTIFIER;
typedef struct
{
DWORD cbData;
BYTE* pbData;
DWORD cUnusedBits;
} CRYPT_BIT_BLOB, *PCRYPT_BIT_BLOB;
typedef struct
{
CRYPT_ALGORITHM_IDENTIFIER Algorithm;
CRYPT_BIT_BLOB PublicKey;
} CERT_PUBLIC_KEY_INFO, *PCERT_PUBLIC_KEY_INFO;
typedef struct
{
LPSTR pszObjId;
BOOL fCritical;
CRYPT_OBJID_BLOB Value;
} CERT_EXTENSION, *PCERT_EXTENSION;
typedef const CERT_EXTENSION* PCCERT_EXTENSION;
typedef struct
{
DWORD dwVersion;
CRYPT_INTEGER_BLOB SerialNumber;
CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm;
CERT_NAME_BLOB Issuer;
FILETIME NotBefore;
FILETIME NotAfter;
CERT_NAME_BLOB Subject;
CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo;
CRYPT_BIT_BLOB IssuerUniqueId;
CRYPT_BIT_BLOB SubjectUniqueId;
DWORD cExtension;
PCERT_EXTENSION rgExtension;
} CERT_INFO, *PCERT_INFO;
typedef void* HCERTSTORE;
typedef ULONG_PTR HCRYPTPROV;
typedef ULONG_PTR HCRYPTPROV_LEGACY;
typedef struct
{
DWORD dwCertEncodingType;
BYTE* pbCertEncoded;
DWORD cbCertEncoded;
PCERT_INFO pCertInfo;
HCERTSTORE hCertStore;
} CERT_CONTEXT, *PCERT_CONTEXT;
typedef const CERT_CONTEXT* PCCERT_CONTEXT;
#if !defined(AT_KEYEXCHANGE)
#define AT_KEYEXCHANGE (1)
#endif
#if !defined(AT_SIGNATURE)
#define AT_SIGNATURE (2)
#endif
#if !defined(AT_AUTHENTICATE)
#define AT_AUTHENTICATE (3)
#endif
#define CERT_ENCODING_TYPE_MASK 0x0000FFFF
#define CMSG_ENCODING_TYPE_MASK 0xFFFF0000
#define GET_CERT_ENCODING_TYPE(x) (x & CERT_ENCODING_TYPE_MASK)
#define GET_CMSG_ENCODING_TYPE(x) (x & CMSG_ENCODING_TYPE_MASK)
#define CRYPT_ASN_ENCODING 0x00000001
#define CRYPT_NDR_ENCODING 0x00000002
#define X509_ASN_ENCODING 0x00000001
#define X509_NDR_ENCODING 0x00000002
#define PKCS_7_ASN_ENCODING 0x00010000
#define PKCS_7_NDR_ENCODING 0x00020000
#define CERT_KEY_PROV_HANDLE_PROP_ID 1
#define CERT_KEY_PROV_INFO_PROP_ID 2
#define CERT_SHA1_HASH_PROP_ID 3
#define CERT_MD5_HASH_PROP_ID 4
#define CERT_HASH_PROP_ID CERT_SHA1_HASH_PROP_ID
#define CERT_KEY_CONTEXT_PROP_ID 5
#define CERT_KEY_SPEC_PROP_ID 6
#define CERT_IE30_RESERVED_PROP_ID 7
#define CERT_PUBKEY_HASH_RESERVED_PROP_ID 8
#define CERT_ENHKEY_USAGE_PROP_ID 9
#define CERT_CTL_USAGE_PROP_ID CERT_ENHKEY_USAGE_PROP_ID
#define CERT_NEXT_UPDATE_LOCATION_PROP_ID 10
#define CERT_FRIENDLY_NAME_PROP_ID 11
#define CERT_PVK_FILE_PROP_ID 12
#define CERT_DESCRIPTION_PROP_ID 13
#define CERT_ACCESS_STATE_PROP_ID 14
#define CERT_SIGNATURE_HASH_PROP_ID 15
#define CERT_SMART_CARD_DATA_PROP_ID 16
#define CERT_EFS_PROP_ID 17
#define CERT_FORTEZZA_DATA_PROP_ID 18
#define CERT_ARCHIVED_PROP_ID 19
#define CERT_KEY_IDENTIFIER_PROP_ID 20
#define CERT_AUTO_ENROLL_PROP_ID 21
#define CERT_PUBKEY_ALG_PARA_PROP_ID 22
#define CERT_CROSS_CERT_DIST_POINTS_PROP_ID 23
#define CERT_ISSUER_PUBLIC_KEY_MD5_HASH_PROP_ID 24
#define CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID 25
#define CERT_ENROLLMENT_PROP_ID 26
#define CERT_DATE_STAMP_PROP_ID 27
#define CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID 28
#define CERT_SUBJECT_NAME_MD5_HASH_PROP_ID 29
#define CERT_EXTENDED_ERROR_INFO_PROP_ID 30
#define CERT_RENEWAL_PROP_ID 64
#define CERT_ARCHIVED_KEY_HASH_PROP_ID 65
#define CERT_AUTO_ENROLL_RETRY_PROP_ID 66
#define CERT_AIA_URL_RETRIEVED_PROP_ID 67
#define CERT_AUTHORITY_INFO_ACCESS_PROP_ID 68
#define CERT_BACKED_UP_PROP_ID 69
#define CERT_OCSP_RESPONSE_PROP_ID 70
#define CERT_REQUEST_ORIGINATOR_PROP_ID 71
#define CERT_SOURCE_LOCATION_PROP_ID 72
#define CERT_SOURCE_URL_PROP_ID 73
#define CERT_NEW_KEY_PROP_ID 74
#define CERT_OCSP_CACHE_PREFIX_PROP_ID 75
#define CERT_SMART_CARD_ROOT_INFO_PROP_ID 76
#define CERT_NO_AUTO_EXPIRE_CHECK_PROP_ID 77
#define CERT_NCRYPT_KEY_HANDLE_PROP_ID 78
#define CERT_HCRYPTPROV_OR_NCRYPT_KEY_HANDLE_PROP_ID 79
#define CERT_SUBJECT_INFO_ACCESS_PROP_ID 80
#define CERT_CA_OCSP_AUTHORITY_INFO_ACCESS_PROP_ID 81
#define CERT_CA_DISABLE_CRL_PROP_ID 82
#define CERT_ROOT_PROGRAM_CERT_POLICIES_PROP_ID 83
#define CERT_ROOT_PROGRAM_NAME_CONSTRAINTS_PROP_ID 84
#define CERT_SUBJECT_OCSP_AUTHORITY_INFO_ACCESS_PROP_ID 85
#define CERT_SUBJECT_DISABLE_CRL_PROP_ID 86
#define CERT_CEP_PROP_ID 87
#define CERT_SIGN_HASH_CNG_ALG_PROP_ID 89
#define CERT_SCARD_PIN_ID_PROP_ID 90
#define CERT_SCARD_PIN_INFO_PROP_ID 91
#define CERT_SUBJECT_PUB_KEY_BIT_LENGTH_PROP_ID 92
#define CERT_PUB_KEY_CNG_ALG_BIT_LENGTH_PROP_ID 93
#define CERT_ISSUER_PUB_KEY_BIT_LENGTH_PROP_ID 94
#define CERT_ISSUER_CHAIN_SIGN_HASH_CNG_ALG_PROP_ID 95
#define CERT_ISSUER_CHAIN_PUB_KEY_CNG_ALG_BIT_LENGTH_PROP_ID 96
#define CERT_NO_EXPIRE_NOTIFICATION_PROP_ID 97
#define CERT_AUTH_ROOT_SHA256_HASH_PROP_ID 98
#define CERT_NCRYPT_KEY_HANDLE_TRANSFER_PROP_ID 99
#define CERT_HCRYPTPROV_TRANSFER_PROP_ID 100
#define CERT_SMART_CARD_READER_PROP_ID 101
#define CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID 102
#define CERT_KEY_REPAIR_ATTEMPTED_PROP_ID 103
#define CERT_DISALLOWED_FILETIME_PROP_ID 104
#define CERT_ROOT_PROGRAM_CHAIN_POLICIES_PROP_ID 105
#define CERT_SMART_CARD_READER_NON_REMOVABLE_PROP_ID 106
#define CERT_SHA256_HASH_PROP_ID 107
#define CERT_SCEP_SERVER_CERTS_PROP_ID 108
#define CERT_SCEP_RA_SIGNATURE_CERT_PROP_ID 109
#define CERT_SCEP_RA_ENCRYPTION_CERT_PROP_ID 110
#define CERT_SCEP_CA_CERT_PROP_ID 111
#define CERT_SCEP_SIGNER_CERT_PROP_ID 112
#define CERT_SCEP_NONCE_PROP_ID 113
#define CERT_SCEP_ENCRYPT_HASH_CNG_ALG_PROP_ID 114
#define CERT_SCEP_FLAGS_PROP_ID 115
#define CERT_SCEP_GUID_PROP_ID 116
#define CERT_SERIALIZABLE_KEY_CONTEXT_PROP_ID 117
#define CERT_ISOLATED_KEY_PROP_ID 118
#define CERT_SERIAL_CHAIN_PROP_ID 119
#define CERT_KEY_CLASSIFICATION_PROP_ID 120
#define CERT_OCSP_MUST_STAPLE_PROP_ID 121
#define CERT_DISALLOWED_ENHKEY_USAGE_PROP_ID 122
#define CERT_NONCOMPLIANT_ROOT_URL_PROP_ID 123
#define CERT_PIN_SHA256_HASH_PROP_ID 124
#define CERT_CLR_DELETE_KEY_PROP_ID 125
#define CERT_NOT_BEFORE_FILETIME_PROP_ID 126
#define CERT_NOT_BEFORE_ENHKEY_USAGE_PROP_ID 127
#define CERT_FIRST_RESERVED_PROP_ID 107
#define CERT_LAST_RESERVED_PROP_ID 0x00007fff
#define CERT_FIRST_USER_PROP_ID 0x8000
#define CERT_LAST_USER_PROP_ID 0x0000ffff
#define CERT_COMPARE_MASK 0xFFFF
#define CERT_COMPARE_SHIFT 16
#define CERT_COMPARE_ANY 0
#define CERT_COMPARE_SHA1_HASH 1
#define CERT_COMPARE_NAME 2
#define CERT_COMPARE_ATTR 3
#define CERT_COMPARE_MD5_HASH 4
#define CERT_COMPARE_PROPERTY 5
#define CERT_COMPARE_PUBLIC_KEY 6
#define CERT_COMPARE_HASH CERT_COMPARE_SHA1_HASH
#define CERT_COMPARE_NAME_STR_A 7
#define CERT_COMPARE_NAME_STR_W 8
#define CERT_COMPARE_KEY_SPEC 9
#define CERT_COMPARE_ENHKEY_USAGE 10
#define CERT_COMPARE_CTL_USAGE CERT_COMPARE_ENHKEY_USAGE
#define CERT_COMPARE_SUBJECT_CERT 11
#define CERT_COMPARE_ISSUER_OF 12
#define CERT_COMPARE_EXISTING 13
#define CERT_COMPARE_SIGNATURE_HASH 14
#define CERT_COMPARE_KEY_IDENTIFIER 15
#define CERT_COMPARE_CERT_ID 16
#define CERT_COMPARE_CROSS_CERT_DIST_POINTS 17
#define CERT_COMPARE_PUBKEY_MD5_HASH 18
#define CERT_COMPARE_SUBJECT_INFO_ACCESS 19
#define CERT_COMPARE_HASH_STR 20
#define CERT_COMPARE_HAS_PRIVATE_KEY 21
#define CERT_FIND_ANY (CERT_COMPARE_ANY << CERT_COMPARE_SHIFT)
#define CERT_FIND_SHA1_HASH (CERT_COMPARE_SHA1_HASH << CERT_COMPARE_SHIFT)
#define CERT_FIND_MD5_HASH (CERT_COMPARE_MD5_HASH << CERT_COMPARE_SHIFT)
#define CERT_FIND_SIGNATURE_HASH (CERT_COMPARE_SIGNATURE_HASH << CERT_COMPARE_SHIFT)
#define CERT_FIND_KEY_IDENTIFIER (CERT_COMPARE_KEY_IDENTIFIER << CERT_COMPARE_SHIFT)
#define CERT_FIND_HASH CERT_FIND_SHA1_HASH
#define CERT_FIND_PROPERTY (CERT_COMPARE_PROPERTY << CERT_COMPARE_SHIFT)
#define CERT_FIND_PUBLIC_KEY (CERT_COMPARE_PUBLIC_KEY << CERT_COMPARE_SHIFT)
#define CERT_FIND_SUBJECT_NAME (CERT_COMPARE_NAME << CERT_COMPARE_SHIFT | CERT_INFO_SUBJECT_FLAG)
#define CERT_FIND_SUBJECT_ATTR (CERT_COMPARE_ATTR << CERT_COMPARE_SHIFT | CERT_INFO_SUBJECT_FLAG)
#define CERT_FIND_ISSUER_NAME (CERT_COMPARE_NAME << CERT_COMPARE_SHIFT | CERT_INFO_ISSUER_FLAG)
#define CERT_FIND_ISSUER_ATTR (CERT_COMPARE_ATTR << CERT_COMPARE_SHIFT | CERT_INFO_ISSUER_FLAG)
#define CERT_FIND_SUBJECT_STR_A \
(CERT_COMPARE_NAME_STR_A << CERT_COMPARE_SHIFT | CERT_INFO_SUBJECT_FLAG)
#define CERT_FIND_SUBJECT_STR_W \
(CERT_COMPARE_NAME_STR_W << CERT_COMPARE_SHIFT | CERT_INFO_SUBJECT_FLAG)
#define CERT_FIND_SUBJECT_STR CERT_FIND_SUBJECT_STR_W
#define CERT_FIND_ISSUER_STR_A \
(CERT_COMPARE_NAME_STR_A << CERT_COMPARE_SHIFT | CERT_INFO_ISSUER_FLAG)
#define CERT_FIND_ISSUER_STR_W \
(CERT_COMPARE_NAME_STR_W << CERT_COMPARE_SHIFT | CERT_INFO_ISSUER_FLAG)
#define CERT_FIND_ISSUER_STR CERT_FIND_ISSUER_STR_W
#define CERT_FIND_KEY_SPEC (CERT_COMPARE_KEY_SPEC << CERT_COMPARE_SHIFT)
#define CERT_FIND_ENHKEY_USAGE (CERT_COMPARE_ENHKEY_USAGE << CERT_COMPARE_SHIFT)
#define CERT_FIND_CTL_USAGE CERT_FIND_ENHKEY_USAGE
#define CERT_FIND_SUBJECT_CERT (CERT_COMPARE_SUBJECT_CERT << CERT_COMPARE_SHIFT)
#define CERT_FIND_ISSUER_OF (CERT_COMPARE_ISSUER_OF << CERT_COMPARE_SHIFT)
#define CERT_FIND_EXISTING (CERT_COMPARE_EXISTING << CERT_COMPARE_SHIFT)
#define CERT_FIND_CERT_ID (CERT_COMPARE_CERT_ID << CERT_COMPARE_SHIFT)
#define CERT_FIND_CROSS_CERT_DIST_POINTS (CERT_COMPARE_CROSS_CERT_DIST_POINTS << CERT_COMPARE_SHIFT)
#define CERT_FIND_PUBKEY_MD5_HASH (CERT_COMPARE_PUBKEY_MD5_HASH << CERT_COMPARE_SHIFT)
#define CERT_FIND_SUBJECT_INFO_ACCESS (CERT_COMPARE_SUBJECT_INFO_ACCESS << CERT_COMPARE_SHIFT)
#define CERT_FIND_HASH_STR (CERT_COMPARE_HASH_STR << CERT_COMPARE_SHIFT)
#define CERT_FIND_HAS_PRIVATE_KEY (CERT_COMPARE_HAS_PRIVATE_KEY << CERT_COMPARE_SHIFT)
#define CERT_FIND_OPTIONAL_ENHKEY_USAGE_FLAG 0x1
#define CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG 0x2
#define CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG 0x4
#define CERT_FIND_NO_ENHKEY_USAGE_FLAG 0x8
#define CERT_FIND_OR_ENHKEY_USAGE_FLAG 0x10
#define CERT_FIND_VALID_ENHKEY_USAGE_FLAG 0x20
#define CERT_FIND_OPTIONAL_CTL_USAGE_FLAG CERT_FIND_OPTIONAL_ENHKEY_USAGE_FLAG
#define CERT_FIND_EXT_ONLY_CTL_USAGE_FLAG CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG
#define CERT_FIND_PROP_ONLY_CTL_USAGE_FLAG CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG
#define CERT_FIND_NO_CTL_USAGE_FLAG CERT_FIND_NO_ENHKEY_USAGE_FLAG
#define CERT_FIND_OR_CTL_USAGE_FLAG CERT_FIND_OR_ENHKEY_USAGE_FLAG
#define CERT_FIND_VALID_CTL_USAGE_FLAG CERT_FIND_VALID_ENHKEY_USAGE_FLAG
#define CERT_NAME_EMAIL_TYPE 1
#define CERT_NAME_RDN_TYPE 2
#define CERT_NAME_ATTR_TYPE 3
#define CERT_NAME_SIMPLE_DISPLAY_TYPE 4
#define CERT_NAME_FRIENDLY_DISPLAY_TYPE 5
#define CERT_NAME_DNS_TYPE 6
#define CERT_NAME_URL_TYPE 7
#define CERT_NAME_UPN_TYPE 8
#define CERT_NAME_ISSUER_FLAG 0x1
#define CERT_NAME_DISABLE_IE4_UTF8_FLAG 0x00010000
#define CERT_NAME_SEARCH_ALL_NAMES_FLAG 0x2
#define CERT_STORE_PROV_MSG ((LPCSTR)1)
#define CERT_STORE_PROV_MEMORY ((LPCSTR)2)
#define CERT_STORE_PROV_FILE ((LPCSTR)3)
#define CERT_STORE_PROV_REG ((LPCSTR)4)
#define CERT_STORE_PROV_PKCS7 ((LPCSTR)5)
#define CERT_STORE_PROV_SERIALIZED ((LPCSTR)6)
#define CERT_STORE_PROV_FILENAME_A ((LPCSTR)7)
#define CERT_STORE_PROV_FILENAME_W ((LPCSTR)8)
#define CERT_STORE_PROV_FILENAME CERT_STORE_PROV_FILENAME_W
#define CERT_STORE_PROV_SYSTEM_A ((LPCSTR)9)
#define CERT_STORE_PROV_SYSTEM_W ((LPCSTR)10)
#define CERT_STORE_PROV_SYSTEM CERT_STORE_PROV_SYSTEM_W
#define CERT_STORE_PROV_COLLECTION ((LPCSTR)11)
#define CERT_STORE_PROV_SYSTEM_REGISTRY_A ((LPCSTR)12)
#define CERT_STORE_PROV_SYSTEM_REGISTRY_W ((LPCSTR)13)
#define CERT_STORE_PROV_SYSTEM_REGISTRY CERT_STORE_PROV_SYSTEM_REGISTRY_W
#define CERT_STORE_PROV_PHYSICAL_W ((LPCSTR)14)
#define CERT_STORE_PROV_PHYSICAL CERT_STORE_PROV_PHYSICAL_W
#define CERT_STORE_PROV_SMART_CARD_W ((LPCSTR)15)
#define CERT_STORE_PROV_SMART_CARD CERT_STORE_PROV_SMART_CARD_W
#define CERT_STORE_PROV_LDAP_W ((LPCSTR)16)
#define CERT_STORE_PROV_LDAP CERT_STORE_PROV_LDAP_W
#define CERT_STORE_PROV_PKCS12 ((LPCSTR)17)
#define sz_CERT_STORE_PROV_MEMORY "Memory"
#define sz_CERT_STORE_PROV_FILENAME_W "File"
#define sz_CERT_STORE_PROV_FILENAME sz_CERT_STORE_PROV_FILENAME_W
#define sz_CERT_STORE_PROV_SYSTEM_W "System"
#define sz_CERT_STORE_PROV_SYSTEM sz_CERT_STORE_PROV_SYSTEM_W
#define sz_CERT_STORE_PROV_PKCS7 "PKCS7"
#define sz_CERT_STORE_PROV_PKCS12 "PKCS12"
#define sz_CERT_STORE_PROV_SERIALIZED "Serialized"
#define sz_CERT_STORE_PROV_COLLECTION "Collection"
#define sz_CERT_STORE_PROV_SYSTEM_REGISTRY_W "SystemRegistry"
#define sz_CERT_STORE_PROV_SYSTEM_REGISTRY sz_CERT_STORE_PROV_SYSTEM_REGISTRY_W
#define sz_CERT_STORE_PROV_PHYSICAL_W "Physical"
#define sz_CERT_STORE_PROV_PHYSICAL sz_CERT_STORE_PROV_PHYSICAL_W
#define sz_CERT_STORE_PROV_SMART_CARD_W "SmartCard"
#define sz_CERT_STORE_PROV_SMART_CARD sz_CERT_STORE_PROV_SMART_CARD_W
#define sz_CERT_STORE_PROV_LDAP_W "Ldap"
#define sz_CERT_STORE_PROV_LDAP sz_CERT_STORE_PROV_LDAP_W
#define CERT_STORE_SIGNATURE_FLAG 0x00000001
#define CERT_STORE_TIME_VALIDITY_FLAG 0x00000002
#define CERT_STORE_REVOCATION_FLAG 0x00000004
#define CERT_STORE_NO_CRL_FLAG 0x00010000
#define CERT_STORE_NO_ISSUER_FLAG 0x00020000
#define CERT_STORE_BASE_CRL_FLAG 0x00000100
#define CERT_STORE_DELTA_CRL_FLAG 0x00000200
#define CERT_STORE_NO_CRYPT_RELEASE_FLAG 0x00000001
#define CERT_STORE_SET_LOCALIZED_NAME_FLAG 0x00000002
#define CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG 0x00000004
#define CERT_STORE_DELETE_FLAG 0x00000010
#define CERT_STORE_UNSAFE_PHYSICAL_FLAG 0x00000020
#define CERT_STORE_SHARE_STORE_FLAG 0x00000040
#define CERT_STORE_SHARE_CONTEXT_FLAG 0x00000080
#define CERT_STORE_MANIFOLD_FLAG 0x00000100
#define CERT_STORE_ENUM_ARCHIVED_FLAG 0x00000200
#define CERT_STORE_UPDATE_KEYID_FLAG 0x00000400
#define CERT_STORE_BACKUP_RESTORE_FLAG 0x00000800
#define CERT_STORE_READONLY_FLAG 0x00008000
#define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
#define CERT_STORE_CREATE_NEW_FLAG 0x00002000
#define CERT_STORE_MAXIMUM_ALLOWED_FLAG 0x00001000
#define CERT_SYSTEM_STORE_MASK 0xFFFF0000
#define CERT_SYSTEM_STORE_RELOCATE_FLAG 0x80000000
#define CERT_SYSTEM_STORE_UNPROTECTED_FLAG 0x40000000
#define CERT_SYSTEM_STORE_DEFER_READ_FLAG 0x20000000
#define CERT_SYSTEM_STORE_LOCATION_MASK 0x00FF0000
#define CERT_SYSTEM_STORE_LOCATION_SHIFT 16
#define CERT_SYSTEM_STORE_CURRENT_USER_ID 1
#define CERT_SYSTEM_STORE_LOCAL_MACHINE_ID 2
#define CERT_SYSTEM_STORE_CURRENT_SERVICE_ID 4
#define CERT_SYSTEM_STORE_SERVICES_ID 5
#define CERT_SYSTEM_STORE_USERS_ID 6
#define CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY_ID 7
#define CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY_ID 8
#define CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE_ID 9
#define CERT_SYSTEM_STORE_CURRENT_USER \
(CERT_SYSTEM_STORE_CURRENT_USER_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT)
#define CERT_SYSTEM_STORE_LOCAL_MACHINE \
(CERT_SYSTEM_STORE_LOCAL_MACHINE_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT)
#define CERT_SYSTEM_STORE_CURRENT_SERVICE \
(CERT_SYSTEM_STORE_CURRENT_SERVICE_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT)
#define CERT_SYSTEM_STORE_SERVICES \
(CERT_SYSTEM_STORE_SERVICES_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT)
#define CERT_SYSTEM_STORE_USERS (CERT_SYSTEM_STORE_USERS_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT)
#define CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY \
(CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT)
#define CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY \
(CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT)
#define CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE \
(CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT)
WINPR_API HCERTSTORE CertOpenStore(LPCSTR lpszStoreProvider, DWORD dwMsgAndCertEncodingType,
HCRYPTPROV_LEGACY hCryptProv, DWORD dwFlags, const void* pvPara);
WINPR_API HCERTSTORE CertOpenSystemStoreW(HCRYPTPROV_LEGACY hProv, LPCWSTR szSubsystemProtocol);
WINPR_API HCERTSTORE CertOpenSystemStoreA(HCRYPTPROV_LEGACY hProv, LPCSTR szSubsystemProtocol);
WINPR_API BOOL CertCloseStore(HCERTSTORE hCertStore, DWORD dwFlags);
#ifdef UNICODE
#define CertOpenSystemStore CertOpenSystemStoreW
#else
#define CertOpenSystemStore CertOpenSystemStoreA
#endif
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API PCCERT_CONTEXT CertFindCertificateInStore(HCERTSTORE hCertStore,
DWORD dwCertEncodingType, DWORD dwFindFlags,
DWORD dwFindType, const void* pvFindPara,
PCCERT_CONTEXT pPrevCertContext);
WINPR_API PCCERT_CONTEXT CertEnumCertificatesInStore(HCERTSTORE hCertStore,
PCCERT_CONTEXT pPrevCertContext);
WINPR_API DWORD CertGetNameStringW(PCCERT_CONTEXT pCertContext, DWORD dwType, DWORD dwFlags,
void* pvTypePara, LPWSTR pszNameString, DWORD cchNameString);
WINPR_API DWORD CertGetNameStringA(PCCERT_CONTEXT pCertContext, DWORD dwType, DWORD dwFlags,
void* pvTypePara, LPSTR pszNameString, DWORD cchNameString);
#ifdef __cplusplus
}
#endif
#ifdef UNICODE
#define CertGetNameString CertGetNameStringW
#else
#define CertGetNameString CertGetNameStringA
#endif
/**
* Data Protection API (DPAPI)
*/
#define CRYPTPROTECTMEMORY_BLOCK_SIZE 16
#define CRYPTPROTECTMEMORY_SAME_PROCESS 0x00000000
#define CRYPTPROTECTMEMORY_CROSS_PROCESS 0x00000001
#define CRYPTPROTECTMEMORY_SAME_LOGON 0x00000002
#define CRYPTPROTECT_PROMPT_ON_UNPROTECT 0x00000001
#define CRYPTPROTECT_PROMPT_ON_PROTECT 0x00000002
#define CRYPTPROTECT_PROMPT_RESERVED 0x00000004
#define CRYPTPROTECT_PROMPT_STRONG 0x00000008
#define CRYPTPROTECT_PROMPT_REQUIRE_STRONG 0x00000010
#define CRYPTPROTECT_UI_FORBIDDEN 0x1
#define CRYPTPROTECT_LOCAL_MACHINE 0x4
#define CRYPTPROTECT_CRED_SYNC 0x8
#define CRYPTPROTECT_AUDIT 0x10
#define CRYPTPROTECT_NO_RECOVERY 0x20
#define CRYPTPROTECT_VERIFY_PROTECTION 0x40
#define CRYPTPROTECT_CRED_REGENERATE 0x80
#define CRYPTPROTECT_FIRST_RESERVED_FLAGVAL 0x0FFFFFFF
#define CRYPTPROTECT_LAST_RESERVED_FLAGVAL 0xFFFFFFFF
typedef struct
{
DWORD cbSize;
DWORD dwPromptFlags;
HWND hwndApp;
LPCWSTR szPrompt;
} CRYPTPROTECT_PROMPTSTRUCT, *PCRYPTPROTECT_PROMPTSTRUCT;
#define CRYPTPROTECT_DEFAULT_PROVIDER \
{ \
0xdf9d8cd0, 0x1501, 0x11d1, \
{ \
0x8c, 0x7a, 0x00, 0xc0, 0x4f, 0xc2, 0x97, 0xeb \
} \
}
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API BOOL CryptProtectMemory(LPVOID pData, DWORD cbData, DWORD dwFlags);
WINPR_API BOOL CryptUnprotectMemory(LPVOID pData, DWORD cbData, DWORD dwFlags);
WINPR_API BOOL CryptProtectData(DATA_BLOB* pDataIn, LPCWSTR szDataDescr,
DATA_BLOB* pOptionalEntropy, PVOID pvReserved,
CRYPTPROTECT_PROMPTSTRUCT* pPromptStruct, DWORD dwFlags,
DATA_BLOB* pDataOut);
WINPR_API BOOL CryptUnprotectData(DATA_BLOB* pDataIn, LPWSTR* ppszDataDescr,
DATA_BLOB* pOptionalEntropy, PVOID pvReserved,
CRYPTPROTECT_PROMPTSTRUCT* pPromptStruct, DWORD dwFlags,
DATA_BLOB* pDataOut);
#ifdef __cplusplus
}
#endif
#define CRYPT_STRING_BASE64HEADER 0x00000000
#define CRYPT_STRING_BASE64 0x00000001
#define CRYPT_STRING_BINARY 0x00000002
#define CRYPT_STRING_BASE64REQUESTHEADER 0x00000003
#define CRYPT_STRING_HEX 0x00000004
#define CRYPT_STRING_HEXASCII 0x00000005
#define CRYPT_STRING_BASE64_ANY 0x00000006
#define CRYPT_STRING_ANY 0x00000007
#define CRYPT_STRING_HEX_ANY 0x00000008
#define CRYPT_STRING_BASE64X509CRLHEADER 0x00000009
#define CRYPT_STRING_HEXADDR 0x0000000A
#define CRYPT_STRING_HEXASCIIADDR 0x0000000B
#define CRYPT_STRING_HEXRAW 0x0000000C
#define CRYPT_STRING_HASHDATA 0x10000000
#define CRYPT_STRING_STRICT 0x20000000
#define CRYPT_STRING_NOCRLF 0x40000000
#define CRYPT_STRING_NOCR 0x80000000
WINPR_API BOOL CryptStringToBinaryW(LPCWSTR pszString, DWORD cchString, DWORD dwFlags,
BYTE* pbBinary, DWORD* pcbBinary, DWORD* pdwSkip,
DWORD* pdwFlags);
WINPR_API BOOL CryptStringToBinaryA(LPCSTR pszString, DWORD cchString, DWORD dwFlags,
BYTE* pbBinary, DWORD* pcbBinary, DWORD* pdwSkip,
DWORD* pdwFlags);
WINPR_API BOOL CryptBinaryToStringW(CONST BYTE* pbBinary, DWORD cbBinary, DWORD dwFlags,
LPWSTR pszString, DWORD* pcchString);
WINPR_API BOOL CryptBinaryToStringA(CONST BYTE* pbBinary, DWORD cbBinary, DWORD dwFlags,
LPSTR pszString, DWORD* pcchString);
#ifdef UNICODE
#define CryptStringToBinary CryptStringToBinaryW
#define CryptBinaryToString CryptBinaryToStringW
#else
#define CryptStringToBinary CryptStringToBinaryA
#define CryptBinaryToString CryptBinaryToStringA
#endif
#endif
#ifndef ALG_SID_ECDSA
#define ALG_SID_ECDSA 3
#define CALG_ECDSA (ALG_CLASS_SIGNATURE | ALG_TYPE_DSS | ALG_SID_ECDSA)
#endif
#endif /* WINPR_WINCRYPT_H */

View File

@@ -0,0 +1,130 @@
/**
* WinPR: Windows Portable Runtime
* Windows Header Include Wrapper
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_WINDOWS_H
#define WINPR_WINDOWS_H
/* Windows header include order is important, use this instead of including windows.h directly */
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#else
/* Client System Parameters Update PDU
* defined in winuser.h
*/
typedef enum
{
SPI_SETDRAGFULLWINDOWS = 0x00000025,
SPI_SETKEYBOARDCUES = 0x0000100B,
SPI_SETKEYBOARDPREF = 0x00000045,
SPI_SETWORKAREA = 0x0000002f,
RAIL_SPI_DISPLAYCHANGE = 0x0000F001,
SPI_SETMOUSEBUTTONSWAP = 0x00000021,
RAIL_SPI_TASKBARPOS = 0x0000F000,
SPI_SETHIGHCONTRAST = 0x00000043,
SPI_SETCARETWIDTH = 0x00002007,
SPI_SETSTICKYKEYS = 0x0000003B,
SPI_SETTOGGLEKEYS = 0x00000035,
SPI_SETFILTERKEYS = 0x00000033,
RAIL_SPI_DISPLAY_ANIMATIONS_ENABLED = 0x0000F002,
RAIL_SPI_DISPLAY_ADVANCED_EFFECTS_ENABLED = 0x0000F003,
RAIL_SPI_DISPLAY_AUTO_HIDE_SCROLLBARS = 0x0000F004,
RAIL_SPI_DISPLAY_MESSAGE_DURATION = 0x0000F005,
RAIL_SPI_CLOSED_CAPTION_FONT_COLOR = 0x0000F006,
RAIL_SPI_CLOSED_CAPTION_FONT_OPACITY = 0x0000F007,
RAIL_SPI_CLOSED_CAPTION_FONT_SIZE = 0x0000F008,
RAIL_SPI_CLOSED_CAPTION_FONT_STYLE = 0x0000F009,
RAIL_SPI_CLOSED_CAPTION_FONT_EDGE_EFFECT = 0x0000F00A,
RAIL_SPI_CLOSED_CAPTION_BACKGROUND_COLOR = 0x0000F00B,
RAIL_SPI_CLOSED_CAPTION_BACKGROUND_OPACITY = 0x0000F00C,
RAIL_SPI_CLOSED_CAPTION_REGION_COLOR = 0x0000F00D,
RAIL_SPI_CLOSED_CAPTION_REGION_OPACITY = 0x0000F00E
} SystemParam;
/* Server System Parameters Update PDU */
#define SPI_SETSCREENSAVEACTIVE 0x00000011
/* HIGHCONTRAST flags values */
#define HCF_HIGHCONTRASTON 0x00000001
#define HCF_AVAILABLE 0x00000002
#define HCF_HOTKEYACTIVE 0x00000004
#define HCF_CONFIRMHOTKEY 0x00000008
#define HCF_HOTKEYSOUND 0x00000010
#define HCF_INDICATOR 0x00000020
#define HCF_HOTKEYAVAILABLE 0x00000040
/* TS_FILTERKEYS */
#define FKF_FILTERKEYSON 0x00000001
#define FKF_AVAILABLE 0x00000002
#define FKF_HOTKEYACTIVE 0x00000004
#define FKF_CONFIRMHOTKEY 0x00000008
#define FKF_HOTKEYSOUND 0x00000010
#define FKF_INDICATOR 0x00000020
#define FKF_CLICKON 0x00000040
/* TS_TOGGLEKEYS */
#define TKF_TOGGLEKEYSON 0x00000001
#define TKF_AVAILABLE 0x00000002
#define TKF_HOTKEYACTIVE 0x00000004
#define TKF_CONFIRMHOTKEY 0x00000008
#define TKF_HOTKEYSOUND 0x00000010
/* TS_STICKYKEYS */
#define SKF_STICKYKEYSON 0x00000001
#define SKF_AVAILABLE 0x00000002
#define SKF_HOTKEYACTIVE 0x00000004
#define SKF_CONFIRMHOTKEY 0x00000008
#define SKF_HOTKEYSOUND 0x00000010
#define SKF_INDICATOR 0x00000020
#define SKF_AUDIBLEFEEDBACK 0x00000040
#define SKF_TRISTATE 0x00000080
#define SKF_TWOKEYSOFF 0x00000100
#define SKF_LSHIFTLOCKED 0x00010000
#define SKF_RSHIFTLOCKED 0x00020000
#define SKF_LCTLLOCKED 0x00040000
#define SKF_RCTLLOCKED 0x00080000
#define SKF_LALTLOCKED 0x00100000
#define SKF_RALTLOCKED 0x00200000
#define SKF_LWINLOCKED 0x00400000
#define SKF_RWINLOCKED 0x00800000
#define SKF_LSHIFTLATCHED 0x01000000
#define SKF_RSHIFTLATCHED 0x02000000
#define SKF_LCTLLATCHED 0x04000000
#define SKF_RCTLLATCHED 0x08000000
#define SKF_LALTLATCHED 0x10000000
#define SKF_RALTLATCHED 0x20000000
#define SKF_LWINLATCHED 0x40000000
#define SKF_RWINLATCHED 0x80000000
#endif
#ifndef SPI_SETSCREENSAVESECURE
#define SPI_SETSCREENSAVESECURE 0x00000077
#endif
#endif /* WINPR_WINDOWS_H */

View File

@@ -0,0 +1,87 @@
/**
* WinPR: Windows Portable Runtime
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_H
#define WINPR_H
#include <winpr/platform.h>
#include <winpr/cast.h>
#include <winpr/wtypes.h>
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API void winpr_get_version(int* major, int* minor, int* revision);
WINPR_API const char* winpr_get_version_string(void);
WINPR_API const char* winpr_get_build_revision(void);
WINPR_API const char* winpr_get_build_config(void);
/** @brief set \b vendor and \b product information for an application
*
* This sets the application details for an application instance. These values determine where
* to look for configuration files and other vendor/product specific settings data.
*
* @note When calling this function, the compile time options \b WINPR_USE_VENDOR_PRODUCT_CONFIG_DIR
* is ignored and the config path will always have the format 'vendor/product' or 'vendor/product1'
* (1 for the actual version set)
*
* @param vendor A vendor name to use. Must not be \b nullptr. Must not contain forbidden
* filesystem symbols for any os. Must be less than \b MAX_PATH bytes.
* @param product A product name to use. Must not be \b nullptr. Must not contain forbidden
* filesystem symbols for any os. Must be less than \b MAX_PATH bytes.
* @param version An optional versioning value to append to paths to settings. Use \b -1 to
* disable.
*
* @return \b TRUE if set successfully, \b FALSE in case of any error.
* @since version 3.23.0
*/
WINPR_API WINPR_ATTR_NODISCARD BOOL winpr_setApplicationDetails(const char* vendor,
const char* product,
SSIZE_T version);
/** @brief Get the current \b vendor string of the application. Defaults to \ref
* WINPR_VENDOR_STRING
*
* @return The current string set as \b vendor.
* @since version 3.23.0
*/
WINPR_API WINPR_ATTR_NODISCARD const char* winpr_getApplicationDetailsVendor(void);
/** @brief Get the current \b product string of the application. Defaults to \ref
* WINPR_PRODUCT_STRING
*
* @return The current string set as \b product.
* @since version 3.23.0
*/
WINPR_API WINPR_ATTR_NODISCARD const char* winpr_getApplicationDetailsProduct(void);
/** @brief Get the current \b version of the application. Defaults to \ref WINPR_API_VERSION
* if \b WITH_RESOURCE_VERSIONING is defined, otherwise \b -1
*
* @return The current number set as \b version
* @since version 3.23.0
*/
WINPR_API WINPR_ATTR_NODISCARD SSIZE_T winpr_getApplicationDetailsVersion(void);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_H */

View File

@@ -0,0 +1,381 @@
/**
* WinPR: Windows Portable Runtime
* Windows Sockets (Winsock)
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_WINSOCK_H
#define WINPR_WINSOCK_H
#include <winpr/platform.h>
#include <winpr/winpr.h>
#include <winpr/wtypes.h>
#include <winpr/windows.h>
WINPR_PRAGMA_DIAG_PUSH
WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER
#ifdef _WIN32
#define _accept accept
#define _bind bind
#define _connect connect
#define _ioctlsocket ioctlsocket
#define _getpeername getpeername
#define _getsockname getsockname
#define _getsockopt getsockopt
#define _htonl htonl
#define _htons htons
#define _inet_addr inet_addr
#define _inet_ntoa inet_ntoa
#define _listen listen
#define _ntohl ntohl
#define _ntohs ntohs
#define _recv recv
#define _recvfrom recvfrom
#define _select select
#define _send send
#define _sendto sendto
#define _setsockopt setsockopt
#define _shutdown shutdown
#define _socket socket
#define _gethostbyaddr gethostbyaddr
#define _gethostbyname gethostbyname
#define _gethostname gethostname
#define _getservbyport getservbyport
#define _getservbyname getservbyname
#define _getprotobynumber getprotobynumber
#define _getprotobyname getprotobyname
#define _IFF_UP IFF_UP
#define _IFF_BROADCAST IFF_BROADCAST
#define _IFF_LOOPBACK IFF_LOOPBACK
#define _IFF_POINTTOPOINT IFF_POINTTOPOINT
#define _IFF_MULTICAST IFF_MULTICAST
#if (_WIN32_WINNT < 0x0600)
WINPR_API PCSTR winpr_inet_ntop(INT Family, PVOID pAddr, PSTR pStringBuf, size_t StringBufSize);
WINPR_API INT winpr_inet_pton(INT Family, PCSTR pszAddrString, PVOID pAddrBuf);
#define inet_ntop winpr_inet_ntop
#define inet_pton winpr_inet_pton
#endif /* (_WIN32_WINNT < 0x0600) */
#else /* _WIN32 */
#include <netdb.h>
#include <unistd.h>
#include <sys/un.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <net/if.h>
#include <winpr/io.h>
#include <winpr/error.h>
#define WSAEVENT HANDLE
#define LPWSAEVENT LPHANDLE
#define WSAOVERLAPPED OVERLAPPED
typedef OVERLAPPED* LPWSAOVERLAPPED;
typedef UINT_PTR SOCKET;
typedef struct sockaddr_storage SOCKADDR_STORAGE;
#ifndef INVALID_SOCKET
#define INVALID_SOCKET (SOCKET)(~0)
#endif
#define WSADESCRIPTION_LEN 256
#define WSASYS_STATUS_LEN 128
#define FD_READ_BIT 0
#define FD_READ (1 << FD_READ_BIT)
#define FD_WRITE_BIT 1
#define FD_WRITE (1 << FD_WRITE_BIT)
#define FD_OOB_BIT 2
#define FD_OOB (1 << FD_OOB_BIT)
#define FD_ACCEPT_BIT 3
#define FD_ACCEPT (1 << FD_ACCEPT_BIT)
#define FD_CONNECT_BIT 4
#define FD_CONNECT (1 << FD_CONNECT_BIT)
#define FD_CLOSE_BIT 5
#define FD_CLOSE (1 << FD_CLOSE_BIT)
#define FD_QOS_BIT 6
#define FD_QOS (1 << FD_QOS_BIT)
#define FD_GROUP_QOS_BIT 7
#define FD_GROUP_QOS (1 << FD_GROUP_QOS_BIT)
#define FD_ROUTING_INTERFACE_CHANGE_BIT 8
#define FD_ROUTING_INTERFACE_CHANGE (1 << FD_ROUTING_INTERFACE_CHANGE_BIT)
#define FD_ADDRESS_LIST_CHANGE_BIT 9
#define FD_ADDRESS_LIST_CHANGE (1 << FD_ADDRESS_LIST_CHANGE_BIT)
#define FD_MAX_EVENTS 10
#define FD_ALL_EVENTS ((1 << FD_MAX_EVENTS) - 1)
#define SD_RECEIVE 0
#define SD_SEND 1
#define SD_BOTH 2
#define SOCKET_ERROR (-1)
typedef struct WSAData
{
WORD wVersion;
WORD wHighVersion;
#ifdef _M_AMD64
unsigned short iMaxSockets;
unsigned short iMaxUdpDg;
char* lpVendorInfo;
char szDescription[WSADESCRIPTION_LEN + 1];
char szSystemStatus[WSASYS_STATUS_LEN + 1];
#else
char szDescription[WSADESCRIPTION_LEN + 1];
char szSystemStatus[WSASYS_STATUS_LEN + 1];
unsigned short iMaxSockets;
unsigned short iMaxUdpDg;
char* lpVendorInfo;
#endif
} WSADATA, *LPWSADATA;
#ifndef MAKEWORD
#define MAKEWORD(a, b) \
((WORD)(((BYTE)((DWORD_PTR)(a)&0xFF)) | (((WORD)((BYTE)((DWORD_PTR)(b)&0xFF))) << 8)))
#endif
typedef struct in6_addr IN6_ADDR;
typedef struct in6_addr* PIN6_ADDR;
typedef struct in6_addr* LPIN6_ADDR;
struct sockaddr_in6_old
{
SHORT sin6_family;
USHORT sin6_port;
ULONG sin6_flowinfo;
IN6_ADDR sin6_addr;
};
typedef union sockaddr_gen
{
struct sockaddr Address;
struct sockaddr_in AddressIn; /* codespell:ignore addressin */
struct sockaddr_in6_old AddressIn6;
} sockaddr_gen;
WINPR_PRAGMA_DIAG_PUSH
WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO
// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _IFF_UP 0x00000001
#define _IFF_BROADCAST 0x00000002
#define _IFF_LOOPBACK 0x00000004
#define _IFF_POINTTOPOINT 0x00000008
#define _IFF_MULTICAST 0x00000010
// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
WINPR_PRAGMA_DIAG_POP
typedef struct
{
ULONG iiFlags;
sockaddr_gen iiAddress;
sockaddr_gen iiBroadcastAddress;
sockaddr_gen iiNetmask;
} INTERFACE_INFO;
typedef INTERFACE_INFO* LPINTERFACE_INFO;
#define MAX_PROTOCOL_CHAIN 7
#define WSAPROTOCOL_LEN 255
typedef struct
{
int ChainLen;
DWORD ChainEntries[MAX_PROTOCOL_CHAIN];
} WSAPROTOCOLCHAIN, *LPWSAPROTOCOLCHAIN;
typedef struct
{
DWORD dwServiceFlags1;
DWORD dwServiceFlags2;
DWORD dwServiceFlags3;
DWORD dwServiceFlags4;
DWORD dwProviderFlags;
GUID ProviderId;
DWORD dwCatalogEntryId;
WSAPROTOCOLCHAIN ProtocolChain;
int iVersion;
int iAddressFamily;
int iMaxSockAddr;
int iMinSockAddr;
int iSocketType;
int iProtocol;
int iProtocolMaxOffset;
int iNetworkByteOrder;
int iSecurityScheme;
DWORD dwMessageSize;
DWORD dwProviderReserved;
CHAR szProtocol[WSAPROTOCOL_LEN + 1];
} WSAPROTOCOL_INFOA, *LPWSAPROTOCOL_INFOA;
typedef struct
{
DWORD dwServiceFlags1;
DWORD dwServiceFlags2;
DWORD dwServiceFlags3;
DWORD dwServiceFlags4;
DWORD dwProviderFlags;
GUID ProviderId;
DWORD dwCatalogEntryId;
WSAPROTOCOLCHAIN ProtocolChain;
int iVersion;
int iAddressFamily;
int iMaxSockAddr;
int iMinSockAddr;
int iSocketType;
int iProtocol;
int iProtocolMaxOffset;
int iNetworkByteOrder;
int iSecurityScheme;
DWORD dwMessageSize;
DWORD dwProviderReserved;
WCHAR szProtocol[WSAPROTOCOL_LEN + 1];
} WSAPROTOCOL_INFOW, *LPWSAPROTOCOL_INFOW;
typedef void(CALLBACK* LPWSAOVERLAPPED_COMPLETION_ROUTINE)(DWORD dwError, DWORD cbTransferred,
LPWSAOVERLAPPED lpOverlapped,
DWORD dwFlags);
typedef UINT32 GROUP;
#define SG_UNCONSTRAINED_GROUP 0x01
#define SG_CONSTRAINED_GROUP 0x02
#define SIO_GET_INTERFACE_LIST _IOR('t', 127, ULONG)
#define SIO_GET_INTERFACE_LIST_EX _IOR('t', 126, ULONG)
#define SIO_SET_MULTICAST_FILTER _IOW('t', 125, ULONG)
#define SIO_GET_MULTICAST_FILTER _IOW('t', 124 | IOC_IN, ULONG)
#define SIOCSIPMSFILTER SIO_SET_MULTICAST_FILTER
#define SIOCGIPMSFILTER SIO_GET_MULTICAST_FILTER
#ifdef UNICODE
#define WSAPROTOCOL_INFO WSAPROTOCOL_INFOW
#define LPWSAPROTOCOL_INFO LPWSAPROTOCOL_INFOW
#else
#define WSAPROTOCOL_INFO WSAPROTOCOL_INFOA
#define LPWSAPROTOCOL_INFO LPWSAPROTOCOL_INFOA
#endif
#ifdef __cplusplus
extern "C"
{
#endif
WINPR_API int WSAStartup(WORD wVersionRequired, LPWSADATA lpWSAData);
WINPR_API int WSACleanup(void);
WINPR_API void WSASetLastError(int iError);
WINPR_API int WSAGetLastError(void);
WINPR_API BOOL WSACloseEvent(HANDLE hEvent);
WINPR_ATTR_MALLOC(WSACloseEvent, 1)
WINPR_ATTR_NODISCARD
WINPR_API HANDLE WSACreateEvent(void);
WINPR_API BOOL WSASetEvent(HANDLE hEvent);
WINPR_API BOOL WSAResetEvent(HANDLE hEvent);
WINPR_API int WSAEventSelect(SOCKET s, WSAEVENT hEventObject, LONG lNetworkEvents);
WINPR_API DWORD WSAWaitForMultipleEvents(DWORD cEvents, const HANDLE* lphEvents, BOOL fWaitAll,
DWORD dwTimeout, BOOL fAlertable);
WINPR_API SOCKET WSASocketA(int af, int type, int protocol, LPWSAPROTOCOL_INFOA lpProtocolInfo,
GROUP g, DWORD dwFlags);
WINPR_API SOCKET WSASocketW(int af, int type, int protocol, LPWSAPROTOCOL_INFOW lpProtocolInfo,
GROUP g, DWORD dwFlags);
WINPR_API int WSAIoctl(SOCKET s, DWORD dwIoControlCode, LPVOID lpvInBuffer, DWORD cbInBuffer,
LPVOID lpvOutBuffer, DWORD cbOutBuffer, LPDWORD lpcbBytesReturned,
LPWSAOVERLAPPED lpOverlapped,
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);
// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
WINPR_API SOCKET _accept(SOCKET s, struct sockaddr* addr, int* addrlen);
WINPR_API int _bind(SOCKET s, const struct sockaddr* addr, int namelen);
WINPR_API int closesocket(SOCKET s);
WINPR_API int _connect(SOCKET s, const struct sockaddr* name, int namelen);
WINPR_API int _ioctlsocket(SOCKET s, long cmd, u_long* argp);
WINPR_API int _getpeername(SOCKET s, struct sockaddr* name, int* namelen);
WINPR_API int _getsockname(SOCKET s, struct sockaddr* name, int* namelen);
WINPR_API int _getsockopt(SOCKET s, int level, int optname, char* optval, int* optlen);
WINPR_API u_long _htonl(u_long hostlong);
WINPR_API u_short _htons(u_short hostshort);
WINPR_API unsigned long _inet_addr(const char* cp);
WINPR_API char* _inet_ntoa(struct in_addr in);
WINPR_API int _listen(SOCKET s, int backlog);
WINPR_API u_long _ntohl(u_long netlong);
WINPR_API u_short _ntohs(u_short netshort);
WINPR_API int _recv(SOCKET s, char* buf, int len, int flags);
WINPR_API int _recvfrom(SOCKET s, char* buf, int len, int flags, struct sockaddr* from,
int* fromlen);
WINPR_API int _select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds,
const struct timeval* timeout);
WINPR_API int _send(SOCKET s, const char* buf, int len, int flags);
WINPR_API int _sendto(SOCKET s, const char* buf, int len, int flags, const struct sockaddr* to,
int tolen);
WINPR_API int _setsockopt(SOCKET s, int level, int optname, const char* optval, int optlen);
WINPR_API int _shutdown(SOCKET s, int how);
WINPR_API SOCKET _socket(int af, int type, int protocol);
WINPR_API struct hostent* _gethostbyaddr(const char* addr, int len, int type);
WINPR_API struct hostent* _gethostbyname(const char* name);
WINPR_API int _gethostname(char* name, int namelen);
WINPR_API struct servent* /* codespell:ignore servent */ _getservbyport(int port,
const char* proto);
WINPR_API struct servent* /* codespell:ignore servent */ _getservbyname(const char* name,
const char* proto);
WINPR_API struct protoent* _getprotobynumber(int number);
WINPR_API struct protoent* _getprotobyname(const char* name);
// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#ifdef __cplusplus
}
#endif
#ifdef UNICODE
#define WSASocket WSASocketW
#else
#define WSASocket WSASocketA
#endif
#endif /* _WIN32 */
WINPR_PRAGMA_DIAG_POP
#endif /* WINPR_WINSOCK_H */

View File

@@ -0,0 +1,335 @@
/**
* WinPR: Windows Portable Runtime
* WinPR Logger
*
* Copyright 2013 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2015 Thincast Technologies GmbH
* Copyright 2015 Bernhard Miklautz <bernhard.miklautz@thincast.com>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_LOG_H
#define WINPR_LOG_H
#ifdef __cplusplus
extern "C"
{
#endif
#include <stdarg.h>
#include <winpr/platform.h>
#include <winpr/wtypes.h>
#include <winpr/winpr.h>
#include <winpr/synch.h>
#include <winpr/thread.h>
/**
* Log Levels
*/
#define WLOG_TRACE 0
#define WLOG_DEBUG 1
#define WLOG_INFO 2
#define WLOG_WARN 3
#define WLOG_ERROR 4
#define WLOG_FATAL 5
#define WLOG_OFF 6
#define WLOG_LEVEL_INHERIT 0xFFFF
/** @defgroup LogMessageTypes Log Message
* @{
*/
#define WLOG_MESSAGE_TEXT 0
#define WLOG_MESSAGE_DATA 1
#define WLOG_MESSAGE_IMAGE 2
#define WLOG_MESSAGE_PACKET 3
/**
* @}
*/
/**
* Log Appenders
*/
#define WLOG_APPENDER_CONSOLE 0
#define WLOG_APPENDER_FILE 1
#define WLOG_APPENDER_BINARY 2
#define WLOG_APPENDER_CALLBACK 3
#define WLOG_APPENDER_SYSLOG 4
#define WLOG_APPENDER_JOURNALD 5
#define WLOG_APPENDER_UDP 6
typedef struct
{
DWORD Type;
DWORD Level;
LPSTR PrefixString;
LPCSTR FormatString;
LPCSTR TextString;
size_t LineNumber; /* __LINE__ */
LPCSTR FileName; /* __FILE__ */
LPCSTR FunctionName; /* __func__ */
/* Data Message */
void* Data;
size_t Length;
/* Image Message */
void* ImageData;
size_t ImageWidth;
size_t ImageHeight;
size_t ImageBpp;
/* Packet Message */
void* PacketData;
size_t PacketLength;
DWORD PacketFlags;
} wLogMessage;
typedef struct s_wLogLayout wLogLayout;
typedef struct s_wLogAppender wLogAppender;
typedef struct s_wLog wLog;
#define WLOG_PACKET_INBOUND 1
#define WLOG_PACKET_OUTBOUND 2
/** @brief specialized function to print text log messages.
* Same as @ref WLog_PrintMessage with \b type = WLOG_MESSAGE_TEXT but with compile time checks
* for issues in format string.
*
* @param log A pointer to the logger to use
* @param line the file line the log message originates from
* @param file the file name the log message originates from
* @param function the function name the log message originates from
* @param fmt the printf style format string
*
* @return \b TRUE for success, \b FALSE otherwise.
* @since version 3.17.0
*/
WINPR_ATTR_FORMAT_ARG(6, 7)
WINPR_API BOOL WLog_PrintTextMessage(wLog* log, DWORD level, size_t line, const char* file,
const char* function, WINPR_FORMAT_ARG const char* fmt,
...);
/** @brief specialized function to print text log messages.
* Same as @ref WLog_PrintMessageVA with \b type = WLOG_MESSAGE_TEXT but with compile time
* checks for issues in format string.
*
* @param log A pointer to the logger to use
* @param line the file line the log message originates from
* @param file the file name the log message originates from
* @param function the function name the log message originates from
* @param fmt the printf style format string
*
* @return \b TRUE for success, \b FALSE otherwise.
* @since version 3.17.0
*/
WINPR_ATTR_FORMAT_ARG(6, 0)
WINPR_API BOOL WLog_PrintTextMessageVA(wLog* log, DWORD level, size_t line, const char* file,
const char* function, WINPR_FORMAT_ARG const char* fmt,
va_list args);
/** @brief log something of a specified type.
* @bug For /b WLOG_MESSAGE_TEXT the format string is not validated at compile time. Use \ref
* WLog_PrintTextMessage instead.
*
* @param log A pointer to the logger to use
* @param type The type of message to log, can be any of \ref LogMessageTypes
* @param line the file line the log message originates from
* @param file the file name the log message originates from
* @param function the function name the log message originates from
*
* @return \b TRUE for success, \b FALSE otherwise.
*/
WINPR_API BOOL WLog_PrintMessage(wLog* log, DWORD type, DWORD level, size_t line,
const char* file, const char* function, ...);
/** @brief log something of a specified type.
* @bug For /b WLOG_MESSAGE_TEXT the format string is not validated at compile time. Use \ref
* WLog_PrintTextMessageVA instead.
*
* @param log A pointer to the logger to use
* @param type The type of message to log, can be any of \ref LogMessageTypes
* @param line the file line the log message originates from
* @param file the file name the log message originates from
* @param function the function name the log message originates from
*
* @return \b TRUE for success, \b FALSE otherwise.
*/
WINPR_API BOOL WLog_PrintMessageVA(wLog* log, DWORD type, DWORD level, size_t line,
const char* file, const char* function, va_list args);
WINPR_API wLog* WLog_GetRoot(void);
WINPR_API wLog* WLog_Get(LPCSTR name);
WINPR_API DWORD WLog_GetLogLevel(wLog* log);
WINPR_API BOOL WLog_IsLevelActive(wLog* _log, DWORD _log_level);
/** @brief Set a custom context for a dynamic logger.
* This can be used to print a customized prefix, e.g. some session id for a specific context
*
* @param log The logger to ste the context for. Must not be \b nullptr
* @param fkt A function pointer that is called to get the custimized string.
* @param context A context \b fkt is called with. Caller must ensure it is still allocated
* when \b log is used
*
* @return \b TRUE for success, \b FALSE otherwise.
*/
WINPR_API BOOL WLog_SetContext(wLog* log, const char* (*fkt)(void*), void* context);
#define WLog_Print_unchecked(_log, _log_level, ...) \
do \
{ \
WLog_PrintTextMessage(_log, _log_level, __LINE__, __FILE__, __func__, __VA_ARGS__); \
} while (0)
#define WLog_Print(_log, _log_level, ...) \
do \
{ \
if (WLog_IsLevelActive(_log, _log_level)) \
{ \
WLog_Print_unchecked(_log, _log_level, __VA_ARGS__); \
} \
} while (0)
#define WLog_Print_tag(_tag, _log_level, ...) \
do \
{ \
static wLog* _log_cached_ptr = nullptr; \
if (!_log_cached_ptr) \
_log_cached_ptr = WLog_Get(_tag); \
WLog_Print(_log_cached_ptr, _log_level, __VA_ARGS__); \
} while (0)
#define WLog_PrintVA_unchecked(_log, _log_level, _args) \
do \
{ \
WLog_PrintTextMessageVA(_log, _log_level, __LINE__, __FILE__, __func__, _args); \
} while (0)
#define WLog_PrintVA(_log, _log_level, _args) \
do \
{ \
if (WLog_IsLevelActive(_log, _log_level)) \
{ \
WLog_PrintVA_unchecked(_log, _log_level, _args); \
} \
} while (0)
#define WLog_Data(_log, _log_level, ...) \
do \
{ \
if (WLog_IsLevelActive(_log, _log_level)) \
{ \
WLog_PrintMessage(_log, WLOG_MESSAGE_DATA, _log_level, __LINE__, __FILE__, __func__, \
__VA_ARGS__); \
} \
} while (0)
#define WLog_Image(_log, _log_level, ...) \
do \
{ \
if (WLog_IsLevelActive(_log, _log_level)) \
{ \
WLog_PrintMessage(_log, WLOG_MESSAGE_DATA, _log_level, __LINE__, __FILE__, __func__, \
__VA_ARGS__); \
} \
} while (0)
#define WLog_Packet(_log, _log_level, ...) \
do \
{ \
if (WLog_IsLevelActive(_log, _log_level)) \
{ \
WLog_PrintMessage(_log, WLOG_MESSAGE_PACKET, _log_level, __LINE__, __FILE__, __func__, \
__VA_ARGS__); \
} \
} while (0)
WINPR_ATTR_FORMAT_ARG(6, 7)
static inline void WLog_Print_dbg_tag(const char* WINPR_RESTRICT tag, DWORD log_level,
size_t line, const char* file, const char* fkt,
WINPR_FORMAT_ARG const char* fmt, ...)
{
static wLog* log_cached_ptr = nullptr;
if (!log_cached_ptr)
log_cached_ptr = WLog_Get(tag);
if (WLog_IsLevelActive(log_cached_ptr, log_level))
{
va_list ap = WINPR_C_ARRAY_INIT;
va_start(ap, fmt);
WLog_PrintTextMessageVA(log_cached_ptr, log_level, line, file, fkt, fmt, ap);
va_end(ap);
}
}
#define WLog_LVL(tag, lvl, ...) \
WLog_Print_dbg_tag(tag, lvl, __LINE__, __FILE__, __func__, __VA_ARGS__)
#define WLog_VRB(tag, ...) \
WLog_Print_dbg_tag(tag, WLOG_TRACE, __LINE__, __FILE__, __func__, __VA_ARGS__)
#define WLog_DBG(tag, ...) \
WLog_Print_dbg_tag(tag, WLOG_DEBUG, __LINE__, __FILE__, __func__, __VA_ARGS__)
#define WLog_INFO(tag, ...) \
WLog_Print_dbg_tag(tag, WLOG_INFO, __LINE__, __FILE__, __func__, __VA_ARGS__)
#define WLog_WARN(tag, ...) \
WLog_Print_dbg_tag(tag, WLOG_WARN, __LINE__, __FILE__, __func__, __VA_ARGS__)
#define WLog_ERR(tag, ...) \
WLog_Print_dbg_tag(tag, WLOG_ERROR, __LINE__, __FILE__, __func__, __VA_ARGS__)
#define WLog_FATAL(tag, ...) \
WLog_Print_dbg_tag(tag, WLOG_FATAL, __LINE__, __FILE__, __func__, __VA_ARGS__)
WINPR_API BOOL WLog_SetLogLevel(wLog* log, DWORD logLevel);
WINPR_API BOOL WLog_SetStringLogLevel(wLog* log, LPCSTR level);
WINPR_API BOOL WLog_AddStringLogFilters(LPCSTR filter);
WINPR_API BOOL WLog_SetLogAppenderType(wLog* log, DWORD logAppenderType);
WINPR_API wLogAppender* WLog_GetLogAppender(wLog* log);
WINPR_API BOOL WLog_OpenAppender(wLog* log);
WINPR_API BOOL WLog_CloseAppender(wLog* log);
WINPR_API BOOL WLog_ConfigureAppender(wLogAppender* appender, const char* setting, void* value);
WINPR_API wLogLayout* WLog_GetLogLayout(wLog* log);
WINPR_API BOOL WLog_Layout_SetPrefixFormat(wLog* log, wLogLayout* layout, const char* format);
#if defined(WITH_WINPR_DEPRECATED)
/** Deprecated */
WINPR_DEPRECATED(WINPR_API BOOL WLog_Init(void));
/** Deprecated */
WINPR_DEPRECATED(WINPR_API BOOL WLog_Uninit(void));
#endif
typedef BOOL (*wLogCallbackMessage_t)(const wLogMessage* msg);
typedef BOOL (*wLogCallbackData_t)(const wLogMessage* msg);
typedef BOOL (*wLogCallbackImage_t)(const wLogMessage* msg);
typedef BOOL (*wLogCallbackPackage_t)(const wLogMessage* msg);
typedef struct
{
WINPR_ATTR_NODISCARD wLogCallbackData_t data;
WINPR_ATTR_NODISCARD wLogCallbackImage_t image;
WINPR_ATTR_NODISCARD wLogCallbackMessage_t message;
WINPR_ATTR_NODISCARD wLogCallbackPackage_t package;
} wLogCallbacks;
#ifdef __cplusplus
}
#endif
#endif /* WINPR_WLOG_H */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,501 @@
/**
* WinPR: Windows Portable Runtime
* Windows Data Types
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2024 Armin Novak <anovak@thincast.com>
* Copyright 2024 Thincast Technologies GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_WTYPES_H
#define WINPR_WTYPES_H
#include <assert.h>
#include <winpr/config.h>
#include <winpr/platform.h>
/* MSDN: Windows Data Types - http://msdn.microsoft.com/en-us/library/aa383751/ */
/* [MS-DTYP]: Windows Data Types - http://msdn.microsoft.com/en-us/library/cc230273/ */
#include <wchar.h>
#include <winpr/windows.h>
#include <winpr/spec.h>
#include <stdbool.h>
#include <stdint.h>
#include <inttypes.h>
#include <limits.h>
#if defined(_WIN32) || defined(__MINGW32__)
#include <wtypes.h>
/* Handle missing ssize_t on Windows */
#if defined(WINPR_HAVE_SSIZE_T)
typedef ssize_t SSIZE_T;
#elif !defined(WINPR_HAVE_WIN_SSIZE_T)
typedef intptr_t SSIZE_T;
#endif
#endif
#if defined(__OBJC__) && defined(__APPLE__)
#include <objc/objc.h>
#endif
#ifndef CONST
#define CONST const
#endif
#ifndef VOID
#define VOID void
#endif
WINPR_PRAGMA_DIAG_PUSH WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO
WINPR_PRAGMA_DIAG_IGNORED_RESERVED_IDENTIFIER
#if !defined(_WIN32) && !defined(__MINGW32__)
#define CALLBACK
#define WINAPI
#define CDECL
#ifndef FAR
#define FAR
#endif
#ifndef NEAR
#define NEAR
#endif
typedef void *PVOID,
*LPVOID, *PVOID64, *LPVOID64;
#ifndef XMD_H /* X11/Xmd.h typedef collision with BOOL */
#ifndef __OBJC__ /* objc.h typedef collision with BOOL */
#ifndef __APPLE__
typedef int32_t BOOL;
#else /* __APPLE__ */
#include <TargetConditionals.h>
/* ensure compatibility with objc libraries */
#if OBJC_BOOL_IS_BOOL
typedef bool BOOL;
#else
#define OBJC_BOOL_IS_CHAR 1
typedef signed char BOOL;
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C"
// even if -funsigned-char is used.
#endif
#endif /* __APPLE__ */
#endif /* __OBJC__ */
#endif /* XMD_H */
typedef BOOL *PBOOL, *LPBOOL;
#ifndef FALSE
#define FALSE false
#endif
#ifndef TRUE
#define TRUE true
#endif
#ifndef XMD_H /* X11/Xmd.h typedef collision with BYTE */
typedef uint8_t BYTE;
#endif /* XMD_H */
typedef BYTE byte, *PBYTE, *LPBYTE;
typedef BYTE BOOLEAN, PBOOLEAN;
#if CHAR_BIT == 8
typedef char CHAR;
typedef unsigned char UCHAR;
#else
typedef int8_t CHAR;
typedef uint8_t UCHAR;
#endif
typedef CHAR CCHAR, *PCHAR, *LPCH, *PCH, *PSTR, *LPSTR;
typedef const CHAR *LPCCH, *PCCH, *LPCSTR, *PCSTR;
typedef UCHAR* PUCHAR;
typedef uint16_t WCHAR;
typedef WCHAR UNICODE, *PWCHAR, *LPWCH, *PWCH, *BSTR, *LMSTR, *LPWSTR, *PWSTR;
typedef const WCHAR *LPCWCH, *PCWCH, *LMCSTR, *LPCWSTR, *PCWSTR;
typedef int16_t SHORT, *PSHORT;
typedef int32_t INT, *PINT, *LPINT;
typedef int32_t LONG, *PLONG, *LPLONG;
typedef int64_t LONGLONG, *PLONGLONG;
typedef uint32_t UINT, *PUINT, *LPUINT;
typedef uint16_t USHORT, *PUSHORT;
typedef uint32_t ULONG, *PULONG;
typedef uint64_t ULONGLONG, *PULONGLONG;
#ifndef XMD_H /* X11/Xmd.h typedef collisions */
typedef int8_t INT8;
typedef int16_t INT16;
typedef int32_t INT32;
typedef int64_t INT64;
#endif
typedef INT8* PINT8;
typedef INT16* PINT16;
typedef INT32* PINT32;
typedef INT64* PINT64;
typedef int32_t LONG32, *PLONG32;
#ifndef LONG64 /* X11/Xmd.h uses/defines LONG64 */
typedef int64_t LONG64, *PLONG64;
#endif
typedef uint8_t UINT8, *PUINT8;
typedef uint16_t UINT16, *PUINT16;
typedef uint32_t UINT32, *PUINT32;
typedef uint64_t UINT64, *PUINT64;
typedef uint64_t ULONG64, *PULONG64;
typedef uint16_t WORD, *PWORD, *LPWORD;
typedef uint32_t DWORD, DWORD32, *PDWORD, *LPDWORD, *PDWORD32;
typedef uint64_t DWORD64, DWORDLONG, QWORD, *PDWORD64, *PDWORDLONG, *PQWORD;
typedef intptr_t INT_PTR, *PINT_PTR;
typedef uintptr_t UINT_PTR, *PUINT_PTR;
typedef intptr_t LONG_PTR, *PLONG_PTR;
typedef uintptr_t ULONG_PTR, *PULONG_PTR;
typedef uintptr_t DWORD_PTR, *PDWORD_PTR;
typedef ULONG_PTR SIZE_T, *PSIZE_T; /** deprecated */
#if defined(WINPR_HAVE_SSIZE_T)
#include <sys/types.h>
typedef ssize_t SSIZE_T;
#elif !defined(WINPR_HAVE_WIN_SSIZE_T)
typedef LONG_PTR SSIZE_T;
#endif
typedef float FLOAT;
typedef double DOUBLE;
typedef void* HANDLE;
typedef HANDLE *PHANDLE, *LPHANDLE;
typedef HANDLE HINSTANCE;
typedef HANDLE HMODULE;
typedef HANDLE HWND;
typedef HANDLE HBITMAP;
typedef HANDLE HICON;
typedef HANDLE HCURSOR;
typedef HANDLE HBRUSH;
typedef HANDLE HMENU;
typedef DWORD HCALL;
typedef ULONG error_status_t;
typedef LONG HRESULT;
typedef LONG SCODE;
typedef SCODE* PSCODE;
typedef struct s_POINTL /* ptl */
{
LONG x;
LONG y;
} POINTL, *PPOINTL;
typedef struct tagSIZE
{
LONG cx;
LONG cy;
} SIZE, *PSIZE, *LPSIZE;
typedef SIZE SIZEL;
typedef struct s_GUID
{
UINT32 Data1;
UINT16 Data2;
UINT16 Data3;
BYTE Data4[8];
} GUID, UUID, *PGUID, *LPGUID, *LPCGUID;
typedef GUID CLSID;
typedef struct s_LUID
{
DWORD LowPart;
LONG HighPart;
} LUID, *PLUID;
typedef GUID IID;
typedef IID* REFIID;
#ifdef UNICODE
#define _T(x) u##x // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#else
#define _T(x) x // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#endif
#ifdef UNICODE
typedef LPWSTR PTSTR;
typedef LPWSTR LPTCH;
typedef LPWSTR LPTSTR;
typedef LPCWSTR LPCTSTR;
#else
typedef LPSTR PTSTR;
typedef LPSTR LPTCH;
typedef LPSTR LPTSTR;
typedef LPCSTR LPCTSTR;
#endif
typedef union u_ULARGE_INTEGER
{
struct
{
DWORD LowPart;
DWORD HighPart;
} DUMMYSTRUCTNAME;
struct
{
DWORD LowPart;
DWORD HighPart;
} u;
ULONGLONG QuadPart;
} ULARGE_INTEGER, *PULARGE_INTEGER;
typedef union u_LARGE_INTEGER
{
struct
{
DWORD LowPart;
LONG HighPart;
} DUMMYSTRUCTNAME;
struct
{
DWORD LowPart;
LONG HighPart;
} u;
LONGLONG QuadPart;
} LARGE_INTEGER, *PLARGE_INTEGER;
typedef struct s_FILETIME
{
DWORD dwLowDateTime;
DWORD dwHighDateTime;
} FILETIME, *PFILETIME, *LPFILETIME;
typedef struct s_SYSTEMTIME
{
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME;
typedef struct s_RPC_SID_IDENTIFIER_AUTHORITY
{
BYTE Value[6];
} RPC_SID_IDENTIFIER_AUTHORITY;
typedef DWORD SECURITY_INFORMATION, *PSECURITY_INFORMATION;
typedef struct s_RPC_SID
{
UCHAR Revision;
UCHAR SubAuthorityCount;
RPC_SID_IDENTIFIER_AUTHORITY IdentifierAuthority;
ULONG SubAuthority[1];
} RPC_SID, *PRPC_SID, *PSID;
typedef struct s_ACL
{
UCHAR AclRevision;
UCHAR Sbz1;
USHORT AclSize;
USHORT AceCount;
USHORT Sbz2;
} ACL, *PACL;
typedef struct s_SECURITY_DESCRIPTOR
{
UCHAR Revision;
UCHAR Sbz1;
USHORT Control;
PSID Owner;
PSID Group;
PACL Sacl;
PACL Dacl;
} SECURITY_DESCRIPTOR, *PSECURITY_DESCRIPTOR;
typedef WORD SECURITY_DESCRIPTOR_CONTROL, *PSECURITY_DESCRIPTOR_CONTROL;
typedef struct s_SECURITY_ATTRIBUTES
{
DWORD nLength;
LPVOID lpSecurityDescriptor;
BOOL bInheritHandle;
} SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;
typedef struct s_PROCESS_INFORMATION
{
HANDLE hProcess;
HANDLE hThread;
DWORD dwProcessId;
DWORD dwThreadId;
} PROCESS_INFORMATION, *PPROCESS_INFORMATION, *LPPROCESS_INFORMATION;
typedef DWORD (*PTHREAD_START_ROUTINE)(LPVOID lpThreadParameter);
typedef PTHREAD_START_ROUTINE LPTHREAD_START_ROUTINE;
typedef void* FARPROC;
typedef struct tagDEC
{
USHORT wReserved;
union
{
struct
{
BYTE scale;
BYTE sign;
} DUMMYSTRUCTNAME;
USHORT signscale;
} DUMMYUNIONNAME;
ULONG Hi32;
union
{
struct
{
ULONG Lo32;
ULONG Mid32;
} DUMMYSTRUCTNAME2;
ULONGLONG Lo64;
} DUMMYUNIONNAME2;
} DECIMAL;
typedef DECIMAL* LPDECIMAL;
#define DECIMAL_NEG ((BYTE)0x80)
#define DECIMAL_SETZERO(dec) \
{ \
(dec).Lo64 = 0; \
(dec).Hi32 = 0; \
(dec).signscale = 0; \
}
typedef DWORD LCID;
typedef PDWORD PLCID;
typedef WORD LANGID;
#endif /* _WIN32 not defined */
typedef void* PCONTEXT_HANDLE;
typedef PCONTEXT_HANDLE* PPCONTEXT_HANDLE;
#ifndef _NTDEF
typedef LONG NTSTATUS;
typedef NTSTATUS* PNTSTATUS;
#endif
#ifndef _LPCVOID_DEFINED // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _LPCVOID_DEFINED // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
typedef const VOID* LPCVOID;
#endif
#ifndef _LPCBYTE_DEFINED // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#define _LPCBYTE_DEFINED // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
typedef const BYTE* LPCBYTE;
#endif
#ifndef SSIZE_MAX
#if defined(_POSIX_SSIZE_MAX)
#define SSIZE_MAX _POSIX_SSIZE_MAX
#elif defined(_WIN64)
#define SSIZE_MAX _I64_MAX
#elif defined(_WIN32)
#define SSIZE_MAX LONG_MAX
#else
#define SSIZE_MAX INTPTR_MAX
#endif
#endif
#define PRIdz "zd"
#define PRIiz "zi"
#define PRIuz "zu"
#define PRIoz "zo"
#define PRIxz "zx"
#define PRIXz "zX"
#include <winpr/user.h>
#ifndef _WIN32
#include <stdio.h>
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
static inline int _fseeki64(FILE* fp, INT64 offset, int origin)
{
return fseeko(fp, offset, origin);
}
// NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
static inline INT64 _ftelli64(FILE* fp)
{
return ftello(fp);
}
#endif
WINPR_PRAGMA_DIAG_POP
#endif /* WINPR_WTYPES_H */

View File

@@ -0,0 +1,268 @@
# WinPR: Windows Portable Runtime
# winpr cmake build script
#
# Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
include(CheckFunctionExists)
include(JsonDetect)
set(WINPR_DIR ${CMAKE_CURRENT_SOURCE_DIR})
set(WINPR_SRCS "")
set(WINPR_LIBS_PRIVATE "")
set(WINPR_LIBS_PUBLIC "")
set(WINPR_INCLUDES "")
set(WINPR_SYSTEM_INCLUDES "")
set(WINPR_DEFINITIONS "")
set(WINPR_COMPILE_OPTIONS "")
set(WINPR_LINK_OPTIONS "")
set(WINPR_LINK_DIRS "")
macro(winpr_module_add)
file(RELATIVE_PATH _relPath "${WINPR_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}")
foreach(_src ${ARGN})
if(_relPath)
list(APPEND WINPR_SRCS "${_relPath}/${_src}")
else()
list(APPEND WINPR_SRCS "${_src}")
endif()
endforeach()
if(_relPath)
set(WINPR_SRCS ${WINPR_SRCS} PARENT_SCOPE)
endif()
endmacro()
macro(winpr_include_directory_add)
file(RELATIVE_PATH _relPath "${WINPR_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}")
foreach(_inc ${ARGN})
if(IS_ABSOLUTE ${_inc})
list(APPEND WINPR_INCLUDES "${_inc}")
else()
if(_relPath)
list(APPEND WINPR_INCLUDES "${_relPath}/${_inc}")
else()
list(APPEND WINPR_INCLUDES "${_inc}")
endif()
endif()
endforeach()
if(_relPath)
set(WINPR_INCLUDES ${WINPR_INCLUDES} PARENT_SCOPE)
endif()
endmacro()
macro(winpr_system_include_directory_add)
file(RELATIVE_PATH _relPath "${WINPR_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}")
foreach(_inc ${ARGN})
if(IS_ABSOLUTE ${_inc})
list(APPEND WINPR_SYSTEM_INCLUDES "${_inc}")
else()
if(_relPath)
list(APPEND WINPR_SYSTEM_INCLUDES "${_relPath}/${_inc}")
else()
list(APPEND WINPR_SYSTEM_INCLUDES "${_inc}")
endif()
endif()
endforeach()
if(_relPath)
set(WINPR_SYSTEM_INCLUDES ${WINPR_SYSTEM_INCLUDES} PARENT_SCOPE)
endif()
endmacro()
macro(winpr_library_add_private)
foreach(_lib ${ARGN})
list(APPEND WINPR_LIBS_PRIVATE "${_lib}")
endforeach()
set(WINPR_LIBS_PRIVATE ${WINPR_LIBS_PRIVATE} PARENT_SCOPE)
endmacro()
macro(winpr_library_add_public)
foreach(_lib ${ARGN})
list(APPEND WINPR_LIBS_PUBLIC "${_lib}")
endforeach()
set(WINPR_LIBS_PUBLIC ${WINPR_LIBS_PUBLIC} PARENT_SCOPE)
endmacro()
macro(winpr_definition_add)
foreach(_define ${ARGN})
list(APPEND WINPR_DEFINITIONS "${_define}")
endforeach()
set(WINPR_DEFINITIONS ${WINPR_DEFINITIONS} PARENT_SCOPE)
endmacro()
macro(winpr_library_add_compile_options)
foreach(_define ${ARGN})
list(APPEND WINPR_COMPILE_OPTIONS "${_define}")
endforeach()
set(WINPR_COMPILE_OPTIONS ${WINPR_COMPILE_OPTIONS} PARENT_SCOPE)
endmacro()
macro(winpr_library_add_link_options)
foreach(_define ${ARGN})
list(APPEND WINPR_LINK_OPTIONS "${_define}")
endforeach()
set(WINPR_LINK_OPTIONS ${WINPR_LINK_OPTIONS} PARENT_SCOPE)
endmacro()
macro(winpr_library_add_link_directory)
foreach(_define ${ARGN})
list(APPEND WINPR_LINK_DIRS "${_define}")
endforeach()
set(WINPR_LINK_DIRS ${WINPR_LINK_DIRS} PARENT_SCOPE)
endmacro()
set(CMAKE_REQUIRED_LIBRARIES rt)
find_package(uriparser)
option(WITH_URIPARSER "use uriparser library to handle URIs" ${uriparser_FOUND})
if(WITH_URIPARSER)
find_package(uriparser CONFIG COMPONENTS char)
if(uriparser_FOUND)
winpr_library_add_private(uriparser::uriparser)
else()
find_package(PkgConfig REQUIRED)
pkg_check_modules(uriparser REQUIRED liburiparser)
winpr_system_include_directory_add(${uriparser_INCLUDEDIR})
winpr_system_include_directory_add(${uriparser_INCLUDE_DIRS})
winpr_library_add_private(${uriparser_LIBRARIES})
endif()
add_compile_definitions("WITH_URIPARSER")
winpr_pc_add_requires_private("liburiparser")
endif()
if(NOT IOS)
check_function_exists(timer_create TIMER_CREATE)
check_function_exists(timer_delete TIMER_DELETE)
check_function_exists(timer_settime TIMER_SETTIME)
check_function_exists(timer_gettime TIMER_GETTIME)
if(TIMER_CREATE AND TIMER_DELETE AND TIMER_SETTIME AND TIMER_GETTIME)
add_compile_definitions(WITH_POSIX_TIMER)
winpr_library_add_private(rt)
endif()
endif()
check_function_exists(pthread_setschedprio PTHREAD_SETSCHEDPRIO)
if(PTHREAD_SETSCHEDPRIO)
winpr_definition_add(PTHREAD_SETSCHEDPRIO)
endif()
if(ANDROID)
winpr_library_add_private(log)
endif()
# Level "1" API as defined for MinCore.lib
set(WINPR_CORE
synch
library
file
comm
credentials
pipe
interlocked
security
environment
crypto
registry
path
io
memory
ncrypt
input
shell
utils
error
timezone
sysinfo
pool
handle
thread
)
foreach(DIR ${WINPR_CORE})
add_subdirectory(${DIR})
source_group("${DIR}" REGULAR_EXPRESSION "${DIR}/.*\\.[ch]")
endforeach()
set(WINPR_LEVEL2
winsock
sspi
sspicli
crt
bcrypt
rpc
wtsapi
dsparse
smartcard
nt
clipboard
)
foreach(DIR ${WINPR_LEVEL2})
add_subdirectory(${DIR})
source_group("${DIR}" REGULAR_EXPRESSION "${DIR}/.*\\.[ch]")
endforeach()
set(MODULE_NAME winpr)
list(REMOVE_DUPLICATES WINPR_DEFINITIONS)
list(REMOVE_DUPLICATES WINPR_COMPILE_OPTIONS)
list(REMOVE_DUPLICATES WINPR_LINK_OPTIONS)
list(REMOVE_DUPLICATES WINPR_LINK_DIRS)
list(REMOVE_DUPLICATES WINPR_INCLUDES)
list(REMOVE_DUPLICATES WINPR_SYSTEM_INCLUDES)
addtargetwithresourcefile(${MODULE_NAME} FALSE "${WINPR_VERSION}" WINPR_SRCS)
if(WITH_RESOURCE_VERSIONING)
target_compile_definitions(${MODULE_NAME} PRIVATE WITH_RESOURCE_VERSIONING)
endif()
if(WINPR_USE_VENDOR_PRODUCT_CONFIG_DIR)
target_compile_definitions(${MODULE_NAME} PRIVATE WINPR_USE_VENDOR_PRODUCT_CONFIG_DIR)
endif()
if(APPLE)
set_target_properties(${MODULE_NAME} PROPERTIES INTERPROCEDURAL_OPTIMIZATION FALSE)
endif()
if(NOT BUILD_SHARED_LIBS)
set(LINK_OPTS_MODE PUBLIC)
else()
set(LINK_OPTS_MODE PRIVATE)
endif()
target_link_options(${MODULE_NAME} ${LINK_OPTS_MODE} ${WINPR_LINK_OPTIONS})
target_include_directories(${MODULE_NAME} PRIVATE ${WINPR_INCLUDES})
target_include_directories(${MODULE_NAME} SYSTEM PRIVATE ${WINPR_SYSTEM_INCLUDES})
target_include_directories(${MODULE_NAME} INTERFACE $<INSTALL_INTERFACE:include/winpr${WINPR_VERSION_MAJOR}>)
target_link_directories(${MODULE_NAME} PRIVATE ${WINPR_LINK_DIRS})
target_compile_options(${MODULE_NAME} PRIVATE ${WINPR_COMPILE_OPTIONS})
target_compile_definitions(${MODULE_NAME} PRIVATE ${WINPR_DEFINITIONS})
target_link_libraries(${MODULE_NAME} PRIVATE ${WINPR_LIBS_PRIVATE} PUBLIC ${WINPR_LIBS_PUBLIC})
installwithrpath(
TARGETS
${MODULE_NAME}
COMPONENT
libraries
EXPORT
WinPRTargets
ARCHIVE
DESTINATION
${CMAKE_INSTALL_LIBDIR}
LIBRARY
DESTINATION
${CMAKE_INSTALL_LIBDIR}
RUNTIME
DESTINATION
${CMAKE_INSTALL_BINDIR}
)
set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "WinPR/libwinpr")

View File

@@ -0,0 +1,22 @@
# WinPR: Windows Portable Runtime
# libwinpr-bcrypt cmake build script
#
# Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
winpr_module_add(bcrypt.c)
if(BUILD_TESTING_INTERNAL OR BUILD_TESTING)
add_subdirectory(test)
endif()

View File

@@ -0,0 +1,7 @@
set(MINWIN_LAYER "0")
set(MINWIN_GROUP "none")
set(MINWIN_MAJOR_VERSION "0")
set(MINWIN_MINOR_VERSION "0")
set(MINWIN_SHORT_NAME "bcrypt")
set(MINWIN_LONG_NAME "Cryptography API: Next Generation (CNG)")
set(MODULE_LIBRARY_NAME "${MINWIN_SHORT_NAME}")

View File

@@ -0,0 +1,154 @@
/**
* WinPR: Windows Portable Runtime
* Cryptography API: Next Generation
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <winpr/config.h>
#include <winpr/wlog.h>
#ifndef _WIN32
#include <winpr/bcrypt.h>
/**
* Cryptography API: Next Generation:
* http://msdn.microsoft.com/en-us/library/windows/desktop/aa376210/
*/
NTSTATUS BCryptOpenAlgorithmProvider(WINPR_ATTR_UNUSED BCRYPT_ALG_HANDLE* phAlgorithm,
WINPR_ATTR_UNUSED LPCWSTR pszAlgId,
WINPR_ATTR_UNUSED LPCWSTR pszImplementation,
WINPR_ATTR_UNUSED ULONG dwFlags)
{
WLog_ERR("TODO", "TODO: implement");
return 0;
}
NTSTATUS BCryptCloseAlgorithmProvider(WINPR_ATTR_UNUSED BCRYPT_ALG_HANDLE hAlgorithm,
WINPR_ATTR_UNUSED ULONG dwFlags)
{
WLog_ERR("TODO", "TODO: implement");
return 0;
}
NTSTATUS BCryptGetProperty(WINPR_ATTR_UNUSED BCRYPT_HANDLE hObject,
WINPR_ATTR_UNUSED LPCWSTR pszProperty, WINPR_ATTR_UNUSED PUCHAR pbOutput,
WINPR_ATTR_UNUSED ULONG cbOutput, WINPR_ATTR_UNUSED ULONG* pcbResult,
WINPR_ATTR_UNUSED ULONG dwFlags)
{
WLog_ERR("TODO", "TODO: implement");
return 0;
}
NTSTATUS BCryptCreateHash(WINPR_ATTR_UNUSED BCRYPT_ALG_HANDLE hAlgorithm,
WINPR_ATTR_UNUSED BCRYPT_HASH_HANDLE* phHash,
WINPR_ATTR_UNUSED PUCHAR pbHashObject,
WINPR_ATTR_UNUSED ULONG cbHashObject, WINPR_ATTR_UNUSED PUCHAR pbSecret,
WINPR_ATTR_UNUSED ULONG cbSecret, WINPR_ATTR_UNUSED ULONG dwFlags)
{
WLog_ERR("TODO", "TODO: implement");
return 0;
}
NTSTATUS BCryptDestroyHash(WINPR_ATTR_UNUSED BCRYPT_HASH_HANDLE hHash)
{
WLog_ERR("TODO", "TODO: implement");
return 0;
}
NTSTATUS BCryptHashData(WINPR_ATTR_UNUSED BCRYPT_HASH_HANDLE hHash,
WINPR_ATTR_UNUSED PUCHAR pbInput, WINPR_ATTR_UNUSED ULONG cbInput,
WINPR_ATTR_UNUSED ULONG dwFlags)
{
WLog_ERR("TODO", "TODO: implement");
return 0;
}
NTSTATUS BCryptFinishHash(WINPR_ATTR_UNUSED BCRYPT_HASH_HANDLE hHash,
WINPR_ATTR_UNUSED PUCHAR pbOutput, WINPR_ATTR_UNUSED ULONG cbOutput,
WINPR_ATTR_UNUSED ULONG dwFlags)
{
WLog_ERR("TODO", "TODO: implement");
return 0;
}
NTSTATUS BCryptGenRandom(WINPR_ATTR_UNUSED BCRYPT_ALG_HANDLE hAlgorithm,
WINPR_ATTR_UNUSED PUCHAR pbBuffer, WINPR_ATTR_UNUSED ULONG cbBuffer,
WINPR_ATTR_UNUSED ULONG dwFlags)
{
WLog_ERR("TODO", "TODO: implement");
return 0;
}
NTSTATUS BCryptGenerateSymmetricKey(WINPR_ATTR_UNUSED BCRYPT_ALG_HANDLE hAlgorithm,
WINPR_ATTR_UNUSED BCRYPT_KEY_HANDLE* phKey,
WINPR_ATTR_UNUSED PUCHAR pbKeyObject,
WINPR_ATTR_UNUSED ULONG cbKeyObject,
WINPR_ATTR_UNUSED PUCHAR pbSecret,
WINPR_ATTR_UNUSED ULONG cbSecret,
WINPR_ATTR_UNUSED ULONG dwFlags)
{
WLog_ERR("TODO", "TODO: implement");
return 0;
}
NTSTATUS BCryptGenerateKeyPair(WINPR_ATTR_UNUSED BCRYPT_ALG_HANDLE hAlgorithm,
WINPR_ATTR_UNUSED BCRYPT_KEY_HANDLE* phKey,
WINPR_ATTR_UNUSED ULONG dwLength, WINPR_ATTR_UNUSED ULONG dwFlags)
{
WLog_ERR("TODO", "TODO: implement");
return 0;
}
NTSTATUS BCryptImportKey(WINPR_ATTR_UNUSED BCRYPT_ALG_HANDLE hAlgorithm,
WINPR_ATTR_UNUSED BCRYPT_KEY_HANDLE hImportKey,
WINPR_ATTR_UNUSED LPCWSTR pszBlobType,
WINPR_ATTR_UNUSED BCRYPT_KEY_HANDLE* phKey,
WINPR_ATTR_UNUSED PUCHAR pbKeyObject, WINPR_ATTR_UNUSED ULONG cbKeyObject,
WINPR_ATTR_UNUSED PUCHAR pbInput, WINPR_ATTR_UNUSED ULONG cbInput,
WINPR_ATTR_UNUSED ULONG dwFlags)
{
WLog_ERR("TODO", "TODO: implement");
return 0;
}
NTSTATUS BCryptDestroyKey(WINPR_ATTR_UNUSED BCRYPT_KEY_HANDLE hKey)
{
WLog_ERR("TODO", "TODO: implement");
return 0;
}
NTSTATUS BCryptEncrypt(WINPR_ATTR_UNUSED BCRYPT_KEY_HANDLE hKey, WINPR_ATTR_UNUSED PUCHAR pbInput,
WINPR_ATTR_UNUSED ULONG cbInput, WINPR_ATTR_UNUSED VOID* pPaddingInfo,
WINPR_ATTR_UNUSED PUCHAR pbIV, WINPR_ATTR_UNUSED ULONG cbIV,
WINPR_ATTR_UNUSED PUCHAR pbOutput, WINPR_ATTR_UNUSED ULONG cbOutput,
WINPR_ATTR_UNUSED ULONG* pcbResult, WINPR_ATTR_UNUSED ULONG dwFlags)
{
WLog_ERR("TODO", "TODO: implement");
return 0;
}
NTSTATUS BCryptDecrypt(WINPR_ATTR_UNUSED BCRYPT_KEY_HANDLE hKey, WINPR_ATTR_UNUSED PUCHAR pbInput,
WINPR_ATTR_UNUSED ULONG cbInput, WINPR_ATTR_UNUSED VOID* pPaddingInfo,
WINPR_ATTR_UNUSED PUCHAR pbIV, WINPR_ATTR_UNUSED ULONG cbIV,
WINPR_ATTR_UNUSED PUCHAR pbOutput, WINPR_ATTR_UNUSED ULONG cbOutput,
WINPR_ATTR_UNUSED ULONG* pcbResult, WINPR_ATTR_UNUSED ULONG dwFlags)
{
WLog_ERR("TODO", "TODO: implement");
return 0;
}
#endif /* _WIN32 */

View File

@@ -0,0 +1,21 @@
set(MODULE_NAME "TestBCrypt")
disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR})
set(DRIVER ${MODULE_NAME}.c)
set(TESTS TestBCryptDefine.c)
create_test_sourcelist(SRCS ${DRIVER} ${TESTS})
add_executable(${MODULE_NAME} ${SRCS})
target_link_libraries(${MODULE_NAME} winpr)
set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}")
foreach(test ${TESTS})
get_filename_component(TestName ${test} NAME_WE)
add_test(${TestName} ${TESTING_OUTPUT_DIRECTORY}/${MODULE_NAME} ${TestName})
endforeach()
set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "WinPR/Test")

View File

@@ -0,0 +1,129 @@
#include <stdio.h>
#include <winpr/string.h>
#include <winpr/bcrypt.h>
#define STR(x) #x
static BOOL test_wchar_len(void)
{
struct test_case
{
size_t bytelen;
const char* name;
const WCHAR* value;
};
const struct test_case test_cases[] = {
{ sizeof(BCRYPT_RSA_ALGORITHM), STR(BCRYPT_RSA_ALGORITHM), BCRYPT_RSA_ALGORITHM },
{ sizeof(BCRYPT_RSA_SIGN_ALGORITHM), STR(BCRYPT_RSA_SIGN_ALGORITHM),
BCRYPT_RSA_SIGN_ALGORITHM },
{ sizeof(BCRYPT_DH_ALGORITHM), STR(BCRYPT_DH_ALGORITHM), BCRYPT_DH_ALGORITHM },
{ sizeof(BCRYPT_DSA_ALGORITHM), STR(BCRYPT_DSA_ALGORITHM), BCRYPT_DSA_ALGORITHM },
{ sizeof(BCRYPT_RC2_ALGORITHM), STR(BCRYPT_RC2_ALGORITHM), BCRYPT_RC2_ALGORITHM },
{ sizeof(BCRYPT_RC4_ALGORITHM), STR(BCRYPT_RC4_ALGORITHM), BCRYPT_RC4_ALGORITHM },
{ sizeof(BCRYPT_AES_ALGORITHM), STR(BCRYPT_AES_ALGORITHM), BCRYPT_AES_ALGORITHM },
{ sizeof(BCRYPT_DES_ALGORITHM), STR(BCRYPT_DES_ALGORITHM), BCRYPT_DES_ALGORITHM },
{ sizeof(BCRYPT_DESX_ALGORITHM), STR(BCRYPT_DESX_ALGORITHM), BCRYPT_DESX_ALGORITHM },
{ sizeof(BCRYPT_3DES_ALGORITHM), STR(BCRYPT_3DES_ALGORITHM), BCRYPT_3DES_ALGORITHM },
{ sizeof(BCRYPT_3DES_112_ALGORITHM), STR(BCRYPT_3DES_112_ALGORITHM),
BCRYPT_3DES_112_ALGORITHM },
{ sizeof(BCRYPT_MD2_ALGORITHM), STR(BCRYPT_MD2_ALGORITHM), BCRYPT_MD2_ALGORITHM },
{ sizeof(BCRYPT_MD4_ALGORITHM), STR(BCRYPT_MD4_ALGORITHM), BCRYPT_MD4_ALGORITHM },
{ sizeof(BCRYPT_MD5_ALGORITHM), STR(BCRYPT_MD5_ALGORITHM), BCRYPT_MD5_ALGORITHM },
{ sizeof(BCRYPT_SHA1_ALGORITHM), STR(BCRYPT_SHA1_ALGORITHM), BCRYPT_SHA1_ALGORITHM },
{ sizeof(BCRYPT_SHA256_ALGORITHM), STR(BCRYPT_SHA256_ALGORITHM), BCRYPT_SHA256_ALGORITHM },
{ sizeof(BCRYPT_SHA384_ALGORITHM), STR(BCRYPT_SHA384_ALGORITHM), BCRYPT_SHA384_ALGORITHM },
{ sizeof(BCRYPT_SHA512_ALGORITHM), STR(BCRYPT_SHA512_ALGORITHM), BCRYPT_SHA512_ALGORITHM },
{ sizeof(BCRYPT_AES_GMAC_ALGORITHM), STR(BCRYPT_AES_GMAC_ALGORITHM),
BCRYPT_AES_GMAC_ALGORITHM },
{ sizeof(BCRYPT_AES_CMAC_ALGORITHM), STR(BCRYPT_AES_CMAC_ALGORITHM),
BCRYPT_AES_CMAC_ALGORITHM },
{ sizeof(BCRYPT_ECDSA_P256_ALGORITHM), STR(BCRYPT_ECDSA_P256_ALGORITHM),
BCRYPT_ECDSA_P256_ALGORITHM },
{ sizeof(BCRYPT_ECDSA_P384_ALGORITHM), STR(BCRYPT_ECDSA_P384_ALGORITHM),
BCRYPT_ECDSA_P384_ALGORITHM },
{ sizeof(BCRYPT_ECDSA_P521_ALGORITHM), STR(BCRYPT_ECDSA_P521_ALGORITHM),
BCRYPT_ECDSA_P521_ALGORITHM },
{ sizeof(BCRYPT_ECDH_P256_ALGORITHM), STR(BCRYPT_ECDH_P256_ALGORITHM),
BCRYPT_ECDH_P256_ALGORITHM },
{ sizeof(BCRYPT_ECDH_P384_ALGORITHM), STR(BCRYPT_ECDH_P384_ALGORITHM),
BCRYPT_ECDH_P384_ALGORITHM },
{ sizeof(BCRYPT_ECDH_P521_ALGORITHM), STR(BCRYPT_ECDH_P521_ALGORITHM),
BCRYPT_ECDH_P521_ALGORITHM },
{ sizeof(BCRYPT_RNG_ALGORITHM), STR(BCRYPT_RNG_ALGORITHM), BCRYPT_RNG_ALGORITHM },
{ sizeof(BCRYPT_RNG_FIPS186_DSA_ALGORITHM), STR(BCRYPT_RNG_FIPS186_DSA_ALGORITHM),
BCRYPT_RNG_FIPS186_DSA_ALGORITHM },
{ sizeof(BCRYPT_RNG_DUAL_EC_ALGORITHM), STR(BCRYPT_RNG_DUAL_EC_ALGORITHM),
BCRYPT_RNG_DUAL_EC_ALGORITHM },
// The following algorithms are only supported on windows 10 onward.
#if !defined(_WIN32) || _WIN32_WINNT >= 0x0A00
{ sizeof(BCRYPT_ECDSA_ALGORITHM), STR(BCRYPT_ECDSA_ALGORITHM), BCRYPT_ECDSA_ALGORITHM },
{ sizeof(BCRYPT_ECDH_ALGORITHM), STR(BCRYPT_ECDH_ALGORITHM), BCRYPT_ECDH_ALGORITHM },
{ sizeof(BCRYPT_XTS_AES_ALGORITHM), STR(BCRYPT_XTS_AES_ALGORITHM),
BCRYPT_XTS_AES_ALGORITHM },
#endif
{ sizeof(MS_PRIMITIVE_PROVIDER), STR(MS_PRIMITIVE_PROVIDER), MS_PRIMITIVE_PROVIDER },
{ sizeof(MS_PLATFORM_CRYPTO_PROVIDER), STR(MS_PLATFORM_CRYPTO_PROVIDER),
MS_PLATFORM_CRYPTO_PROVIDER },
{ sizeof(BCRYPT_OBJECT_LENGTH), STR(BCRYPT_OBJECT_LENGTH), BCRYPT_OBJECT_LENGTH },
{ sizeof(BCRYPT_ALGORITHM_NAME), STR(BCRYPT_ALGORITHM_NAME), BCRYPT_ALGORITHM_NAME },
{ sizeof(BCRYPT_PROVIDER_HANDLE), STR(BCRYPT_PROVIDER_HANDLE), BCRYPT_PROVIDER_HANDLE },
{ sizeof(BCRYPT_CHAINING_MODE), STR(BCRYPT_CHAINING_MODE), BCRYPT_CHAINING_MODE },
{ sizeof(BCRYPT_BLOCK_LENGTH), STR(BCRYPT_BLOCK_LENGTH), BCRYPT_BLOCK_LENGTH },
{ sizeof(BCRYPT_KEY_LENGTH), STR(BCRYPT_KEY_LENGTH), BCRYPT_KEY_LENGTH },
{ sizeof(BCRYPT_KEY_OBJECT_LENGTH), STR(BCRYPT_KEY_OBJECT_LENGTH),
BCRYPT_KEY_OBJECT_LENGTH },
{ sizeof(BCRYPT_KEY_STRENGTH), STR(BCRYPT_KEY_STRENGTH), BCRYPT_KEY_STRENGTH },
{ sizeof(BCRYPT_KEY_LENGTHS), STR(BCRYPT_KEY_LENGTHS), BCRYPT_KEY_LENGTHS },
{ sizeof(BCRYPT_BLOCK_SIZE_LIST), STR(BCRYPT_BLOCK_SIZE_LIST), BCRYPT_BLOCK_SIZE_LIST },
{ sizeof(BCRYPT_EFFECTIVE_KEY_LENGTH), STR(BCRYPT_EFFECTIVE_KEY_LENGTH),
BCRYPT_EFFECTIVE_KEY_LENGTH },
{ sizeof(BCRYPT_HASH_LENGTH), STR(BCRYPT_HASH_LENGTH), BCRYPT_HASH_LENGTH },
{ sizeof(BCRYPT_HASH_OID_LIST), STR(BCRYPT_HASH_OID_LIST), BCRYPT_HASH_OID_LIST },
{ sizeof(BCRYPT_PADDING_SCHEMES), STR(BCRYPT_PADDING_SCHEMES), BCRYPT_PADDING_SCHEMES },
{ sizeof(BCRYPT_SIGNATURE_LENGTH), STR(BCRYPT_SIGNATURE_LENGTH), BCRYPT_SIGNATURE_LENGTH },
{ sizeof(BCRYPT_HASH_BLOCK_LENGTH), STR(BCRYPT_HASH_BLOCK_LENGTH),
BCRYPT_HASH_BLOCK_LENGTH },
{ sizeof(BCRYPT_AUTH_TAG_LENGTH), STR(BCRYPT_AUTH_TAG_LENGTH), BCRYPT_AUTH_TAG_LENGTH },
{ sizeof(BCRYPT_PRIMITIVE_TYPE), STR(BCRYPT_PRIMITIVE_TYPE), BCRYPT_PRIMITIVE_TYPE },
{ sizeof(BCRYPT_IS_KEYED_HASH), STR(BCRYPT_IS_KEYED_HASH), BCRYPT_IS_KEYED_HASH },
{ sizeof(BCRYPT_KEY_DATA_BLOB), STR(BCRYPT_KEY_DATA_BLOB), BCRYPT_KEY_DATA_BLOB }
};
BOOL rc = TRUE;
for (size_t x = 0; x < ARRAYSIZE(test_cases); x++)
{
const struct test_case* cur = &test_cases[x];
// sizeof(WCHAR) == 2, so all strings must have even byte length
if (cur->bytelen % 2 != 0)
{
(void)fprintf(stderr, "[%s] invalid bytelength %" PRIuz, cur->name, cur->bytelen);
rc = FALSE;
continue;
}
// each string must be '\0' terminated
const size_t len = _wcsnlen(cur->value, cur->bytelen / sizeof(WCHAR));
if (len == cur->bytelen / sizeof(WCHAR))
{
(void)fprintf(stderr, "[%s] missing '\0' termination", cur->name);
rc = FALSE;
continue;
}
}
return rc;
}
int TestBCryptDefine(int argc, char* argv[])
{
WINPR_UNUSED(argc);
WINPR_UNUSED(argv);
if (!test_wchar_len())
return -1;
return 0;
}

View File

@@ -0,0 +1,22 @@
# WinPR: Windows Portable Runtime
# libwinpr-clipboard cmake build script
#
# Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
winpr_module_add(synthetic.c clipboard.c clipboard.h synthetic_file.h synthetic_file.c)
if(BUILD_TESTING_INTERNAL OR BUILD_TESTING)
add_subdirectory(test)
endif()

View File

@@ -0,0 +1,7 @@
set(MINWIN_LAYER "0")
set(MINWIN_GROUP "none")
set(MINWIN_MAJOR_VERSION "0")
set(MINWIN_MINOR_VERSION "0")
set(MINWIN_SHORT_NAME "clipboard")
set(MINWIN_LONG_NAME "Clipboard Functions")
set(MODULE_LIBRARY_NAME "clipboard")

View File

@@ -0,0 +1,771 @@
/**
* WinPR: Windows Portable Runtime
* Clipboard Functions
*
* Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <winpr/config.h>
#include <winpr/crt.h>
#include <winpr/collections.h>
#include <winpr/wlog.h>
#include <winpr/clipboard.h>
#include "clipboard.h"
#include "synthetic_file.h"
#include "../log.h"
#define TAG WINPR_TAG("clipboard")
const char* const mime_text_plain = "text/plain";
/**
* Clipboard (Windows):
* msdn.microsoft.com/en-us/library/windows/desktop/ms648709/
*
* W3C Clipboard API and events:
* http://www.w3.org/TR/clipboard-apis/
*/
static const char* CF_STANDARD_STRINGS[] = {
"CF_RAW", /* 0 */
"CF_TEXT", /* 1 */
"CF_BITMAP", /* 2 */
"CF_METAFILEPICT", /* 3 */
"CF_SYLK", /* 4 */
"CF_DIF", /* 5 */
"CF_TIFF", /* 6 */
"CF_OEMTEXT", /* 7 */
"CF_DIB", /* 8 */
"CF_PALETTE", /* 9 */
"CF_PENDATA", /* 10 */
"CF_RIFF", /* 11 */
"CF_WAVE", /* 12 */
"CF_UNICODETEXT", /* 13 */
"CF_ENHMETAFILE", /* 14 */
"CF_HDROP", /* 15 */
"CF_LOCALE", /* 16 */
"CF_DIBV5" /* 17 */
};
const char* ClipboardGetFormatIdString(UINT32 formatId)
{
if (formatId < ARRAYSIZE(CF_STANDARD_STRINGS))
return CF_STANDARD_STRINGS[formatId];
return "CF_REGISTERED_FORMAT";
}
static wClipboardFormat* ClipboardFindFormat(wClipboard* clipboard, UINT32 formatId,
const char* name)
{
wClipboardFormat* format = nullptr;
if (!clipboard)
return nullptr;
if (formatId)
{
for (UINT32 index = 0; index < clipboard->numFormats; index++)
{
wClipboardFormat* cformat = &clipboard->formats[index];
if (formatId == cformat->formatId)
{
format = cformat;
break;
}
}
}
else if (name)
{
for (UINT32 index = 0; index < clipboard->numFormats; index++)
{
wClipboardFormat* cformat = &clipboard->formats[index];
if (!cformat->formatName)
continue;
if (strcmp(name, cformat->formatName) == 0)
{
format = cformat;
break;
}
}
}
else
{
/* special "CF_RAW" case */
if (clipboard->numFormats > 0)
{
format = &clipboard->formats[0];
if (format->formatId)
return nullptr;
if (!format->formatName || (strcmp(format->formatName, CF_STANDARD_STRINGS[0]) == 0))
return format;
}
}
return format;
}
static wClipboardSynthesizer* ClipboardFindSynthesizer(wClipboardFormat* format, UINT32 formatId)
{
if (!format)
return nullptr;
for (UINT32 index = 0; index < format->numSynthesizers; index++)
{
wClipboardSynthesizer* synthesizer = &(format->synthesizers[index]);
if (formatId == synthesizer->syntheticId)
return synthesizer;
}
return nullptr;
}
void ClipboardLock(wClipboard* clipboard)
{
if (!clipboard)
return;
EnterCriticalSection(&(clipboard->lock));
}
void ClipboardUnlock(wClipboard* clipboard)
{
if (!clipboard)
return;
LeaveCriticalSection(&(clipboard->lock));
}
BOOL ClipboardEmpty(wClipboard* clipboard)
{
if (!clipboard)
return FALSE;
if (clipboard->data)
{
free(clipboard->data);
clipboard->data = nullptr;
}
clipboard->size = 0;
clipboard->formatId = 0;
clipboard->sequenceNumber++;
return TRUE;
}
UINT32 ClipboardCountRegisteredFormats(wClipboard* clipboard)
{
if (!clipboard)
return 0;
return clipboard->numFormats;
}
UINT32 ClipboardGetRegisteredFormatIds(wClipboard* clipboard, UINT32** ppFormatIds)
{
UINT32* pFormatIds = nullptr;
wClipboardFormat* format = nullptr;
if (!clipboard)
return 0;
if (!ppFormatIds)
return 0;
pFormatIds = *ppFormatIds;
if (!pFormatIds)
{
pFormatIds = calloc(clipboard->numFormats, sizeof(UINT32));
if (!pFormatIds)
return 0;
*ppFormatIds = pFormatIds;
}
for (UINT32 index = 0; index < clipboard->numFormats; index++)
{
format = &(clipboard->formats[index]);
pFormatIds[index] = format->formatId;
}
return clipboard->numFormats;
}
UINT32 ClipboardRegisterFormat(wClipboard* clipboard, const char* name)
{
wClipboardFormat* format = nullptr;
if (!clipboard)
return 0;
format = ClipboardFindFormat(clipboard, 0, name);
if (format)
return format->formatId;
if ((clipboard->numFormats + 1) >= clipboard->maxFormats)
{
UINT32 numFormats = clipboard->maxFormats * 2;
wClipboardFormat* tmpFormat = nullptr;
tmpFormat =
(wClipboardFormat*)realloc(clipboard->formats, numFormats * sizeof(wClipboardFormat));
if (!tmpFormat)
return 0;
clipboard->formats = tmpFormat;
clipboard->maxFormats = numFormats;
}
format = &(clipboard->formats[clipboard->numFormats]);
ZeroMemory(format, sizeof(wClipboardFormat));
if (name)
{
format->formatName = _strdup(name);
if (!format->formatName)
return 0;
}
format->formatId = clipboard->nextFormatId++;
clipboard->numFormats++;
return format->formatId;
}
BOOL ClipboardRegisterSynthesizer(wClipboard* clipboard, UINT32 formatId, UINT32 syntheticId,
CLIPBOARD_SYNTHESIZE_FN pfnSynthesize)
{
UINT32 index = 0;
wClipboardFormat* format = nullptr;
wClipboardSynthesizer* synthesizer = nullptr;
if (!clipboard)
return FALSE;
format = ClipboardFindFormat(clipboard, formatId, nullptr);
if (!format)
return FALSE;
if (format->formatId == syntheticId)
return FALSE;
synthesizer = ClipboardFindSynthesizer(format, formatId);
if (!synthesizer)
{
wClipboardSynthesizer* tmpSynthesizer = nullptr;
UINT32 numSynthesizers = format->numSynthesizers + 1;
tmpSynthesizer = (wClipboardSynthesizer*)realloc(
format->synthesizers, numSynthesizers * sizeof(wClipboardSynthesizer));
if (!tmpSynthesizer)
return FALSE;
format->synthesizers = tmpSynthesizer;
format->numSynthesizers = numSynthesizers;
index = numSynthesizers - 1;
synthesizer = &(format->synthesizers[index]);
}
synthesizer->syntheticId = syntheticId;
synthesizer->pfnSynthesize = pfnSynthesize;
return TRUE;
}
UINT32 ClipboardCountFormats(wClipboard* clipboard)
{
UINT32 count = 0;
wClipboardFormat* format = nullptr;
if (!clipboard)
return 0;
format = ClipboardFindFormat(clipboard, clipboard->formatId, nullptr);
if (!format)
return 0;
count = 1 + format->numSynthesizers;
return count;
}
UINT32 ClipboardGetFormatIds(wClipboard* clipboard, UINT32** ppFormatIds)
{
UINT32 count = 0;
UINT32* pFormatIds = nullptr;
wClipboardFormat* format = nullptr;
wClipboardSynthesizer* synthesizer = nullptr;
if (!clipboard)
return 0;
format = ClipboardFindFormat(clipboard, clipboard->formatId, nullptr);
if (!format)
return 0;
count = 1 + format->numSynthesizers;
if (!ppFormatIds)
return 0;
pFormatIds = *ppFormatIds;
if (!pFormatIds)
{
pFormatIds = calloc(count, sizeof(UINT32));
if (!pFormatIds)
return 0;
*ppFormatIds = pFormatIds;
}
pFormatIds[0] = format->formatId;
for (UINT32 index = 1; index < count; index++)
{
synthesizer = &(format->synthesizers[index - 1]);
pFormatIds[index] = synthesizer->syntheticId;
}
return count;
}
static void ClipboardUninitFormats(wClipboard* clipboard)
{
WINPR_ASSERT(clipboard);
for (UINT32 formatId = 0; formatId < clipboard->numFormats; formatId++)
{
wClipboardFormat* format = &clipboard->formats[formatId];
free(format->formatName);
free(format->synthesizers);
format->formatName = nullptr;
format->synthesizers = nullptr;
}
}
static BOOL ClipboardInitFormats(wClipboard* clipboard)
{
UINT32 formatId = 0;
wClipboardFormat* format = nullptr;
if (!clipboard)
return FALSE;
for (formatId = 0; formatId < CF_MAX; formatId++, clipboard->numFormats++)
{
format = &(clipboard->formats[clipboard->numFormats]);
ZeroMemory(format, sizeof(wClipboardFormat));
format->formatId = formatId;
format->formatName = _strdup(CF_STANDARD_STRINGS[formatId]);
if (!format->formatName)
goto error;
}
if (!ClipboardInitSynthesizers(clipboard))
goto error;
return TRUE;
error:
ClipboardUninitFormats(clipboard);
return FALSE;
}
UINT32 ClipboardGetFormatId(wClipboard* clipboard, const char* name)
{
wClipboardFormat* format = nullptr;
if (!clipboard)
return 0;
format = ClipboardFindFormat(clipboard, 0, name);
if (!format)
return 0;
return format->formatId;
}
const char* ClipboardGetFormatName(wClipboard* clipboard, UINT32 formatId)
{
wClipboardFormat* format = nullptr;
if (!clipboard)
return nullptr;
format = ClipboardFindFormat(clipboard, formatId, nullptr);
if (!format)
return nullptr;
return format->formatName;
}
void* ClipboardGetData(wClipboard* clipboard, UINT32 formatId, UINT32* pSize)
{
UINT32 SrcSize = 0;
UINT32 DstSize = 0;
void* pSrcData = nullptr;
void* pDstData = nullptr;
wClipboardFormat* format = nullptr;
wClipboardSynthesizer* synthesizer = nullptr;
if (!clipboard || !pSize)
{
WLog_ERR(TAG, "Invalid parameters clipboard=%p, pSize=%p",
WINPR_CXX_COMPAT_CAST(const void*, clipboard),
WINPR_CXX_COMPAT_CAST(const void*, pSize));
return nullptr;
}
*pSize = 0;
format = ClipboardFindFormat(clipboard, clipboard->formatId, nullptr);
if (!format)
{
WLog_ERR(TAG, "Format [0x%08" PRIx32 "] not found", clipboard->formatId);
return nullptr;
}
SrcSize = clipboard->size;
pSrcData = clipboard->data;
if (formatId == format->formatId)
{
DstSize = SrcSize;
pDstData = malloc(DstSize);
if (!pDstData)
return nullptr;
CopyMemory(pDstData, pSrcData, SrcSize);
*pSize = DstSize;
}
else
{
synthesizer = ClipboardFindSynthesizer(format, formatId);
if (!synthesizer || !synthesizer->pfnSynthesize)
{
WLog_ERR(TAG, "No synthesizer for format %s [0x%08" PRIx32 "] --> %s [0x%08" PRIx32 "]",
ClipboardGetFormatName(clipboard, clipboard->formatId), clipboard->formatId,
ClipboardGetFormatName(clipboard, formatId), formatId);
return nullptr;
}
DstSize = SrcSize;
pDstData = synthesizer->pfnSynthesize(clipboard, format->formatId, pSrcData, &DstSize);
if (pDstData)
*pSize = DstSize;
}
WLog_DBG(TAG, "getting formatId=%s [0x%08" PRIx32 "] data=%p, size=%" PRIu32,
ClipboardGetFormatName(clipboard, formatId), formatId, pDstData, *pSize);
return pDstData;
}
BOOL ClipboardSetData(wClipboard* clipboard, UINT32 formatId, const void* data, UINT32 size)
{
wClipboardFormat* format = nullptr;
WLog_DBG(TAG, "setting formatId=%s [0x%08" PRIx32 "], size=%" PRIu32,
ClipboardGetFormatName(clipboard, formatId), formatId, size);
if (!clipboard)
return FALSE;
format = ClipboardFindFormat(clipboard, formatId, nullptr);
if (!format)
return FALSE;
free(clipboard->data);
clipboard->data = calloc(size + sizeof(WCHAR), sizeof(char));
if (!clipboard->data)
return FALSE;
memcpy(clipboard->data, data, size);
/* For string values we don´t know if they are '\0' terminated.
* so set the size to the full length in bytes (e.g. string length + 1)
*/
switch (formatId)
{
case CF_TEXT:
case CF_OEMTEXT:
clipboard->size = (UINT32)(strnlen(clipboard->data, size) + 1UL);
break;
case CF_UNICODETEXT:
clipboard->size =
(UINT32)((_wcsnlen(clipboard->data, size / sizeof(WCHAR)) + 1UL) * sizeof(WCHAR));
break;
default:
clipboard->size = size;
break;
}
clipboard->formatId = formatId;
clipboard->sequenceNumber++;
return TRUE;
}
UINT64 ClipboardGetOwner(wClipboard* clipboard)
{
if (!clipboard)
return 0;
return clipboard->ownerId;
}
void ClipboardSetOwner(wClipboard* clipboard, UINT64 ownerId)
{
if (!clipboard)
return;
clipboard->ownerId = ownerId;
}
wClipboardDelegate* ClipboardGetDelegate(wClipboard* clipboard)
{
if (!clipboard)
return nullptr;
return &clipboard->delegate;
}
static void ClipboardInitLocalFileSubsystem(wClipboard* clipboard)
{
/*
* There can be only one local file subsystem active.
* Return as soon as initialization succeeds.
*/
if (ClipboardInitSyntheticFileSubsystem(clipboard))
{
WLog_DBG(TAG, "initialized synthetic local file subsystem");
return;
}
else
{
WLog_WARN(TAG, "failed to initialize synthetic local file subsystem");
}
WLog_INFO(TAG, "failed to initialize local file subsystem, file transfer not available");
}
wClipboard* ClipboardCreate(void)
{
wClipboard* clipboard = (wClipboard*)calloc(1, sizeof(wClipboard));
if (!clipboard)
return nullptr;
clipboard->nextFormatId = 0xC000;
clipboard->sequenceNumber = 0;
if (!InitializeCriticalSectionAndSpinCount(&(clipboard->lock), 4000))
goto fail;
clipboard->numFormats = 0;
clipboard->maxFormats = 64;
clipboard->formats = (wClipboardFormat*)calloc(clipboard->maxFormats, sizeof(wClipboardFormat));
if (!clipboard->formats)
goto fail;
if (!ClipboardInitFormats(clipboard))
goto fail;
clipboard->delegate.clipboard = clipboard;
ClipboardInitLocalFileSubsystem(clipboard);
return clipboard;
fail:
ClipboardDestroy(clipboard);
return nullptr;
}
void ClipboardDestroy(wClipboard* clipboard)
{
if (!clipboard)
return;
ArrayList_Free(clipboard->localFiles);
clipboard->localFiles = nullptr;
ClipboardUninitFormats(clipboard);
free(clipboard->data);
clipboard->data = nullptr;
clipboard->size = 0;
clipboard->numFormats = 0;
free(clipboard->formats);
DeleteCriticalSection(&(clipboard->lock));
free(clipboard);
}
static BOOL is_dos_drive(const char* path, size_t len)
{
if (len < 2)
return FALSE;
WINPR_ASSERT(path);
if (path[1] == ':' || path[1] == '|')
{
if (((path[0] >= 'A') && (path[0] <= 'Z')) || ((path[0] >= 'a') && (path[0] <= 'z')))
return TRUE;
}
return FALSE;
}
char* parse_uri_to_local_file(const char* uri, size_t uri_len)
{
// URI is specified by RFC 8089: https://datatracker.ietf.org/doc/html/rfc8089
const char prefix[] = "file:";
const char prefixTraditional[] = "file://";
const char* localName = nullptr;
size_t localLen = 0;
char* buffer = nullptr;
const size_t prefixLen = strnlen(prefix, sizeof(prefix));
const size_t prefixTraditionalLen = strnlen(prefixTraditional, sizeof(prefixTraditional));
WINPR_ASSERT(uri || (uri_len == 0));
WLog_VRB(TAG, "processing URI: %.*s", WINPR_ASSERTING_INT_CAST(int, uri_len), uri);
if ((uri_len <= prefixLen) || strncmp(uri, prefix, prefixLen) != 0)
{
WLog_ERR(TAG, "non-'file:' URI schemes are not supported");
return nullptr;
}
do
{
/* https://datatracker.ietf.org/doc/html/rfc8089#appendix-F
* - The minimal representation of a local file in a DOS- or Windows-
* based environment with no authority field and an absolute path
* that begins with a drive letter.
*
* "file:c:/path/to/file"
*
* - Regular DOS or Windows file URIs with vertical line characters in
* the drive letter construct.
*
* "file:c|/path/to/file"
*
*/
if (uri[prefixLen] != '/')
{
if (is_dos_drive(&uri[prefixLen], uri_len - prefixLen))
{
// Dos and Windows file URI
localName = &uri[prefixLen];
localLen = uri_len - prefixLen;
break;
}
else
{
WLog_ERR(TAG, "URI format are not supported: %s", uri);
return nullptr;
}
}
/*
* - The minimal representation of a local file with no authority field
* and an absolute path that begins with a slash "/". For example:
*
* "file:/path/to/file"
*
*/
else if ((uri_len > prefixLen + 1) && (uri[prefixLen + 1] != '/'))
{
if (is_dos_drive(&uri[prefixLen + 1], uri_len - prefixLen - 1))
{
// Dos and Windows file URI
localName = (uri + prefixLen + 1);
localLen = uri_len - prefixLen - 1;
}
else
{
localName = &uri[prefixLen];
localLen = uri_len - prefixLen;
}
break;
}
/*
* - A traditional file URI for a local file with an empty authority.
*
* "file:///path/to/file"
*/
if ((uri_len < prefixTraditionalLen) ||
strncmp(uri, prefixTraditional, prefixTraditionalLen) != 0)
{
WLog_ERR(TAG, "non-'file:' URI schemes are not supported");
return nullptr;
}
localName = &uri[prefixTraditionalLen];
localLen = uri_len - prefixTraditionalLen;
if (localLen < 1)
{
WLog_ERR(TAG, "empty 'file:' URI schemes are not supported");
return nullptr;
}
/*
* "file:///c:/path/to/file"
* "file:///c|/path/to/file"
*/
if (localName[0] != '/')
{
WLog_ERR(TAG, "URI format are not supported: %s", uri);
return nullptr;
}
if (is_dos_drive(&localName[1], localLen - 1))
{
localName++;
localLen--;
}
} while (0);
buffer = winpr_str_url_decode(localName, localLen);
if (buffer)
{
if (buffer[1] == '|' &&
((buffer[0] >= 'A' && buffer[0] <= 'Z') || (buffer[0] >= 'a' && buffer[0] <= 'z')))
buffer[1] = ':';
return buffer;
}
return nullptr;
}

View File

@@ -0,0 +1,77 @@
/**
* WinPR: Windows Portable Runtime
* Clipboard Functions
*
* Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_CLIPBOARD_PRIVATE_H
#define WINPR_CLIPBOARD_PRIVATE_H
#include <winpr/winpr.h>
#include <winpr/clipboard.h>
#include <winpr/collections.h>
typedef struct
{
UINT32 syntheticId;
CLIPBOARD_SYNTHESIZE_FN pfnSynthesize;
} wClipboardSynthesizer;
typedef struct
{
UINT32 formatId;
char* formatName;
UINT32 numSynthesizers;
wClipboardSynthesizer* synthesizers;
} wClipboardFormat;
struct s_wClipboard
{
UINT64 ownerId;
/* clipboard formats */
UINT32 numFormats;
UINT32 maxFormats;
UINT32 nextFormatId;
wClipboardFormat* formats;
/* clipboard data */
UINT32 size;
void* data;
UINT32 formatId;
UINT32 sequenceNumber;
/* clipboard file handling */
wArrayList* localFiles;
UINT32 fileListSequenceNumber;
wClipboardDelegate delegate;
CRITICAL_SECTION lock;
};
WINPR_LOCAL BOOL ClipboardInitSynthesizers(wClipboard* clipboard);
WINPR_LOCAL char* parse_uri_to_local_file(const char* uri, size_t uri_len);
extern const char* const mime_text_plain;
#endif /* WINPR_CLIPBOARD_PRIVATE_H */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,27 @@
/**
* WinPR: Windows Portable Runtime
* Clipboard Functions: POSIX file handling
*
* Copyright 2017 Alexei Lozovsky <a.lozovsky@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_CLIPBOARD_POSIX_H
#define WINPR_CLIPBOARD_POSIX_H
#include <winpr/clipboard.h>
BOOL ClipboardInitSyntheticFileSubsystem(wClipboard* clipboard);
#endif /* WINPR_CLIPBOARD_POSIX_H */

View File

@@ -0,0 +1,40 @@
set(MODULE_NAME "TestClipboard")
set(MODULE_PREFIX "TEST_CLIPBOARD")
disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR})
set(DRIVER ${MODULE_NAME}.c)
set(TESTS TestClipboardFormats.c)
if(BUILD_TESTING_INTERNAL)
list(APPEND TESTS TestUri.c)
endif()
set(TEST_CLIP_PNG "${CMAKE_SOURCE_DIR}/resources/FreeRDP_Icon.png")
file(TO_NATIVE_PATH "${TEST_CLIP_PNG}" TEST_CLIP_PNG)
set(TEST_CLIP_BMP "${CMAKE_SOURCE_DIR}/resources/FreeRDP_Install.bmp")
file(TO_NATIVE_PATH "${TEST_CLIP_BMP}" TEST_CLIP_BMP)
if(WIN32)
string(REPLACE "\\" "\\\\" TEST_CLIP_PNG "${TEST_CLIP_PNG}")
string(REPLACE "\\" "\\\\" TEST_CLIP_BMP "${TEST_CLIP_BMP}")
endif()
add_compile_definitions(TEST_CLIP_BMP="${TEST_CLIP_BMP}")
add_compile_definitions(TEST_CLIP_PNG="${TEST_CLIP_PNG}")
create_test_sourcelist(SRCS ${DRIVER} ${TESTS})
add_executable(${MODULE_NAME} ${SRCS})
target_link_libraries(${MODULE_NAME} winpr)
set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}")
foreach(test ${TESTS})
get_filename_component(TestName ${test} NAME_WE)
add_test(${TestName} ${TESTING_OUTPUT_DIRECTORY}/${MODULE_NAME} ${TestName})
endforeach()
set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "WinPR/Test")

View File

@@ -0,0 +1,243 @@
#include <winpr/crt.h>
#include <winpr/print.h>
#include <winpr/image.h>
#include <winpr/clipboard.h>
int TestClipboardFormats(int argc, char* argv[])
{
int rc = -1;
UINT32 count = 0;
UINT32* pFormatIds = nullptr;
const char* formatName = nullptr;
wClipboard* clipboard = nullptr;
UINT32 utf8StringFormatId = 0;
WINPR_UNUSED(argc);
WINPR_UNUSED(argv);
clipboard = ClipboardCreate();
if (!clipboard)
return -1;
const char* mime_types[] = { "text/html", "text/html", "image/bmp",
"image/png", "image/webp", "image/jpeg" };
for (size_t x = 0; x < ARRAYSIZE(mime_types); x++)
{
const char* mime = mime_types[x];
UINT32 id = ClipboardRegisterFormat(clipboard, mime);
(void)fprintf(stderr, "ClipboardRegisterFormat(%s) -> 0x%08" PRIx32 "\n", mime, id);
if (id == 0)
goto fail;
}
utf8StringFormatId = ClipboardRegisterFormat(clipboard, "UTF8_STRING");
pFormatIds = nullptr;
count = ClipboardGetRegisteredFormatIds(clipboard, &pFormatIds);
for (UINT32 index = 0; index < count; index++)
{
UINT32 formatId = pFormatIds[index];
formatName = ClipboardGetFormatName(clipboard, formatId);
(void)fprintf(stderr, "Format: 0x%08" PRIX32 " %s\n", formatId, formatName);
}
free(pFormatIds);
if (1)
{
BOOL bSuccess = 0;
UINT32 SrcSize = 0;
UINT32 DstSize = 0;
const char pSrcData[] = "this is a test string";
char* pDstData = nullptr;
SrcSize = (UINT32)(strnlen(pSrcData, ARRAYSIZE(pSrcData)) + 1);
bSuccess = ClipboardSetData(clipboard, utf8StringFormatId, pSrcData, SrcSize);
(void)fprintf(stderr, "ClipboardSetData: %" PRId32 "\n", bSuccess);
DstSize = 0;
pDstData = (char*)ClipboardGetData(clipboard, utf8StringFormatId, &DstSize);
(void)fprintf(stderr, "ClipboardGetData: %s\n", pDstData);
free(pDstData);
}
if (1)
{
UINT32 DstSize = 0;
char* pSrcData = nullptr;
WCHAR* pDstData = nullptr;
DstSize = 0;
pDstData = (WCHAR*)ClipboardGetData(clipboard, CF_UNICODETEXT, &DstSize);
pSrcData = ConvertWCharNToUtf8Alloc(pDstData, DstSize / sizeof(WCHAR), nullptr);
(void)fprintf(stderr, "ClipboardGetData (synthetic): %s\n", pSrcData);
free(pDstData);
free(pSrcData);
}
pFormatIds = nullptr;
count = ClipboardGetFormatIds(clipboard, &pFormatIds);
for (UINT32 index = 0; index < count; index++)
{
UINT32 formatId = pFormatIds[index];
formatName = ClipboardGetFormatName(clipboard, formatId);
(void)fprintf(stderr, "Format: 0x%08" PRIX32 " %s\n", formatId, formatName);
}
if (1)
{
const char* name = TEST_CLIP_BMP;
BOOL bSuccess = FALSE;
UINT32 idBmp = ClipboardRegisterFormat(clipboard, "image/bmp");
wImage* img = winpr_image_new();
if (!img)
goto fail;
if (winpr_image_read(img, name) <= 0)
{
winpr_image_free(img, TRUE);
goto fail;
}
size_t bmpsize = 0;
void* data = winpr_image_write_buffer(img, WINPR_IMAGE_BITMAP, &bmpsize);
bSuccess = ClipboardSetData(clipboard, idBmp, data, bmpsize);
(void)fprintf(stderr, "ClipboardSetData: %" PRId32 "\n", bSuccess);
free(data);
winpr_image_free(img, TRUE);
if (!bSuccess)
goto fail;
{
UINT32 id = CF_DIB;
UINT32 DstSize = 0;
void* pDstData = ClipboardGetData(clipboard, id, &DstSize);
(void)fprintf(stderr, "ClipboardGetData: [CF_DIB] %p [%" PRIu32 "]\n", pDstData,
DstSize);
if (!pDstData)
goto fail;
bSuccess = ClipboardSetData(clipboard, id, pDstData, DstSize);
free(pDstData);
if (!bSuccess)
goto fail;
}
{
const uint32_t id = ClipboardGetFormatId(clipboard, "HTML Format");
UINT32 DstSize = 0;
void* pDstData = ClipboardGetData(clipboard, id, &DstSize);
if (!pDstData)
goto fail;
{
FILE* fp = fopen("test.html", "w");
if (fp)
{
(void)fwrite(pDstData, 1, DstSize, fp);
(void)fclose(fp);
}
}
free(pDstData);
}
{
UINT32 id = ClipboardRegisterFormat(clipboard, "image/bmp");
UINT32 DstSize = 0;
void* pDstData = ClipboardGetData(clipboard, id, &DstSize);
(void)fprintf(stderr, "ClipboardGetData: [image/bmp] %p [%" PRIu32 "]\n", pDstData,
DstSize);
if (!pDstData)
goto fail;
free(pDstData);
if (DstSize != bmpsize)
goto fail;
}
#if defined(WINPR_UTILS_IMAGE_PNG)
{
UINT32 id = ClipboardRegisterFormat(clipboard, "image/png");
UINT32 DstSize = 0;
void* pDstData = ClipboardGetData(clipboard, id, &DstSize);
(void)fprintf(stderr, "ClipboardGetData: [image/png] %p\n", pDstData);
if (!pDstData)
goto fail;
free(pDstData);
}
{
const char* name = TEST_CLIP_PNG;
BOOL bSuccess = FALSE;
UINT32 idBmp = ClipboardRegisterFormat(clipboard, "image/png");
wImage* img = winpr_image_new();
if (!img)
goto fail;
if (winpr_image_read(img, name) <= 0)
{
winpr_image_free(img, TRUE);
goto fail;
}
size_t bmpsize = 0;
void* data = winpr_image_write_buffer(img, WINPR_IMAGE_PNG, &bmpsize);
bSuccess = ClipboardSetData(clipboard, idBmp, data, bmpsize);
(void)fprintf(stderr, "ClipboardSetData: %" PRId32 "\n", bSuccess);
free(data);
winpr_image_free(img, TRUE);
if (!bSuccess)
goto fail;
}
{
UINT32 id = CF_DIB;
UINT32 DstSize = 0;
void* pDstData = ClipboardGetData(clipboard, id, &DstSize);
(void)fprintf(stderr, "ClipboardGetData: [CF_DIB] %p [%" PRIu32 "]\n", pDstData,
DstSize);
if (!pDstData)
goto fail;
bSuccess = ClipboardSetData(clipboard, id, pDstData, DstSize);
free(pDstData);
if (!bSuccess)
goto fail;
}
#endif
#if defined(WINPR_UTILS_IMAGE_WEBP)
{
UINT32 id = ClipboardRegisterFormat(clipboard, "image/webp");
UINT32 DstSize = 0;
void* pDstData = ClipboardGetData(clipboard, id, &DstSize);
(void)fprintf(stderr, "ClipboardGetData: [image/webp] %p\n", pDstData);
if (!pDstData)
goto fail;
free(pDstData);
}
#endif
#if defined(WINPR_UTILS_IMAGE_JPEG)
{
UINT32 id = ClipboardRegisterFormat(clipboard, "image/jpeg");
UINT32 DstSize = 0;
void* pDstData = ClipboardGetData(clipboard, id, &DstSize);
(void)fprintf(stderr, "ClipboardGetData: [image/jpeg] %p\n", pDstData);
if (!pDstData)
goto fail;
free(pDstData);
}
#endif
}
rc = 0;
fail:
free(pFormatIds);
ClipboardDestroy(clipboard);
return rc;
}

View File

@@ -0,0 +1,69 @@
#include <stdio.h>
#include <string.h>
#include <memory.h>
#include <stdlib.h>
#include <winpr/winpr.h>
#include "winpr/wlog.h"
#include "../clipboard.h"
#define WINPR_TAG(tag) "com.winpr." tag
#define TAG WINPR_TAG("clipboard.posix")
int TestUri(int argc, char* argv[])
{
int nRet = 0;
const char* input[] = { /*uri, file or nullptr*/
"file://root/a.txt",
nullptr,
"file:a.txt",
nullptr,
"file:///c:/windows/a.txt",
"c:/windows/a.txt",
"file:c:/windows/a.txt",
"c:/windows/a.txt",
"file:c|/windows/a.txt",
"c:/windows/a.txt",
"file:///root/a.txt",
"/root/a.txt",
"file:/root/a.txt",
"/root/a.txt"
};
const size_t nLen = ARRAYSIZE(input);
WINPR_UNUSED(argc);
WINPR_UNUSED(argv);
printf("input length:%" PRIuz "\n", nLen / 2);
for (size_t i = 0; i < nLen; i += 2)
{
const char* in = input[i];
const char* cmp = input[i + 1];
int bTest = 0;
char* name = parse_uri_to_local_file(in, strlen(in));
if (name && cmp)
{
bTest = !strcmp(name, cmp);
if (!bTest)
{
printf("Test error: input: %s; Expected value: %s; output: %s\n", in, cmp, name);
nRet++;
}
free(name);
}
else
{
if (cmp)
{
printf("Test error: input: %s; Expected value: %s; output: %s\n", in, cmp, name);
nRet++;
}
}
}
printf("TestUri return value: %d\n", nRet);
return nRet;
}

View File

@@ -0,0 +1,49 @@
# WinPR: Windows Portable Runtime
# libwinpr-comm cmake build script
#
# Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set(MODULE_NAME "winpr-comm")
set(MODULE_PREFIX "WINPR_COMM")
if(NOT WIN32)
set(${MODULE_PREFIX}_SRCS comm.c comm.h)
if(NOT EMSCRIPTEN AND NOT APPLE)
winpr_definition_add(WINPR_HAVE_SERIAL_SUPPORT)
list(
APPEND
${MODULE_PREFIX}_SRCS
comm_io.c
comm_ioctl.c
comm_ioctl.h
comm_serial_sys.c
comm_serial_sys.h
comm_sercx_sys.c
comm_sercx_sys.h
comm_sercx2_sys.c
comm_sercx2_sys.h
)
else()
list(APPEND ${MODULE_PREFIX}_SRCS comm_ioctl_dummy.c comm_ioctl.h)
endif()
winpr_module_add(${${MODULE_PREFIX}_SRCS})
if(NOT EMSCRIPTEN)
if(BUILD_TESTING_INTERNAL AND BUILD_COMM_TESTS)
add_subdirectory(test)
endif()
endif()
endif()

View File

@@ -0,0 +1,9 @@
set(MINWIN_LAYER "1")
set(MINWIN_GROUP "core")
set(MINWIN_MAJOR_VERSION "1")
set(MINWIN_MINOR_VERSION "0")
set(MINWIN_SHORT_NAME "comm")
set(MINWIN_LONG_NAME "Serial Communication API")
set(MODULE_LIBRARY_NAME
"api-ms-win-${MINWIN_GROUP}-${MINWIN_SHORT_NAME}-l${MINWIN_LAYER}-${MINWIN_MAJOR_VERSION}-${MINWIN_MINOR_VERSION}"
)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,134 @@
/**
* WinPR: Windows Portable Runtime
* Serial Communication API
*
* Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_COMM_PRIVATE_H
#define WINPR_COMM_PRIVATE_H
#if defined(__linux__)
#define WINPR_HAVE_COMM_COUNTERS
#include <linux/serial.h>
#endif
#include <winpr/comm.h>
#include "../handle/handle.h"
#include <winpr/config.h>
#if defined(WINPR_HAVE_SYS_EVENTFD_H)
#include <sys/eventfd.h>
#endif
struct winpr_comm
{
WINPR_HANDLE common;
int fd;
int fd_read;
int fd_read_event; /* as of today, only used by _purge() */
CRITICAL_SECTION ReadLock;
int fd_write;
int fd_write_event; /* as of today, only used by _purge() */
CRITICAL_SECTION WriteLock;
/* permissive mode on errors. If TRUE (default is FALSE)
* CommDeviceIoControl always return TRUE.
*
* Not all features are supported yet and an error is then returned when
* an application turns them on (e.g: i/o buffers > 4096). It appeared
* though that devices and applications can be still functional on such
* errors.
*
* see also: comm_ioctl.c
*
* FIXME: getting rid of this flag once all features supported.
*/
BOOL permissive;
SERIAL_DRIVER_ID serverSerialDriverId;
COMMTIMEOUTS timeouts;
CRITICAL_SECTION
EventsLock; /* protects counters, WaitEventMask and PendingEvents */
#if defined(WINPR_HAVE_COMM_COUNTERS)
struct serial_icounter_struct counters;
#endif
ULONG WaitEventMask;
ULONG PendingEvents;
BYTE eventChar;
/* NB: CloseHandle() has to free resources */
ULONG XOnLimit;
ULONG XOffLimit;
#if defined(WINPR_HAVE_COMM_COUNTERS)
BOOL TIOCGICOUNTSupported;
#endif
};
typedef struct winpr_comm WINPR_COMM;
#define SERIAL_EV_RXCHAR 0x0001
#define SERIAL_EV_RXFLAG 0x0002
#define SERIAL_EV_TXEMPTY 0x0004
#define SERIAL_EV_CTS 0x0008
#define SERIAL_EV_DSR 0x0010
#define SERIAL_EV_RLSD 0x0020
#define SERIAL_EV_BREAK 0x0040
#define SERIAL_EV_ERR 0x0080
#define SERIAL_EV_RING 0x0100
#define SERIAL_EV_PERR 0x0200
#define SERIAL_EV_RX80FULL 0x0400
#define SERIAL_EV_EVENT1 0x0800
#define SERIAL_EV_EVENT2 0x1000
#define SERIAL_EV_WINPR_WAITING 0x4000 /* bit today unused by other SERIAL_EV_* */
#define SERIAL_EV_WINPR_STOP 0x8000 /* bit today unused by other SERIAL_EV_* */
#define WINPR_PURGE_TXABORT 0x00000001 /* abort pending transmission */
#define WINPR_PURGE_RXABORT 0x00000002 /* abort pending reception */
#define CommLog_Print(level, ...) CommLog_PrintEx(level, __FILE__, __LINE__, __func__, __VA_ARGS__)
WINPR_ATTR_FORMAT_ARG(5, 6)
void CommLog_PrintEx(DWORD level, const char* file, size_t line, const char* fkt,
WINPR_FORMAT_ARG const char* fmt, ...);
BOOL CommIsHandled(HANDLE handle);
BOOL CommIsHandleValid(HANDLE handle);
BOOL CommCloseHandle(HANDLE handle);
const HANDLE_CREATOR* GetCommHandleCreator(void);
#define CommIoCtl(pComm, ctl, data) \
CommIoCtl_int((pComm), (ctl), (data), __FILE__, __func__, __LINE__)
BOOL CommIoCtl_int(WINPR_COMM* pComm, unsigned long int ctl, void* data, const char* file,
const char* fkt, size_t line);
BOOL CommUpdateIOCount(HANDLE handle, BOOL checkSupportStatus);
const char* CommSerialEvString(ULONG status, char* buffer, size_t size);
#if defined(WINPR_HAVE_SYS_EVENTFD_H)
#ifndef WITH_EVENTFD_READ_WRITE
int eventfd_read(int fd, eventfd_t* value);
int eventfd_write(int fd, eventfd_t value);
#endif
#endif
#endif /* WINPR_COMM_PRIVATE_H */

View File

@@ -0,0 +1,567 @@
/**
* WinPR: Windows Portable Runtime
* Serial Communication API
*
* Copyright 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <winpr/config.h>
#include <winpr/assert.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <winpr/io.h>
#include <winpr/wlog.h>
#include <winpr/wtypes.h>
#include "comm.h"
BOOL _comm_set_permissive(HANDLE hDevice, BOOL permissive)
{
WINPR_COMM* pComm = (WINPR_COMM*)hDevice;
if (!CommIsHandled(hDevice))
return FALSE;
pComm->permissive = permissive;
return TRUE;
}
/* Computes VTIME in deciseconds from Ti in milliseconds */
static UCHAR svtime(ULONG Ti)
{
/* FIXME: look for an equivalent math function otherwise let
* do the compiler do the optimization */
if (Ti == 0)
return 0;
else if (Ti < 100)
return 1;
else if (Ti > 25500)
return 255; /* 0xFF */
else
return (UCHAR)(Ti / 100);
}
/**
* ERRORS:
* ERROR_INVALID_HANDLE
* ERROR_NOT_SUPPORTED
* ERROR_INVALID_PARAMETER
* ERROR_TIMEOUT
* ERROR_IO_DEVICE
* ERROR_BAD_DEVICE
*/
BOOL CommReadFile(HANDLE hDevice, LPVOID lpBuffer, DWORD nNumberOfBytesToRead,
LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
WINPR_COMM* pComm = (WINPR_COMM*)hDevice;
int biggestFd = -1;
fd_set read_set;
int nbFds = 0;
COMMTIMEOUTS* pTimeouts = nullptr;
UCHAR vmin = 0;
UCHAR vtime = 0;
LONGLONG Tmax = 0;
struct timeval tmaxTimeout;
struct timeval* pTmaxTimeout = nullptr;
struct termios currentTermios;
EnterCriticalSection(&pComm->ReadLock); /* KISSer by the function's beginning */
if (!CommIsHandled(hDevice))
goto return_false;
if (lpOverlapped != nullptr)
{
SetLastError(ERROR_NOT_SUPPORTED);
goto return_false;
}
if (lpNumberOfBytesRead == nullptr)
{
SetLastError(
ERROR_INVALID_PARAMETER); /* since we doesn't support lpOverlapped != nullptr */
goto return_false;
}
*lpNumberOfBytesRead = 0; /* will be adjusted if required ... */
if (nNumberOfBytesToRead <= 0) /* N */
{
goto return_true; /* FIXME: or FALSE? */
}
if (tcgetattr(pComm->fd, &currentTermios) < 0)
{
SetLastError(ERROR_IO_DEVICE);
goto return_false;
}
if (currentTermios.c_lflag & ICANON)
{
CommLog_Print(WLOG_WARN, "Canonical mode not supported"); /* the timeout could not be set */
SetLastError(ERROR_NOT_SUPPORTED);
goto return_false;
}
/* http://msdn.microsoft.com/en-us/library/hh439614%28v=vs.85%29.aspx
* http://msdn.microsoft.com/en-us/library/windows/hardware/hh439614%28v=vs.85%29.aspx
*
* ReadIntervalTimeout | ReadTotalTimeoutMultiplier | ReadTotalTimeoutConstant | VMIN | VTIME |
* TMAX | 0 | 0 | 0 | N | 0 |
* INDEF | Blocks for N bytes available. 0< Ti <MAXULONG | 0 | 0 |
* N | Ti | INDEF | Blocks on first byte, then use Ti between bytes. MAXULONG | 0 | 0
* | 0 | 0 | 0 | Returns immediately with bytes available (don't block) MAXULONG |
* MAXULONG | 0< Tc <MAXULONG | N | 0 | Tc | Blocks on first byte
* during Tc or returns immediately with bytes available MAXULONG | m |
* MAXULONG | | Invalid 0 | m | 0< Tc
* <MAXULONG | N | 0 | Tmax | Blocks on first byte during Tmax or returns
* immediately with bytes available 0< Ti <MAXULONG | m | 0<
* Tc <MAXULONG | N | Ti | Tmax | Blocks on first byte, then use Ti between bytes.
* Tmax is used for the whole system call.
*/
/* NB: timeouts are in milliseconds, VTIME are in deciseconds and is an unsigned char */
/* FIXME: double check whether open(pComm->fd_read_event, O_NONBLOCK) doesn't conflict with
* above use cases */
pTimeouts = &(pComm->timeouts);
if ((pTimeouts->ReadIntervalTimeout == MAXULONG) &&
(pTimeouts->ReadTotalTimeoutConstant == MAXULONG))
{
CommLog_Print(
WLOG_WARN,
"ReadIntervalTimeout and ReadTotalTimeoutConstant cannot be both set to MAXULONG");
SetLastError(ERROR_INVALID_PARAMETER);
goto return_false;
}
/* VMIN */
if ((pTimeouts->ReadIntervalTimeout == MAXULONG) &&
(pTimeouts->ReadTotalTimeoutMultiplier == 0) && (pTimeouts->ReadTotalTimeoutConstant == 0))
{
vmin = 0;
}
else
{
/* N */
/* vmin = nNumberOfBytesToRead < 256 ? nNumberOfBytesToRead : 255;*/ /* 0xFF */
/* NB: we might wait endlessly with vmin=N, prefer to
* force vmin=1 and return with bytes
* available. FIXME: is a feature disarded here? */
vmin = 1;
}
/* VTIME */
if ((pTimeouts->ReadIntervalTimeout > 0) && (pTimeouts->ReadIntervalTimeout < MAXULONG))
{
/* Ti */
vtime = svtime(pTimeouts->ReadIntervalTimeout);
}
/* TMAX */
pTmaxTimeout = &tmaxTimeout;
if ((pTimeouts->ReadIntervalTimeout == MAXULONG) &&
(pTimeouts->ReadTotalTimeoutMultiplier == MAXULONG))
{
/* Tc */
Tmax = pTimeouts->ReadTotalTimeoutConstant;
}
else
{
/* Tmax */
Tmax = 1ll * nNumberOfBytesToRead * pTimeouts->ReadTotalTimeoutMultiplier +
1ll * pTimeouts->ReadTotalTimeoutConstant;
/* INDEFinitely */
if ((Tmax == 0) && (pTimeouts->ReadIntervalTimeout < MAXULONG) &&
(pTimeouts->ReadTotalTimeoutMultiplier == 0))
pTmaxTimeout = nullptr;
}
if ((currentTermios.c_cc[VMIN] != vmin) || (currentTermios.c_cc[VTIME] != vtime))
{
currentTermios.c_cc[VMIN] = vmin;
currentTermios.c_cc[VTIME] = vtime;
if (tcsetattr(pComm->fd, TCSANOW, &currentTermios) < 0)
{
CommLog_Print(WLOG_WARN,
"CommReadFile failure, could not apply new timeout values: VMIN=%" PRIu8
", VTIME=%" PRIu8 "",
vmin, vtime);
SetLastError(ERROR_IO_DEVICE);
goto return_false;
}
}
/* wait indefinitely if pTmaxTimeout is nullptr */
if (pTmaxTimeout != nullptr)
{
ZeroMemory(pTmaxTimeout, sizeof(struct timeval));
if (Tmax > 0) /* return immdiately if Tmax == 0 */
{
pTmaxTimeout->tv_sec = Tmax / 1000; /* s */
pTmaxTimeout->tv_usec = (Tmax % 1000) * 1000; /* us */
}
}
/* FIXME: had expected eventfd_write() to return EAGAIN when
* there is no eventfd_read() but this not the case. */
/* discard a possible and no more relevant event */
#if defined(WINPR_HAVE_SYS_EVENTFD_H)
{
eventfd_t val = 0;
(void)eventfd_read(pComm->fd_read_event, &val);
}
#endif
biggestFd = pComm->fd_read;
if (pComm->fd_read_event > biggestFd)
biggestFd = pComm->fd_read_event;
FD_ZERO(&read_set);
WINPR_ASSERT(pComm->fd_read_event < FD_SETSIZE);
WINPR_ASSERT(pComm->fd_read < FD_SETSIZE);
FD_SET(pComm->fd_read_event, &read_set);
FD_SET(pComm->fd_read, &read_set);
nbFds = select(biggestFd + 1, &read_set, nullptr, nullptr, pTmaxTimeout);
if (nbFds < 0)
{
char ebuffer[256] = WINPR_C_ARRAY_INIT;
CommLog_Print(WLOG_WARN, "select() failure, errno=[%d] %s\n", errno,
winpr_strerror(errno, ebuffer, sizeof(ebuffer)));
SetLastError(ERROR_IO_DEVICE);
goto return_false;
}
if (nbFds == 0)
{
/* timeout */
SetLastError(ERROR_TIMEOUT);
goto return_false;
}
/* read_set */
if (FD_ISSET(pComm->fd_read_event, &read_set))
{
#if defined(WINPR_HAVE_SYS_EVENTFD_H)
eventfd_t event = 0;
if (eventfd_read(pComm->fd_read_event, &event) < 0)
{
if (errno == EAGAIN)
{
WINPR_ASSERT(FALSE); /* not quite sure this should ever happen */
/* keep on */
}
else
{
char ebuffer[256] = WINPR_C_ARRAY_INIT;
CommLog_Print(WLOG_WARN,
"unexpected error on reading fd_read_event, errno=[%d] %s\n", errno,
winpr_strerror(errno, ebuffer, sizeof(ebuffer)));
/* FIXME: goto return_false ? */
}
WINPR_ASSERT(errno == EAGAIN);
}
if (event == WINPR_PURGE_RXABORT)
{
SetLastError(ERROR_CANCELLED);
goto return_false;
}
WINPR_ASSERT(event == WINPR_PURGE_RXABORT); /* no other expected event so far */
#endif
}
if (FD_ISSET(pComm->fd_read, &read_set))
{
ssize_t nbRead = read(pComm->fd_read, lpBuffer, nNumberOfBytesToRead);
if ((nbRead < 0) || (nbRead > nNumberOfBytesToRead))
{
char ebuffer[256] = WINPR_C_ARRAY_INIT;
CommLog_Print(WLOG_WARN,
"CommReadFile failed, ReadIntervalTimeout=%" PRIu32
", ReadTotalTimeoutMultiplier=%" PRIu32
", ReadTotalTimeoutConstant=%" PRIu32 " VMIN=%u, VTIME=%u",
pTimeouts->ReadIntervalTimeout, pTimeouts->ReadTotalTimeoutMultiplier,
pTimeouts->ReadTotalTimeoutConstant, currentTermios.c_cc[VMIN],
currentTermios.c_cc[VTIME]);
CommLog_Print(
WLOG_WARN, "CommReadFile failed, nNumberOfBytesToRead=%" PRIu32 ", errno=[%d] %s",
nNumberOfBytesToRead, errno, winpr_strerror(errno, ebuffer, sizeof(ebuffer)));
if (errno == EAGAIN)
{
/* keep on */
goto return_true; /* expect a read-loop to be implemented on the server side */
}
else if (errno == EBADF)
{
SetLastError(ERROR_BAD_DEVICE); /* STATUS_INVALID_DEVICE_REQUEST */
goto return_false;
}
else
{
WINPR_ASSERT(FALSE);
SetLastError(ERROR_IO_DEVICE);
goto return_false;
}
}
if (nbRead == 0)
{
/* termios timeout */
SetLastError(ERROR_TIMEOUT);
goto return_false;
}
*lpNumberOfBytesRead = WINPR_ASSERTING_INT_CAST(UINT32, nbRead);
EnterCriticalSection(&pComm->EventsLock);
if (pComm->PendingEvents & SERIAL_EV_WINPR_WAITING)
{
if (pComm->eventChar != '\0' &&
memchr(lpBuffer, pComm->eventChar, WINPR_ASSERTING_INT_CAST(size_t, nbRead)))
pComm->PendingEvents |= SERIAL_EV_RXCHAR;
}
LeaveCriticalSection(&pComm->EventsLock);
goto return_true;
}
WINPR_ASSERT(FALSE);
*lpNumberOfBytesRead = 0;
return_false:
LeaveCriticalSection(&pComm->ReadLock);
return FALSE;
return_true:
LeaveCriticalSection(&pComm->ReadLock);
return TRUE;
}
/**
* ERRORS:
* ERROR_INVALID_HANDLE
* ERROR_NOT_SUPPORTED
* ERROR_INVALID_PARAMETER
* ERROR_BAD_DEVICE
*/
BOOL CommWriteFile(HANDLE hDevice, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped)
{
WINPR_COMM* pComm = (WINPR_COMM*)hDevice;
struct timeval tmaxTimeout;
struct timeval* pTmaxTimeout = nullptr;
EnterCriticalSection(&pComm->WriteLock); /* KISSer by the function's beginning */
if (!CommIsHandled(hDevice))
goto return_false;
if (lpOverlapped != nullptr)
{
SetLastError(ERROR_NOT_SUPPORTED);
goto return_false;
}
if (lpNumberOfBytesWritten == nullptr)
{
SetLastError(
ERROR_INVALID_PARAMETER); /* since we doesn't support lpOverlapped != nullptr */
goto return_false;
}
*lpNumberOfBytesWritten = 0; /* will be adjusted if required ... */
if (nNumberOfBytesToWrite <= 0)
{
goto return_true; /* FIXME: or FALSE? */
}
/* FIXME: had expected eventfd_write() to return EAGAIN when
* there is no eventfd_read() but this not the case. */
/* discard a possible and no more relevant event */
#if defined(WINPR_HAVE_SYS_EVENTFD_H)
{
eventfd_t val = 0;
(void)eventfd_read(pComm->fd_write_event, &val);
}
#endif
{
/* ms */
const LONGLONG Tmax =
1ll * nNumberOfBytesToWrite * pComm->timeouts.WriteTotalTimeoutMultiplier +
1ll * pComm->timeouts.WriteTotalTimeoutConstant;
/* NB: select() may update the timeout argument to indicate
* how much time was left. Keep the timeout variable out of
* the while() */
pTmaxTimeout = &tmaxTimeout;
ZeroMemory(pTmaxTimeout, sizeof(struct timeval));
if (Tmax > 0)
{
pTmaxTimeout->tv_sec = Tmax / 1000; /* s */
pTmaxTimeout->tv_usec = (Tmax % 1000) * 1000; /* us */
}
else if ((pComm->timeouts.WriteTotalTimeoutMultiplier == 0) &&
(pComm->timeouts.WriteTotalTimeoutConstant == 0))
{
pTmaxTimeout = nullptr;
}
}
/* else return immdiately */
while (*lpNumberOfBytesWritten < nNumberOfBytesToWrite)
{
int biggestFd = -1;
fd_set event_set;
fd_set write_set;
int nbFds = 0;
biggestFd = pComm->fd_write;
if (pComm->fd_write_event > biggestFd)
biggestFd = pComm->fd_write_event;
FD_ZERO(&event_set);
FD_ZERO(&write_set);
WINPR_ASSERT(pComm->fd_write_event < FD_SETSIZE);
WINPR_ASSERT(pComm->fd_write < FD_SETSIZE);
FD_SET(pComm->fd_write_event, &event_set);
FD_SET(pComm->fd_write, &write_set);
nbFds = select(biggestFd + 1, &event_set, &write_set, nullptr, pTmaxTimeout);
if (nbFds < 0)
{
char ebuffer[256] = WINPR_C_ARRAY_INIT;
CommLog_Print(WLOG_WARN, "select() failure, errno=[%d] %s\n", errno,
winpr_strerror(errno, ebuffer, sizeof(ebuffer)));
SetLastError(ERROR_IO_DEVICE);
goto return_false;
}
if (nbFds == 0)
{
/* timeout */
SetLastError(ERROR_TIMEOUT);
goto return_false;
}
/* event_set */
if (FD_ISSET(pComm->fd_write_event, &event_set))
{
#if defined(WINPR_HAVE_SYS_EVENTFD_H)
eventfd_t event = 0;
if (eventfd_read(pComm->fd_write_event, &event) < 0)
{
if (errno == EAGAIN)
{
WINPR_ASSERT(FALSE); /* not quite sure this should ever happen */
/* keep on */
}
else
{
char ebuffer[256] = WINPR_C_ARRAY_INIT;
CommLog_Print(WLOG_WARN,
"unexpected error on reading fd_write_event, errno=[%d] %s\n",
errno, winpr_strerror(errno, ebuffer, sizeof(ebuffer)));
/* FIXME: goto return_false ? */
}
WINPR_ASSERT(errno == EAGAIN);
}
if (event == WINPR_PURGE_TXABORT)
{
SetLastError(ERROR_CANCELLED);
goto return_false;
}
WINPR_ASSERT(event == WINPR_PURGE_TXABORT); /* no other expected event so far */
#endif
}
/* write_set */
if (FD_ISSET(pComm->fd_write, &write_set))
{
ssize_t nbWritten = 0;
const BYTE* ptr = lpBuffer;
nbWritten = write(pComm->fd_write, &ptr[*lpNumberOfBytesWritten],
nNumberOfBytesToWrite - (*lpNumberOfBytesWritten));
if (nbWritten < 0)
{
char ebuffer[256] = WINPR_C_ARRAY_INIT;
CommLog_Print(WLOG_WARN,
"CommWriteFile failed after %" PRIu32
" bytes written, errno=[%d] %s\n",
*lpNumberOfBytesWritten, errno,
winpr_strerror(errno, ebuffer, sizeof(ebuffer)));
if (errno == EAGAIN)
{
/* keep on */
continue;
}
else if (errno == EBADF)
{
SetLastError(ERROR_BAD_DEVICE); /* STATUS_INVALID_DEVICE_REQUEST */
goto return_false;
}
else
{
WINPR_ASSERT(FALSE);
SetLastError(ERROR_IO_DEVICE);
goto return_false;
}
}
*lpNumberOfBytesWritten += nbWritten;
}
} /* while */
/* FIXME: this call to tcdrain() doesn't look correct and
* might hide a bug but was required while testing a serial
* printer. Its driver was expecting the modem line status
* SERIAL_MSR_DSR true after the sending which was never
* happening otherwise. A purge was also done before each
* Write operation. The serial port was opened with:
* DesiredAccess=0x0012019F. The printer worked fine with
* mstsc. */
tcdrain(pComm->fd_write);
return_true:
LeaveCriticalSection(&pComm->WriteLock);
return TRUE;
return_false:
LeaveCriticalSection(&pComm->WriteLock);
return FALSE;
}

View File

@@ -0,0 +1,759 @@
/**
* WinPR: Windows Portable Runtime
* Serial Communication API
*
* Copyright 2011 O.S. Systems Software Ltda.
* Copyright 2011 Eduardo Fiss Beloni <beloni@ossystems.com.br>
* Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <winpr/config.h>
#include <winpr/assert.h>
#include <errno.h>
#include <winpr/wlog.h>
#include "comm.h"
#include "comm_ioctl.h"
#include "comm_serial_sys.h"
#include "comm_sercx_sys.h"
#include "comm_sercx2_sys.h"
static const char* comm_ioctl_modem_status_string(ULONG status, char* buffer, size_t size);
/* NB: MS-RDPESP's recommendation:
*
* <2> Section 3.2.5.1.6: Windows Implementations use IOCTL constants
* for IoControlCode values. The content and values of the IOCTLs are
* opaque to the protocol. On the server side, the data contained in
* an IOCTL is simply packaged and sent to the client side. For
* maximum compatibility between the different versions of the Windows
* operating system, the client implementation only singles out
* critical IOCTLs and invokes the applicable Win32 port API. The
* other IOCTLS are passed directly to the client-side driver, and the
* processing of this value depends on the drivers installed on the
* client side. The values and parameters for these IOCTLS can be
* found in [MSFT-W2KDDK] Volume 2, Part 2—Serial and Parallel
* Drivers, and in [MSDN-PORTS].
*/
static BOOL s_CommDeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode, LPVOID lpInBuffer,
DWORD nInBufferSize, LPVOID lpOutBuffer, DWORD nOutBufferSize,
LPDWORD lpBytesReturned, LPOVERLAPPED lpOverlapped)
{
char buffer[128] = WINPR_C_ARRAY_INIT;
WINPR_COMM* pComm = (WINPR_COMM*)hDevice;
const SERIAL_DRIVER* pServerSerialDriver = nullptr;
if (!CommIsHandleValid(hDevice))
return FALSE;
if (lpOverlapped)
{
SetLastError(ERROR_NOT_SUPPORTED);
return FALSE;
}
if (lpBytesReturned == nullptr)
{
SetLastError(
ERROR_INVALID_PARAMETER); /* since we doesn't support lpOverlapped != nullptr */
return FALSE;
}
/* clear any previous last error */
SetLastError(ERROR_SUCCESS);
*lpBytesReturned = 0; /* will be adjusted if required ... */
CommLog_Print(WLOG_DEBUG, "CommDeviceIoControl: IoControlCode: %s [0x%08" PRIx32 "]",
_comm_serial_ioctl_name(dwIoControlCode), dwIoControlCode);
/* remoteSerialDriver to be use ...
*
* FIXME: might prefer to use an automatic rather than static structure
*/
switch (pComm->serverSerialDriverId)
{
case SerialDriverSerialSys:
pServerSerialDriver = SerialSys_s();
break;
case SerialDriverSerCxSys:
pServerSerialDriver = SerCxSys_s();
break;
case SerialDriverSerCx2Sys:
pServerSerialDriver = SerCx2Sys_s();
break;
case SerialDriverUnknown:
default:
CommLog_Print(WLOG_DEBUG, "Unknown remote serial driver (%u), using SerCx2.sys",
pComm->serverSerialDriverId);
pServerSerialDriver = SerCx2Sys_s();
break;
}
WINPR_ASSERT(pServerSerialDriver != nullptr);
switch (dwIoControlCode)
{
case IOCTL_USBPRINT_GET_1284_ID:
{
/* FIXME:
* http://msdn.microsoft.com/en-us/library/windows/hardware/ff551803(v=vs.85).aspx */
*lpBytesReturned = nOutBufferSize; /* an empty OutputBuffer will be returned */
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
return FALSE;
}
case IOCTL_SERIAL_SET_BAUD_RATE:
{
if (pServerSerialDriver->set_baud_rate)
{
SERIAL_BAUD_RATE* pBaudRate = (SERIAL_BAUD_RATE*)lpInBuffer;
WINPR_ASSERT(nInBufferSize >= sizeof(SERIAL_BAUD_RATE));
if (nInBufferSize < sizeof(SERIAL_BAUD_RATE))
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
return pServerSerialDriver->set_baud_rate(pComm, pBaudRate);
}
break;
}
case IOCTL_SERIAL_GET_BAUD_RATE:
{
if (pServerSerialDriver->get_baud_rate)
{
SERIAL_BAUD_RATE* pBaudRate = (SERIAL_BAUD_RATE*)lpOutBuffer;
WINPR_ASSERT(nOutBufferSize >= sizeof(SERIAL_BAUD_RATE));
if (nOutBufferSize < sizeof(SERIAL_BAUD_RATE))
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
if (!pServerSerialDriver->get_baud_rate(pComm, pBaudRate))
return FALSE;
*lpBytesReturned = sizeof(SERIAL_BAUD_RATE);
return TRUE;
}
break;
}
case IOCTL_SERIAL_GET_PROPERTIES:
{
if (pServerSerialDriver->get_properties)
{
COMMPROP* pProperties = (COMMPROP*)lpOutBuffer;
WINPR_ASSERT(nOutBufferSize >= sizeof(COMMPROP));
if (nOutBufferSize < sizeof(COMMPROP))
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
if (!pServerSerialDriver->get_properties(pComm, pProperties))
return FALSE;
*lpBytesReturned = sizeof(COMMPROP);
return TRUE;
}
break;
}
case IOCTL_SERIAL_SET_CHARS:
{
if (pServerSerialDriver->set_serial_chars)
{
SERIAL_CHARS* pSerialChars = (SERIAL_CHARS*)lpInBuffer;
WINPR_ASSERT(nInBufferSize >= sizeof(SERIAL_CHARS));
if (nInBufferSize < sizeof(SERIAL_CHARS))
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
return pServerSerialDriver->set_serial_chars(pComm, pSerialChars);
}
break;
}
case IOCTL_SERIAL_GET_CHARS:
{
if (pServerSerialDriver->get_serial_chars)
{
SERIAL_CHARS* pSerialChars = (SERIAL_CHARS*)lpOutBuffer;
WINPR_ASSERT(nOutBufferSize >= sizeof(SERIAL_CHARS));
if (nOutBufferSize < sizeof(SERIAL_CHARS))
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
if (!pServerSerialDriver->get_serial_chars(pComm, pSerialChars))
return FALSE;
*lpBytesReturned = sizeof(SERIAL_CHARS);
return TRUE;
}
break;
}
case IOCTL_SERIAL_SET_LINE_CONTROL:
{
if (pServerSerialDriver->set_line_control)
{
SERIAL_LINE_CONTROL* pLineControl = (SERIAL_LINE_CONTROL*)lpInBuffer;
WINPR_ASSERT(nInBufferSize >= sizeof(SERIAL_LINE_CONTROL));
if (nInBufferSize < sizeof(SERIAL_LINE_CONTROL))
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
return pServerSerialDriver->set_line_control(pComm, pLineControl);
}
break;
}
case IOCTL_SERIAL_GET_LINE_CONTROL:
{
if (pServerSerialDriver->get_line_control)
{
SERIAL_LINE_CONTROL* pLineControl = (SERIAL_LINE_CONTROL*)lpOutBuffer;
WINPR_ASSERT(nOutBufferSize >= sizeof(SERIAL_LINE_CONTROL));
if (nOutBufferSize < sizeof(SERIAL_LINE_CONTROL))
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
if (!pServerSerialDriver->get_line_control(pComm, pLineControl))
return FALSE;
*lpBytesReturned = sizeof(SERIAL_LINE_CONTROL);
return TRUE;
}
break;
}
case IOCTL_SERIAL_SET_HANDFLOW:
{
if (pServerSerialDriver->set_handflow)
{
SERIAL_HANDFLOW* pHandflow = (SERIAL_HANDFLOW*)lpInBuffer;
WINPR_ASSERT(nInBufferSize >= sizeof(SERIAL_HANDFLOW));
if (nInBufferSize < sizeof(SERIAL_HANDFLOW))
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
return pServerSerialDriver->set_handflow(pComm, pHandflow);
}
break;
}
case IOCTL_SERIAL_GET_HANDFLOW:
{
if (pServerSerialDriver->get_handflow)
{
SERIAL_HANDFLOW* pHandflow = (SERIAL_HANDFLOW*)lpOutBuffer;
WINPR_ASSERT(nOutBufferSize >= sizeof(SERIAL_HANDFLOW));
if (nOutBufferSize < sizeof(SERIAL_HANDFLOW))
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
if (!pServerSerialDriver->get_handflow(pComm, pHandflow))
return FALSE;
*lpBytesReturned = sizeof(SERIAL_HANDFLOW);
return TRUE;
}
break;
}
case IOCTL_SERIAL_SET_TIMEOUTS:
{
if (pServerSerialDriver->set_timeouts)
{
SERIAL_TIMEOUTS* pHandflow = (SERIAL_TIMEOUTS*)lpInBuffer;
WINPR_ASSERT(nInBufferSize >= sizeof(SERIAL_TIMEOUTS));
if (nInBufferSize < sizeof(SERIAL_TIMEOUTS))
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
return pServerSerialDriver->set_timeouts(pComm, pHandflow);
}
break;
}
case IOCTL_SERIAL_GET_TIMEOUTS:
{
if (pServerSerialDriver->get_timeouts)
{
SERIAL_TIMEOUTS* pHandflow = (SERIAL_TIMEOUTS*)lpOutBuffer;
WINPR_ASSERT(nOutBufferSize >= sizeof(SERIAL_TIMEOUTS));
if (nOutBufferSize < sizeof(SERIAL_TIMEOUTS))
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
if (!pServerSerialDriver->get_timeouts(pComm, pHandflow))
return FALSE;
*lpBytesReturned = sizeof(SERIAL_TIMEOUTS);
return TRUE;
}
break;
}
case IOCTL_SERIAL_SET_DTR:
{
if (pServerSerialDriver->set_dtr)
{
return pServerSerialDriver->set_dtr(pComm);
}
break;
}
case IOCTL_SERIAL_CLR_DTR:
{
if (pServerSerialDriver->clear_dtr)
{
return pServerSerialDriver->clear_dtr(pComm);
}
break;
}
case IOCTL_SERIAL_SET_RTS:
{
if (pServerSerialDriver->set_rts)
{
return pServerSerialDriver->set_rts(pComm);
}
break;
}
case IOCTL_SERIAL_CLR_RTS:
{
if (pServerSerialDriver->clear_rts)
{
return pServerSerialDriver->clear_rts(pComm);
}
break;
}
case IOCTL_SERIAL_GET_MODEMSTATUS:
{
if (pServerSerialDriver->get_modemstatus)
{
ULONG* pRegister = (ULONG*)lpOutBuffer;
WINPR_ASSERT(nOutBufferSize >= sizeof(ULONG));
if (nOutBufferSize < sizeof(ULONG))
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
if (!pServerSerialDriver->get_modemstatus(pComm, pRegister))
return FALSE;
CommLog_Print(WLOG_DEBUG, "modem status %s" PRIx32,
comm_ioctl_modem_status_string(*pRegister, buffer, sizeof(buffer)));
*lpBytesReturned = sizeof(ULONG);
return TRUE;
}
break;
}
case IOCTL_SERIAL_SET_WAIT_MASK:
{
if (pServerSerialDriver->set_wait_mask)
{
ULONG* pWaitMask = (ULONG*)lpInBuffer;
WINPR_ASSERT(nInBufferSize >= sizeof(ULONG));
if (nInBufferSize < sizeof(ULONG))
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
const BOOL rc = pServerSerialDriver->set_wait_mask(pComm, pWaitMask);
CommLog_Print(WLOG_DEBUG, "set_wait_mask %s -> %d",
CommSerialEvString(*pWaitMask, buffer, sizeof(buffer)), rc);
return rc;
}
break;
}
case IOCTL_SERIAL_GET_WAIT_MASK:
{
if (pServerSerialDriver->get_wait_mask)
{
ULONG* pWaitMask = (ULONG*)lpOutBuffer;
WINPR_ASSERT(nOutBufferSize >= sizeof(ULONG));
if (nOutBufferSize < sizeof(ULONG))
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
if (!pServerSerialDriver->get_wait_mask(pComm, pWaitMask))
return FALSE;
CommLog_Print(WLOG_DEBUG, "get_wait_mask %s",
CommSerialEvString(*pWaitMask, buffer, sizeof(buffer)));
*lpBytesReturned = sizeof(ULONG);
return TRUE;
}
break;
}
case IOCTL_SERIAL_WAIT_ON_MASK:
{
if (pServerSerialDriver->wait_on_mask)
{
ULONG* pOutputMask = (ULONG*)lpOutBuffer;
WINPR_ASSERT(nOutBufferSize >= sizeof(ULONG));
if (nOutBufferSize < sizeof(ULONG))
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
const BOOL rc = pServerSerialDriver->wait_on_mask(pComm, pOutputMask);
*lpBytesReturned = sizeof(ULONG);
CommLog_Print(WLOG_DEBUG, "wait_on_mask %s -> %d",
CommSerialEvString(*pOutputMask, buffer, sizeof(buffer)), rc);
return rc;
}
break;
}
case IOCTL_SERIAL_SET_QUEUE_SIZE:
{
if (pServerSerialDriver->set_queue_size)
{
SERIAL_QUEUE_SIZE* pQueueSize = (SERIAL_QUEUE_SIZE*)lpInBuffer;
WINPR_ASSERT(nInBufferSize >= sizeof(SERIAL_QUEUE_SIZE));
if (nInBufferSize < sizeof(SERIAL_QUEUE_SIZE))
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
return pServerSerialDriver->set_queue_size(pComm, pQueueSize);
}
break;
}
case IOCTL_SERIAL_PURGE:
{
if (pServerSerialDriver->purge)
{
ULONG* pPurgeMask = (ULONG*)lpInBuffer;
WINPR_ASSERT(nInBufferSize >= sizeof(ULONG));
if (nInBufferSize < sizeof(ULONG))
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
return pServerSerialDriver->purge(pComm, pPurgeMask);
}
break;
}
case IOCTL_SERIAL_GET_COMMSTATUS:
{
if (pServerSerialDriver->get_commstatus)
{
SERIAL_STATUS* pCommstatus = (SERIAL_STATUS*)lpOutBuffer;
WINPR_ASSERT(nOutBufferSize >= sizeof(SERIAL_STATUS));
if (nOutBufferSize < sizeof(SERIAL_STATUS))
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
if (!pServerSerialDriver->get_commstatus(pComm, pCommstatus))
return FALSE;
*lpBytesReturned = sizeof(SERIAL_STATUS);
return TRUE;
}
break;
}
case IOCTL_SERIAL_SET_BREAK_ON:
{
if (pServerSerialDriver->set_break_on)
{
return pServerSerialDriver->set_break_on(pComm);
}
break;
}
case IOCTL_SERIAL_SET_BREAK_OFF:
{
if (pServerSerialDriver->set_break_off)
{
return pServerSerialDriver->set_break_off(pComm);
}
break;
}
case IOCTL_SERIAL_SET_XOFF:
{
if (pServerSerialDriver->set_xoff)
{
return pServerSerialDriver->set_xoff(pComm);
}
break;
}
case IOCTL_SERIAL_SET_XON:
{
if (pServerSerialDriver->set_xon)
{
return pServerSerialDriver->set_xon(pComm);
}
break;
}
case IOCTL_SERIAL_GET_DTRRTS:
{
if (pServerSerialDriver->get_dtrrts)
{
ULONG* pMask = (ULONG*)lpOutBuffer;
WINPR_ASSERT(nOutBufferSize >= sizeof(ULONG));
if (nOutBufferSize < sizeof(ULONG))
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
if (!pServerSerialDriver->get_dtrrts(pComm, pMask))
return FALSE;
*lpBytesReturned = sizeof(ULONG);
return TRUE;
}
break;
}
case IOCTL_SERIAL_CONFIG_SIZE:
{
if (pServerSerialDriver->config_size)
{
ULONG* pSize = (ULONG*)lpOutBuffer;
WINPR_ASSERT(nOutBufferSize >= sizeof(ULONG));
if (nOutBufferSize < sizeof(ULONG))
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
if (!pServerSerialDriver->config_size(pComm, pSize))
return FALSE;
*lpBytesReturned = sizeof(ULONG);
return TRUE;
}
break;
}
case IOCTL_SERIAL_IMMEDIATE_CHAR:
{
if (pServerSerialDriver->immediate_char)
{
UCHAR* pChar = (UCHAR*)lpInBuffer;
WINPR_ASSERT(nInBufferSize >= sizeof(UCHAR));
if (nInBufferSize < sizeof(UCHAR))
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
return pServerSerialDriver->immediate_char(pComm, pChar);
}
break;
}
case IOCTL_SERIAL_RESET_DEVICE:
{
if (pServerSerialDriver->reset_device)
{
return pServerSerialDriver->reset_device(pComm);
}
break;
}
default:
break;
}
CommLog_Print(
WLOG_WARN, _T("unsupported IoControlCode=[0x%08" PRIX32 "] %s (remote serial driver: %s)"),
dwIoControlCode, _comm_serial_ioctl_name(dwIoControlCode), pServerSerialDriver->name);
SetLastError(ERROR_CALL_NOT_IMPLEMENTED); /* => STATUS_NOT_IMPLEMENTED */
return FALSE;
}
/**
* FIXME: to be used through winpr-io's DeviceIoControl
*
* Any previous error as returned by GetLastError is cleared.
*
* ERRORS:
* ERROR_INVALID_HANDLE
* ERROR_INVALID_PARAMETER
* ERROR_NOT_SUPPORTED lpOverlapped is not supported
* ERROR_INSUFFICIENT_BUFFER
* ERROR_CALL_NOT_IMPLEMENTED unimplemented ioctl
*/
BOOL CommDeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode, LPVOID lpInBuffer,
DWORD nInBufferSize, LPVOID lpOutBuffer, DWORD nOutBufferSize,
LPDWORD lpBytesReturned, LPOVERLAPPED lpOverlapped)
{
WINPR_COMM* pComm = (WINPR_COMM*)hDevice;
BOOL result = 0;
if (hDevice == INVALID_HANDLE_VALUE)
{
SetLastError(ERROR_INVALID_HANDLE);
return FALSE;
}
if (!CommIsHandled(hDevice))
return FALSE;
if (!pComm->fd)
{
SetLastError(ERROR_INVALID_HANDLE);
return FALSE;
}
result = s_CommDeviceIoControl(hDevice, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer,
nOutBufferSize, lpBytesReturned, lpOverlapped);
if (lpBytesReturned && *lpBytesReturned != nOutBufferSize)
{
/* This might be a hint for a bug, especially when result==TRUE */
CommLog_Print(WLOG_WARN,
"IoControlCode=[0x%08" PRIX32 "] %s: lpBytesReturned=%" PRIu32
" and nOutBufferSize=%" PRIu32 " are different!",
dwIoControlCode, _comm_serial_ioctl_name(dwIoControlCode), *lpBytesReturned,
nOutBufferSize);
}
if (pComm->permissive)
{
if (!result)
{
CommLog_Print(WLOG_WARN,
"[permissive]: IoControlCode=[0x%08" PRIX32 "] %s failed, ignoring",
dwIoControlCode, _comm_serial_ioctl_name(dwIoControlCode));
}
return TRUE; /* always! */
}
return result;
}
int comm_ioctl_tcsetattr(int fd, int optional_actions, const struct termios* termios_p)
{
struct termios currentState = WINPR_C_ARRAY_INIT;
size_t count = 0;
do
{
const int src = tcsetattr(fd, optional_actions, termios_p);
if (src < 0)
{
char buffer[64] = WINPR_C_ARRAY_INIT;
CommLog_Print(WLOG_WARN, "[%" PRIuz "] tcsetattr failure, errno: %s [%d]", count,
winpr_strerror(errno, buffer, sizeof(buffer)), errno);
return src;
}
/* NB: tcsetattr() can succeed even if not all changes have been applied. */
const int rrc = tcgetattr(fd, &currentState);
if (rrc < 0)
{
char buffer[64] = WINPR_C_ARRAY_INIT;
CommLog_Print(WLOG_WARN, "[%" PRIuz "] tcgetattr failure, errno: %s [%d]", count,
winpr_strerror(errno, buffer, sizeof(buffer)), errno);
return rrc;
}
// NOLINTNEXTLINE(bugprone-suspicious-memory-comparison,cert-exp42-c,cert-flp37-c)
} while ((memcmp(&currentState, termios_p, sizeof(struct termios)) != 0) && (count++ < 2));
return 0;
}
static const char* comm_ioctl_modem_flag_str(ULONG flag)
{
switch (flag)
{
case SERIAL_MSR_DCTS:
return "SERIAL_MSR_DCTS";
case SERIAL_MSR_DDSR:
return "SERIAL_MSR_DDSR";
case SERIAL_MSR_TERI:
return "SERIAL_MSR_TERI";
case SERIAL_MSR_DDCD:
return "SERIAL_MSR_DDCD";
case SERIAL_MSR_CTS:
return "SERIAL_MSR_CTS";
case SERIAL_MSR_DSR:
return "SERIAL_MSR_DSR";
case SERIAL_MSR_RI:
return "SERIAL_MSR_RI";
case SERIAL_MSR_DCD:
return "SERIAL_MSR_DCD";
default:
return "SERIAL_MSR_UNKNOWN";
}
}
const char* comm_ioctl_modem_status_string(ULONG status, char* buffer, size_t size)
{
const ULONG flags[] = { SERIAL_MSR_DCTS, SERIAL_MSR_DDSR, SERIAL_MSR_TERI, SERIAL_MSR_DDCD,
SERIAL_MSR_CTS, SERIAL_MSR_DSR, SERIAL_MSR_RI, SERIAL_MSR_DCD
};
winpr_str_append("{", buffer, size, "");
const char* sep = "";
for (size_t x = 0; x < ARRAYSIZE(flags); x++)
{
const ULONG flag = flags[x];
if (status & flag)
{
winpr_str_append(comm_ioctl_modem_flag_str(flag), buffer, size, sep);
sep = "|";
}
}
char number[32] = WINPR_C_ARRAY_INIT;
(void)_snprintf(number, sizeof(number), "}[0x%08" PRIx32 "]", status);
winpr_str_append(number, buffer, size, "");
return buffer;
}

View File

@@ -0,0 +1,232 @@
/**
* WinPR: Windows Portable Runtime
* Serial Communication API
*
* Copyright 2011 O.S. Systems Software Ltda.
* Copyright 2011 Eduardo Fiss Beloni <beloni@ossystems.com.br>
* Copyright 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WINPR_COMM_IOCTL_H_
#define WINPR_COMM_IOCTL_H_
#include <termios.h>
#include <winpr/io.h>
#include <winpr/tchar.h>
#include <winpr/wtypes.h>
#include "comm.h"
/* Serial I/O Request Interface: http://msdn.microsoft.com/en-us/library/dn265347%28v=vs.85%29.aspx
* Ntddser.h http://msdn.microsoft.com/en-us/cc308432.aspx
* Ntddpar.h http://msdn.microsoft.com/en-us/cc308431.aspx
*/
#ifdef __cplusplus
extern "C"
{
#endif
/* TODO: defines and types below are very similar to those in comm.h, keep only
* those that differ more than the names */
#define STOP_BIT_1 0
#define STOP_BITS_1_5 1
#define STOP_BITS_2 2
#define NO_PARITY 0
#define ODD_PARITY 1
#define EVEN_PARITY 2
#define MARK_PARITY 3
#define SPACE_PARITY 4
typedef struct
{
ULONG BaudRate;
} SERIAL_BAUD_RATE, *PSERIAL_BAUD_RATE;
typedef struct
{
UCHAR EofChar;
UCHAR ErrorChar;
UCHAR BreakChar;
UCHAR EventChar;
UCHAR XonChar;
UCHAR XoffChar;
} SERIAL_CHARS, *PSERIAL_CHARS;
typedef struct
{
UCHAR StopBits;
UCHAR Parity;
UCHAR WordLength;
} SERIAL_LINE_CONTROL, *PSERIAL_LINE_CONTROL;
typedef struct
{
ULONG ControlHandShake;
ULONG FlowReplace;
ULONG XonLimit;
ULONG XoffLimit;
} SERIAL_HANDFLOW, *PSERIAL_HANDFLOW;
#define SERIAL_DTR_MASK ((ULONG)0x03)
#define SERIAL_DTR_CONTROL ((ULONG)0x01)
#define SERIAL_DTR_HANDSHAKE ((ULONG)0x02)
#define SERIAL_CTS_HANDSHAKE ((ULONG)0x08)
#define SERIAL_DSR_HANDSHAKE ((ULONG)0x10)
#define SERIAL_DCD_HANDSHAKE ((ULONG)0x20)
#define SERIAL_OUT_HANDSHAKEMASK ((ULONG)0x38)
#define SERIAL_DSR_SENSITIVITY ((ULONG)0x40)
#define SERIAL_ERROR_ABORT ((ULONG)0x80000000)
#define SERIAL_CONTROL_INVALID ((ULONG)0x7fffff84)
#define SERIAL_AUTO_TRANSMIT ((ULONG)0x01)
#define SERIAL_AUTO_RECEIVE ((ULONG)0x02)
#define SERIAL_ERROR_CHAR ((ULONG)0x04)
#define SERIAL_NULL_STRIPPING ((ULONG)0x08)
#define SERIAL_BREAK_CHAR ((ULONG)0x10)
#define SERIAL_RTS_MASK ((ULONG)0xc0)
#define SERIAL_RTS_CONTROL ((ULONG)0x40)
#define SERIAL_RTS_HANDSHAKE ((ULONG)0x80)
#define SERIAL_TRANSMIT_TOGGLE ((ULONG)0xc0)
#define SERIAL_XOFF_CONTINUE ((ULONG)0x80000000)
#define SERIAL_FLOW_INVALID ((ULONG)0x7fffff20)
#define SERIAL_SP_SERIALCOMM ((ULONG)0x00000001)
#define SERIAL_SP_UNSPECIFIED ((ULONG)0x00000000)
#define SERIAL_SP_RS232 ((ULONG)0x00000001)
#define SERIAL_SP_PARALLEL ((ULONG)0x00000002)
#define SERIAL_SP_RS422 ((ULONG)0x00000003)
#define SERIAL_SP_RS423 ((ULONG)0x00000004)
#define SERIAL_SP_RS449 ((ULONG)0x00000005)
#define SERIAL_SP_MODEM ((ULONG)0x00000006)
#define SERIAL_SP_FAX ((ULONG)0x00000021)
#define SERIAL_SP_SCANNER ((ULONG)0x00000022)
#define SERIAL_SP_BRIDGE ((ULONG)0x00000100)
#define SERIAL_SP_LAT ((ULONG)0x00000101)
#define SERIAL_SP_TELNET ((ULONG)0x00000102)
#define SERIAL_SP_X25 ((ULONG)0x00000103)
typedef struct
{
ULONG ReadIntervalTimeout;
ULONG ReadTotalTimeoutMultiplier;
ULONG ReadTotalTimeoutConstant;
ULONG WriteTotalTimeoutMultiplier;
ULONG WriteTotalTimeoutConstant;
} SERIAL_TIMEOUTS, *PSERIAL_TIMEOUTS;
#define SERIAL_MSR_DCTS 0x01
#define SERIAL_MSR_DDSR 0x02
#define SERIAL_MSR_TERI 0x04
#define SERIAL_MSR_DDCD 0x08
#define SERIAL_MSR_CTS 0x10
#define SERIAL_MSR_DSR 0x20
#define SERIAL_MSR_RI 0x40
#define SERIAL_MSR_DCD 0x80
typedef struct
{
ULONG InSize;
ULONG OutSize;
} SERIAL_QUEUE_SIZE, *PSERIAL_QUEUE_SIZE;
#define SERIAL_PURGE_TXABORT 0x00000001
#define SERIAL_PURGE_RXABORT 0x00000002
#define SERIAL_PURGE_TXCLEAR 0x00000004
#define SERIAL_PURGE_RXCLEAR 0x00000008
typedef struct
{
ULONG Errors;
ULONG HoldReasons;
ULONG AmountInInQueue;
ULONG AmountInOutQueue;
BOOLEAN EofReceived;
BOOLEAN WaitForImmediate;
} SERIAL_STATUS, *PSERIAL_STATUS;
#define SERIAL_TX_WAITING_FOR_CTS ((ULONG)0x00000001)
#define SERIAL_TX_WAITING_FOR_DSR ((ULONG)0x00000002)
#define SERIAL_TX_WAITING_FOR_DCD ((ULONG)0x00000004)
#define SERIAL_TX_WAITING_FOR_XON ((ULONG)0x00000008)
#define SERIAL_TX_WAITING_XOFF_SENT ((ULONG)0x00000010)
#define SERIAL_TX_WAITING_ON_BREAK ((ULONG)0x00000020)
#define SERIAL_RX_WAITING_FOR_DSR ((ULONG)0x00000040)
#define SERIAL_ERROR_BREAK ((ULONG)0x00000001)
#define SERIAL_ERROR_FRAMING ((ULONG)0x00000002)
#define SERIAL_ERROR_OVERRUN ((ULONG)0x00000004)
#define SERIAL_ERROR_QUEUEOVERRUN ((ULONG)0x00000008)
#define SERIAL_ERROR_PARITY ((ULONG)0x00000010)
#define SERIAL_DTR_STATE ((ULONG)0x00000001)
#define SERIAL_RTS_STATE ((ULONG)0x00000002)
#define SERIAL_CTS_STATE ((ULONG)0x00000010)
#define SERIAL_DSR_STATE ((ULONG)0x00000020)
#define SERIAL_RI_STATE ((ULONG)0x00000040)
#define SERIAL_DCD_STATE ((ULONG)0x00000080)
/**
* A function might be nullptr if not supported by the underlying driver.
*
* FIXME: better have to use input and output buffers for all functions?
*/
typedef struct
{
SERIAL_DRIVER_ID id;
TCHAR* name;
BOOL (*set_baud_rate)(WINPR_COMM* pComm, const SERIAL_BAUD_RATE* pBaudRate);
BOOL (*get_baud_rate)(WINPR_COMM* pComm, SERIAL_BAUD_RATE* pBaudRate);
BOOL (*get_properties)(WINPR_COMM* pComm, COMMPROP* pProperties);
BOOL (*set_serial_chars)(WINPR_COMM* pComm, const SERIAL_CHARS* pSerialChars);
BOOL (*get_serial_chars)(WINPR_COMM* pComm, SERIAL_CHARS* pSerialChars);
BOOL (*set_line_control)(WINPR_COMM* pComm, const SERIAL_LINE_CONTROL* pLineControl);
BOOL (*get_line_control)(WINPR_COMM* pComm, SERIAL_LINE_CONTROL* pLineControl);
BOOL (*set_handflow)(WINPR_COMM* pComm, const SERIAL_HANDFLOW* pHandflow);
BOOL (*get_handflow)(WINPR_COMM* pComm, SERIAL_HANDFLOW* pHandflow);
BOOL (*set_timeouts)(WINPR_COMM* pComm, const SERIAL_TIMEOUTS* pTimeouts);
BOOL (*get_timeouts)(WINPR_COMM* pComm, SERIAL_TIMEOUTS* pTimeouts);
BOOL (*set_dtr)(WINPR_COMM* pComm);
BOOL (*clear_dtr)(WINPR_COMM* pComm);
BOOL (*set_rts)(WINPR_COMM* pComm);
BOOL (*clear_rts)(WINPR_COMM* pComm);
BOOL (*get_modemstatus)(WINPR_COMM* pComm, ULONG* pRegister);
BOOL (*set_wait_mask)(WINPR_COMM* pComm, const ULONG* pWaitMask);
BOOL (*get_wait_mask)(WINPR_COMM* pComm, ULONG* pWaitMask);
BOOL (*wait_on_mask)(WINPR_COMM* pComm, ULONG* pOutputMask);
BOOL (*set_queue_size)(WINPR_COMM* pComm, const SERIAL_QUEUE_SIZE* pQueueSize);
BOOL (*purge)(WINPR_COMM* pComm, const ULONG* pPurgeMask);
BOOL (*get_commstatus)(WINPR_COMM* pComm, SERIAL_STATUS* pCommstatus);
BOOL (*set_break_on)(WINPR_COMM* pComm);
BOOL (*set_break_off)(WINPR_COMM* pComm);
BOOL (*set_xoff)(WINPR_COMM* pComm);
BOOL (*set_xon)(WINPR_COMM* pComm);
BOOL (*get_dtrrts)(WINPR_COMM* pComm, ULONG* pMask);
BOOL (*config_size)(WINPR_COMM* pComm, ULONG* pSize);
BOOL (*immediate_char)(WINPR_COMM* pComm, const UCHAR* pChar);
BOOL (*reset_device)(WINPR_COMM* pComm);
} SERIAL_DRIVER;
int comm_ioctl_tcsetattr(int fd, int optional_actions, const struct termios* termios_p);
#ifdef __cplusplus
}
#endif
#endif /* WINPR_COMM_IOCTL_H_ */

View File

@@ -0,0 +1,87 @@
/**
* WinPR: Windows Portable Runtime
* Serial Communication API - Dummy implementation
*
* Copyright 2024 Armin Novak <anovak@thincast.com>
* Copyright 2024 Thincast Technologies GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <winpr/comm.h>
#include "comm_ioctl.h"
#include <../log.h>
#define TAG WINPR_TAG("comm")
BOOL CommDeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode, LPVOID lpInBuffer,
DWORD nInBufferSize, LPVOID lpOutBuffer, DWORD nOutBufferSize,
LPDWORD lpBytesReturned, LPOVERLAPPED lpOverlapped)
{
WINPR_UNUSED(hDevice);
WINPR_UNUSED(dwIoControlCode);
WINPR_UNUSED(lpInBuffer);
WINPR_UNUSED(nInBufferSize);
WINPR_UNUSED(lpOutBuffer);
WINPR_UNUSED(nOutBufferSize);
WINPR_UNUSED(lpBytesReturned);
WINPR_UNUSED(lpOverlapped);
WLog_ERR(TAG, "TODO: Function not implemented for this platform");
return FALSE;
}
int comm_ioctl_tcsetattr(int fd, int optional_actions, const struct termios* termios_p)
{
WINPR_UNUSED(fd);
WINPR_UNUSED(optional_actions);
WINPR_UNUSED(termios_p);
WLog_ERR(TAG, "TODO: Function not implemented for this platform");
return -1;
}
BOOL _comm_set_permissive(HANDLE hDevice, BOOL permissive)
{
WINPR_UNUSED(hDevice);
WINPR_UNUSED(permissive);
WLog_ERR(TAG, "TODO: Function not implemented for this platform");
return FALSE;
}
BOOL CommReadFile(HANDLE hDevice, LPVOID lpBuffer, DWORD nNumberOfBytesToRead,
LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
WINPR_UNUSED(hDevice);
WINPR_UNUSED(lpBuffer);
WINPR_UNUSED(nNumberOfBytesToRead);
WINPR_UNUSED(lpNumberOfBytesRead);
WINPR_UNUSED(lpOverlapped);
WLog_ERR(TAG, "TODO: Function not implemented for this platform");
return FALSE;
}
BOOL CommWriteFile(HANDLE hDevice, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped)
{
WINPR_UNUSED(hDevice);
WINPR_UNUSED(lpBuffer);
WINPR_UNUSED(nNumberOfBytesToWrite);
WINPR_UNUSED(lpNumberOfBytesWritten);
WINPR_UNUSED(lpOverlapped);
WLog_ERR(TAG, "TODO: Function not implemented for this platform");
return FALSE;
}

View File

@@ -0,0 +1,210 @@
/**
* WinPR: Windows Portable Runtime
* Serial Communication API
*
* Copyright 2011 O.S. Systems Software Ltda.
* Copyright 2011 Eduardo Fiss Beloni <beloni@ossystems.com.br>
* Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <winpr/assert.h>
#include <winpr/wlog.h>
#include "comm_serial_sys.h"
#include "comm_sercx_sys.h"
#include "comm_sercx2_sys.h"
/* http://msdn.microsoft.com/en-us/library/dn265347%28v=vs.85%29.aspx
*
* SerCx2 does not support special characters. SerCx2 always completes
* an IOCTL_SERIAL_SET_CHARS request with a STATUS_SUCCESS status
* code, but does not set any special characters or perform any other
* operation in response to this request. For an
* IOCTL_SERIAL_GET_CHARS request, SerCx2 sets all the character
* values in the SERIAL_CHARS structure to null, and completes the
* request with a STATUS_SUCCESS status code.
*/
static BOOL set_serial_chars(WINPR_ATTR_UNUSED WINPR_COMM* pComm,
WINPR_ATTR_UNUSED const SERIAL_CHARS* pSerialChars)
{
WINPR_ASSERT(pComm);
WINPR_ASSERT(pSerialChars);
return TRUE;
}
static BOOL get_serial_chars(WINPR_ATTR_UNUSED WINPR_COMM* pComm, SERIAL_CHARS* pSerialChars)
{
WINPR_ASSERT(pComm);
WINPR_ASSERT(pSerialChars);
ZeroMemory(pSerialChars, sizeof(SERIAL_CHARS));
return TRUE;
}
/* http://msdn.microsoft.com/en-us/library/windows/hardware/hh439605%28v=vs.85%29.aspx */
/* FIXME: only using the Serial.sys' events, complete the support of the remaining events */
static const ULONG SERCX2_SYS_SUPPORTED_EV_MASK =
SERIAL_EV_RXCHAR | SERIAL_EV_RXFLAG | SERIAL_EV_TXEMPTY | SERIAL_EV_CTS | SERIAL_EV_DSR |
SERIAL_EV_RLSD | SERIAL_EV_BREAK | SERIAL_EV_ERR | SERIAL_EV_RING |
/* SERIAL_EV_PERR | */
SERIAL_EV_RX80FULL /*|
SERIAL_EV_EVENT1 |
SERIAL_EV_EVENT2*/
;
/* use Serial.sys for basis (not SerCx.sys) */
static BOOL set_wait_mask(WINPR_COMM* pComm, const ULONG* pWaitMask)
{
const SERIAL_DRIVER* pSerialSys = SerialSys_s();
WINPR_ASSERT(pComm);
WINPR_ASSERT(pWaitMask);
WINPR_ASSERT(pSerialSys);
const ULONG possibleMask = *pWaitMask & SERCX2_SYS_SUPPORTED_EV_MASK;
if (possibleMask != *pWaitMask)
{
CommLog_Print(WLOG_WARN,
"Not all wait events supported (SerCx2.sys), requested events= 0x%08" PRIX32
", possible events= 0x%08" PRIX32 "",
*pWaitMask, possibleMask);
/* FIXME: shall we really set the possibleMask and return FALSE? */
pComm->WaitEventMask = possibleMask;
return FALSE;
}
/* NB: All events that are supported by SerCx.sys are supported by Serial.sys*/
return pSerialSys->set_wait_mask(pComm, pWaitMask);
}
static BOOL purge(WINPR_COMM* pComm, const ULONG* pPurgeMask)
{
const SERIAL_DRIVER* pSerialSys = SerialSys_s();
WINPR_ASSERT(pComm);
WINPR_ASSERT(pPurgeMask);
WINPR_ASSERT(pSerialSys);
/* http://msdn.microsoft.com/en-us/library/windows/hardware/ff546655%28v=vs.85%29.aspx */
if ((*pPurgeMask & SERIAL_PURGE_RXCLEAR) && !(*pPurgeMask & SERIAL_PURGE_RXABORT))
{
CommLog_Print(WLOG_WARN,
"Expecting SERIAL_PURGE_RXABORT since SERIAL_PURGE_RXCLEAR is set");
SetLastError(ERROR_INVALID_DEVICE_OBJECT_PARAMETER);
return FALSE;
}
if ((*pPurgeMask & SERIAL_PURGE_TXCLEAR) && !(*pPurgeMask & SERIAL_PURGE_TXABORT))
{
CommLog_Print(WLOG_WARN,
"Expecting SERIAL_PURGE_TXABORT since SERIAL_PURGE_TXCLEAR is set");
SetLastError(ERROR_INVALID_DEVICE_OBJECT_PARAMETER);
return FALSE;
}
return pSerialSys->purge(pComm, pPurgeMask);
}
/* specific functions only */
static SERIAL_DRIVER SerCx2Sys = {
.id = SerialDriverSerCx2Sys,
.name = _T("SerCx2.sys"),
.set_baud_rate = nullptr,
.get_baud_rate = nullptr,
.get_properties = nullptr,
.set_serial_chars = set_serial_chars,
.get_serial_chars = get_serial_chars,
.set_line_control = nullptr,
.get_line_control = nullptr,
.set_handflow = nullptr,
.get_handflow = nullptr,
.set_timeouts = nullptr,
.get_timeouts = nullptr,
.set_dtr = nullptr,
.clear_dtr = nullptr,
.set_rts = nullptr,
.clear_rts = nullptr,
.get_modemstatus = nullptr,
.set_wait_mask = set_wait_mask,
.get_wait_mask = nullptr,
.wait_on_mask = nullptr,
.set_queue_size = nullptr,
.purge = purge,
.get_commstatus = nullptr,
.set_break_on = nullptr,
.set_break_off = nullptr,
.set_xoff = nullptr, /* not supported by SerCx2.sys */
.set_xon = nullptr, /* not supported by SerCx2.sys */
.get_dtrrts = nullptr,
.config_size = nullptr, /* not supported by SerCx2.sys */
.immediate_char = nullptr, /* not supported by SerCx2.sys */
.reset_device = nullptr, /* not supported by SerCx2.sys */
};
const SERIAL_DRIVER* SerCx2Sys_s(void)
{
/* SerCx2Sys completed with inherited functions from SerialSys or SerCxSys */
const SERIAL_DRIVER* pSerialSys = SerialSys_s();
const SERIAL_DRIVER* pSerCxSys = SerCxSys_s();
if (!pSerialSys || !pSerCxSys)
return nullptr;
SerCx2Sys.set_baud_rate = pSerialSys->set_baud_rate;
SerCx2Sys.get_baud_rate = pSerialSys->get_baud_rate;
SerCx2Sys.get_properties = pSerialSys->get_properties;
SerCx2Sys.set_line_control = pSerCxSys->set_line_control;
SerCx2Sys.get_line_control = pSerCxSys->get_line_control;
/* Only SERIAL_CTS_HANDSHAKE, SERIAL_RTS_CONTROL and SERIAL_RTS_HANDSHAKE flags are really
* required by SerCx2.sys http://msdn.microsoft.com/en-us/library/jj680685%28v=vs.85%29.aspx
*/
SerCx2Sys.set_handflow = pSerialSys->set_handflow;
SerCx2Sys.get_handflow = pSerialSys->get_handflow;
SerCx2Sys.set_timeouts = pSerialSys->set_timeouts;
SerCx2Sys.get_timeouts = pSerialSys->get_timeouts;
SerCx2Sys.set_dtr = pSerialSys->set_dtr;
SerCx2Sys.clear_dtr = pSerialSys->clear_dtr;
SerCx2Sys.set_rts = pSerialSys->set_rts;
SerCx2Sys.clear_rts = pSerialSys->clear_rts;
SerCx2Sys.get_modemstatus = pSerialSys->get_modemstatus;
SerCx2Sys.set_wait_mask = pSerialSys->set_wait_mask;
SerCx2Sys.get_wait_mask = pSerialSys->get_wait_mask;
SerCx2Sys.wait_on_mask = pSerialSys->wait_on_mask;
SerCx2Sys.set_queue_size = pSerialSys->set_queue_size;
SerCx2Sys.get_commstatus = pSerialSys->get_commstatus;
SerCx2Sys.set_break_on = pSerialSys->set_break_on;
SerCx2Sys.set_break_off = pSerialSys->set_break_off;
SerCx2Sys.get_dtrrts = pSerialSys->get_dtrrts;
return &SerCx2Sys;
}

Some files were not shown because too many files have changed in this diff Show More